如何创建一个列,其中包含当前在表中创建行的用户的默认值?
我尝试了system_user ,但是显示了从表中选择时登录的用户。
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.
最满意答案
尝试这样的事情:
CREATE TABLE DemoTable ( ID INT IDENTITY(1,1), SomeValue VARCHAR(50), CreatedBy VARCHAR(50) CONSTRAINT DF_DemoTable_CreatedBy DEFAULT(SUSER_NAME()) )您基本上在其中一个列上创建了默认约束 ,并使用SUSER_NAME()函数将其填充到当前登录的用户。
然后,当您将值插入该表时:
INSERT INTO dbo.DemoTable(SomeValue) VALUES('Some Value')并且您没有为CreatedBy指定显式值,该列填充了SUSER_NAME()函数中的值,您可以通过从表中选择来检查该值:
SELECT * FROM dbo.DemoTable在TechNet上阅读有关SUSER_NAME()和一些相关函数 (如SUSER_ID() )的更多信息。
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.DemoTableRead more about SUSER_NAME() and a few related functions (like SUSER_ID()) on TechNet.
更多推荐
发布评论