SQL Server USER_NAME() Function

SQL Server USER_NAME() function returns a database user name for the specified user Id or returns the name of the current logged in user.

USER_NAME([uid])

Parameters

uid: The user id uid column associated with a database user in the sysusers table.

Return Value

Returns the user name of nvarchar(128) type.

Note: Usernames and their corresponding ids are stored in the sysusers table in the master database. The system tables has been mapped to system views in SQL Server 2015 onwards. The sysusers table is mapped to sys.database_principals view.

In the following example, the USER_NAME() returns the database user name whose Id is 7. You can validate this from the above sysusers table.

Example: USER_NAME()
SELECT USER_NAME(7) AS Result;

The following calls the USER_NAME() function without passing an Id parameter which returns the current user name.

Example: USER_NAME()
SELECT USER_NAME() AS Result;