CURRENT_USER() Function in SQL Server
CURRENT_USER() function :
This function in SQL Server is used to return the current user’s name in the database of SQL Server in use.
Features :
- This function is used to find the current user’s name.
- This function comes under Advanced Functions.
- This function doesn’t accept any parameter.
Syntax :
CURRENT_USER
Parameter : This method does not accept any parameter.
Returns : It returns the current user’s name in the database of SQL Server which is in use.
Example-1 :
Using CURRENT_USER () function and getting the current user’s name.
SELECT CURRENT_USER;
Output :
nidhi
Example-2 :
Using CURRENT_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 CURRENT_USER
);
Inserting values in the table –
INSERT user01(customer_id)
VALUES (101), (102);
Displaying the contents of the table –
SELECT *
FROM user01;
Output :
|
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 CURRENT_USER function as a default value.
Note: For running above code use SQL server compiler, you can also use an online compiler.
Example-3 :
Using CURRENT_USER () function and impersonating user ‘Geek’.
SELECT CURRENT_USER;
EXECUTE AS USER = 'Geek';
SELECT CURRENT_USER;
Output :
nidhi
Geek
Here, we are impersonating user as ‘Geek’, then calling CURRENT_USER function to get the current user’s name.
Example-4 :
Using CURRENT_USER () function for impersonating user ‘Geek’ then again reverting the code to get the previous current user.
SELECT CURRENT_USER;
EXECUTE AS USER = 'Geek';
SELECT CURRENT_USER;
REVERT;
SELECT CURRENT_USER;
Output :
nidhi
Geek
nidhi
Application :
- This function is used to find the current user’s name in the database of the SQL server.
Last Updated :
15 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...