Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Display the username in a column

Tags:

sql

sql-server

We have a SQL Server 2012 database that 4 developers use, lets call them, user1, user2, user3, user4.

I want to create a column in one of the tables lets call the column User_Input, this column needs to show the username of the developer who insert any data, is this possible? For example if user2 inserted a new record, the column User_Input should display user2.

Please let me know if SQL Server does not support that, and if there is any other solution cause I searched the @@ functions for SQL Server and non of them seems to get the username.

like image 674
user3221917 Avatar asked Mar 07 '14 16:03

user3221917


People also ask

How do I display a username in SQL?

SQL Server USER_NAME() Function The USER_NAME() function returns the database user name based on the specified id. If no id is specified, this function will return the name of the current user.

How do I show column names in SQL?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'

How do I find the SID username in SQL Server?

To find out these groups run the query: execute as login = 'LCF\jmp' select distinct name from sys. login_token where principal_id > 0 and type = 'WINDOWS GROUP'; And mind that it's not "orphaned", it need not to have it's sid mapped to server to be able to connect to server, Windows groups sid s are enough.

How can check current user in SQL Server?

The CURRENT_USER function returns the name of the current user in the SQL Server database.


Video Answer


1 Answers

SYSTEM_USER function will return the login name of the user.

You can test it out with this statement: SELECT SYSTEM_USER

The MSDN documentation for SYSTEM_USER states:

You can use the SYSTEM_USER function with DEFAULT constraints in the CREATE TABLE and ALTER TABLE statements. You can also use it as any standard function.

Here is a quick example of how to create a table with DEFAULT constraint that inserts the SYSTEM_USER into the User_Input column.

CREATE TABLE MyTable 
(
   ID int, 
   Value varchar(30), 
   User_Input varchar(200) DEFAULT SYSTEM_USER
)   
like image 72
Adam Porad Avatar answered Oct 12 '22 04:10

Adam Porad