7

我的一张表有以下 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
4

4 回答 4

12

为此使用suser_name ()的system_user 。

dbo如果您的用户处于 sysadmin 角色,则user_name()将返回。

于 2013-08-30T14:43:08.787 回答
5

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;

做同样的事情,但方式更简洁(没有额外的逻辑和变量,只有一条语句)。

有什么问题就问吧!

于 2013-08-30T14:18:17.723 回答
1

Current_user 是您正在寻找的好先生(取决于您正在运行的 sql-server 版本) http://technet.microsoft.com/en-us/library/ms176050.aspx

于 2013-08-30T14:18:27.840 回答
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
于 2016-06-02T12:46:11.410 回答