我的一个表有以下sql触发器。我只是想知道我是否可以跟踪并添加对表进行更改的用户?
见下面的代码
ALTER trigger [dbo].[Trigger_Audit_Client] on [dbo].[Client] for insert, update, delete
as
declare @type varchar(1) ,
@UpdateDate datetime
if exists (select * from inserted) and exists (select * from deleted)
select @type = 'U'
else if exists (select * from inserted)
select @type = 'I'
else
select @type = 'D'
select @UpdateDate = getdate()
insert Client_Audit (Client_Id, ClientName, ClientSurname, TelephoneHome, TelephoneWork, TelephoneCellular, DOB, Gender, ClientIdNumber, Company_Id, Region, City, Email, AddressLine1, AddressLine2, Will_UID, WillCreated, WillLatest, UpdateDate, UpdateType)
select Client_Id, ClientName, ClientSurname, TelephoneHome, TelephoneWork, TelephoneCellular, DOB, Gender, ClientIdNumber, Company_Id, Region, City, Email, AddressLine1, AddressLine2, Will_UID, WillCreated, WillLatest, @UpdateDate, @type + '_old'
from deleted
insert Client_Audit (Client_Id, ClientName, ClientSurname, TelephoneHome, TelephoneWork, TelephoneCellular, DOB, Gender, ClientIdNumber, Company_Id, Region, City, Email, AddressLine1, AddressLine2, Will_UID, WillCreated, WillLatest, UpdateDate, UpdateType)
select Client_Id, ClientName, ClientSurname, TelephoneHome, TelephoneWork, TelephoneCellular, DOB, Gender, ClientIdNumber, Company_Id, Region, City, Email, AddressLine1, AddressLine2, Will_UID, WillCreated, WillLatest, @UpdateDate, @type + '_new'
from inserted
答案 0 :(得分:10)
user_name()将返回dbo
。
答案 1 :(得分:4)
User_Name()
:http://technet.microsoft.com/en-us/library/ms188014.aspx
USER_NAME ( [ id ] )
当省略id时,假定当前上下文中的当前用户。如果参数包含单词NULL,则返回NULL。当在EXECUTE AS语句之后调用USER_NAME而未指定id时,USER_NAME将返回模拟用户的名称。如果Windows主体通过组中的成员身份访问数据库,则USER_NAME将返回Windows主体的名称而不是组。
我会将您的触发器代码更改为:
SET NOCOUNT ON;
INSERT INTO dbo.Client_Audit (Cliend_Id, ClientName, ..., UpdateDate, UpdateType)
SELECT Coalesce(i.Cliend_Id, d.Cliend_Id) As Cliend_Id
, Coalesce(i.ClientName, d.ClientName) As ClientName
, ...
, Current_Timestamp As UpdateDate
, CASE WHEN i.Cliend_Id IS NULL THEN 'D'
WHEN d.Cliend_Id IS NULL THEN 'I'
ELSE 'U'
END As UpdateType
FROM inserted As i
FULL
JOIN deleted As d
ON d.Cliend_Id = i.Cliend_Id;
同样的事情,但更清洁(没有额外的逻辑和变量,只有一个声明)。
任何问题都可以问!
答案 2 :(得分:1)
Current_user就是你要找的好先生(取决于你正在运行的sql-server的版本) http://technet.microsoft.com/en-us/library/ms176050.aspx
答案 3 :(得分:0)
您可以创建一个新表并使用触发器填充它,例如:
create trigger LogTrigger
ON YourTable
FOR INSERT
as
insert into LogTable (Col_1, Col_2, Col_3, DataInsert, UserName)
select Col_1, Col_2, Col_3, GETDATE(), User_Name()
from inserted