开发者

How to save current SQL Server user to custom table through c# client?

I use С# Express with Entity Framework. And not very good in SQL Server scripting.

So, I have this table

CREATE TABLE DataTable
(
  Id                INT              NOT NULL  ,
  Value             VARCHAR(20)          NULL  ,
  Author            ???????????      NOT NULL  ,
  开发者_StackOverflow社区CreateTime        DATETIME         NOT NULL  ,  
  CONSTRAINT PK_DataTable PRIMARY KEY CLUSTERED (num ASC) 
  ON [PRIMARY] 
)

Tell me please, how to write current Server user as author of data commit to my table. Users enter through a local network in SQL Serve authorization mode. It should be pretty transparently for c# programmer, and it should be handle on server side.


This would be a great place for a trigger. Database triggers are often used for logging operations such as the one you're describing. In the trigger simply include the current user in your insert data.

There is a complete sample here.


you can make it varchar(100) with a default of SUSER_SNAME() for insert, for an update use an update trigger or pass in SUSER_SNAME() from your front end.

SUSER_SNAME() will work for both windows and sql logins


I used this script

    CREATE TRIGGER Author
    ON DataTable
    INSTEAD OF INSERT
    AS
    DECLARE
    @Value nvarchar(max),
    @CreateTime datetime

    SET @Value = (SELECT Value FROM inserted)
    SET @CreateTime = (SELECT CreateTime FROM inserted)

    INSERT INTO [DataTable]
               ([Value]
               ,[Author]
               ,[CreateTime])
        VALUES (@Value
               ,USER_ID()
               ,@CreateTime)
    GO
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜