Open In App

SYSTEM_USER() Function in SQL Server

Last Updated : 19 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

SYSTEM_USER() function :
This function in SQL Server is used to return the current user’s login name.

Features :

  • This function is used to find the current user’s login name.
  • This function comes under Advanced Functions.
  • This function doesn’t accept any parameter.

Syntax :

SYSTEM_USER;

Parameter :
This method doesn’t accept any parameter.

Returns :
It returns the current user’s login name.

Example-1 :
Using SYSTEM_USER() function and getting the current user’s login name.

SELECT SYSTEM_USER;

Output :

nidhi

Example-2 :
Using SYSTEM_USER as a default value in the below example and getting the output.
 

CREATE TABLE user01
(  
user_id int IDENTITY(100, 2) NOT NULL,
customer_id int NOT NULL,
user_name char(50) NOT NULL DEFAULT SYSTEM_USER
);  
INSERT user01(customer_id)  
VALUES (101);

INSERT user01(customer_id)  
VALUES (102);

SELECT * FROM user01; 

Output :

 

S.No. user_id customer_id user_name
1 100 101 nidhi
2 101 102 nidhi

Here, firstly you need to create a table then insert values into it then generate the required output using SYSTEM_USER function as a default value.

Note : For running above code use sql server compiler, you can also use a online compiler.

Example-3 :
Using SYSTEM_USER() function and impersonating user ‘Geek’.
 

SELECT SYSTEM_USER;  
EXECUTE AS USER = 'Geek';  
SELECT SYSTEM_USER;  

Output :

nidhi
Geek

Here, we are impersonating user as ‘Geek’, then calling SYSTEM_USER function to get the current user’s name.

Example-4 :
Using SYSTEM_USER() function for impersonating user ‘Geek’ then again reverting the code to get the previous current user.
 

SELECT SYSTEM_USER;  
EXECUTE AS USER = 'Geek';  
SELECT SYSTEM_USER;  
REVERT;
SELECT SYSTEM_USER;

Output :

nidhi
Geek
nidhi

Application :
This function is used to find the current user’s login name.
 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads