简体   繁体   English

默认登录用户到SQL Server列

[英]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. 我尝试了system_user ,但是显示了从表中选择时登录的用户。

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. 您基本上在其中一个列上创建了默认约束 ,并使用SUSER_NAME()函数将其填充到当前登录的用户。

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: 并且您没有CreatedBy指定显式值,该列填充了SUSER_NAME()函数中的值,您可以通过从表中选择来检查该值:

SELECT * FROM dbo.DemoTable

Read more about SUSER_NAME() and a few related functions (like SUSER_ID() ) on TechNet. 在TechNet上阅读有关SUSER_NAME()和一些相关函数 (如SUSER_ID() )的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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