SQL USER_NAME()
The USER_NAME() function in SQL Server is used to return the database username associated with the current session. It is commonly used for logging, auditing, and security-related tasks to determine which user is executing a query.
In this tutorial, we will explore the USER_NAME function, its syntax, and practical examples demonstrating its usage.
Syntax of SQL USER_NAME Function
The basic syntax of the USER_NAME() function is as follows:
</>
Copy
USER_NAME([id])
Parameters:
id(optional) – The ID of the user in the system catalog. If omitted, it returns the current user’s name.
Return Value: This function returns the username as a string.
Step-by-Step Examples Using SQL USER_NAME
1 Getting the Current Logged-in User
To retrieve the username of the currently connected user, use the following query:
</>
Copy
SELECT USER_NAME() AS user_name_1;
Explanation:
- The
USER_NAME()function returns the username of the session executing the query. - The alias
user_name_1is used to display the result in a readable format.
Example Output:
