我有一个简单的触发器,当用户在表中插入行时运行。
由于批量插入和插入顺序也很重要,有没有办法在触发器中保留它?
可以这样做,还是有更好的方法呢?
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;
答案 0 :(得分: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无关紧要
答案 1 :(得分: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;