2

我有一个简单的触发器,当用户在表中插入行时运行。

由于还可以进行批量插入并且插入顺序很重要,有没有办法在触发器中保留它?

可以这样做还是有更好的方法来做到这一点?

ALTER TRIGGER simpleTrigger
ON shop
AFTER INSERT AS

SELECT * INTO #orderedInserted from inserted i ORDER BY i.Emp_Sal

declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);

    select @empid=#orderedInserted.Emp_ID from inserted i;  
    select @empname=#orderedInserted.Emp_Name from inserted i;  
    select @empsal=#orderedInserted.Emp_Sal from inserted i;    
    set @audit_action='Inserted Record -- After Insert Trigger.';

    insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
    values(@empid,@empname,@empsal,@audit_action,getdate());
GO;
4

2 回答 2

3

像这样的东西

ALTER TRIGGER simpleTrigger
ON shop
AFTER INSERT AS

    insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
    select i.Emp_ID, i.Emp_Name, i.Emp_Sal, 'Inserted Record -- After Insert Trigger.', getdate()
    from inserted i
    order by i.Emp_Sal

GO;

但如果您在 中没有标识列Employee_Test_Audit,则 ORDER BY 无关紧要

于 2013-07-02T11:55:06.633 回答
1

很简单,你不使用变量:

ALTER TRIGGER simpleTrigger
ON shop
AFTER INSERT AS    
    declare @audit_action varchar(100);
    set @audit_action='Inserted Record -- After Insert Trigger.';

    insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
    SELECT i.Emp_ID, i.Emp_Name, i.Emp_sal, @audit_action, getdate() from inserted i ORDER BY i.Emp_Sal ;
GO;
于 2013-07-02T11:55:30.557 回答