How do you use the SYSTEM_USER function to retrieve the current user name?
Posted by TinaGrn
Last Updated: June 03, 2024
In SQL Server, the SYSTEM_USER function is used to retrieve the name of the current user or the login name of the user connected to the SQL Server instance. You can use it in a SQL query as follows:
SELECT SYSTEM_USER AS CurrentUserName;
This will return the currently logged-in user's name as a result in a single row with a column heading of CurrentUserName. If you want to include more context or additional information alongside the current user, you can combine it with other columns or use it within a more complex query. For example, you might want to get the current user name along with the current database:
SELECT DB_NAME() AS CurrentDatabase, SYSTEM_USER AS CurrentUserName;
This will output both the name of the current database and the user name of the person executing the query. SYSTEM_USER can also be used in other contexts, such as in a WHERE clause, to filter results based on the current user.