USER_ID() and USER_NAME() in SQL Server

You can pass a name string into USER_ID() function and get the current database ID for that name. This is very useful when we are accessing the system tables and need to check names against group membership or permission value.

And USER_NAME() is just opposite of the USER_ID function. You pass it as a valid database user id, and this function returns the name of that user.

You can see the all users for the your database in Security–>Users( see picture)


SELECT USER_ID(‘guest’) as [userid]

above query return the user id of the ‘guest’ user of the database, output will be:

Now see this query:

SELECT USER_NAME(2) as [user name]

Output will be:
user name