简体   繁体   中英

Default logged in user to SQL Server column

How can I create a column with a default value of the user that created the row at the time in the table?

I tried system_user , but that shows who is logged in when selecting from the table.

Try something like this:

CREATE TABLE DemoTable
(
    ID INT IDENTITY(1,1), 
    SomeValue VARCHAR(50), 
    CreatedBy VARCHAR(50) 
        CONSTRAINT DF_DemoTable_CreatedBy DEFAULT(SUSER_NAME())
) 

You basically create a default constraint on one of your columns, and you use the SUSER_NAME() function to populate it with the currently logged in user.

When you then insert values into that table:

INSERT INTO dbo.DemoTable(SomeValue) VALUES('Some Value')

and you don't specify an explicit value for CreatedBy , that column is filled with the value from the SUSER_NAME() function, which you can check by selecting from the table:

SELECT * FROM dbo.DemoTable

Read more about SUSER_NAME() and a few related functions (like SUSER_ID() ) on TechNet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM