如何在插入后在表上创建触发器以在Audit表中添加Row

时间:2017-11-23 20:47:04

标签: sql sql-server-2008

我想在插入后在学生表上创建一个触发器,以在学生审核表中添加行(服务器用户名,日期,注释),其中注释为“[用户名]在表中插入带有键的新行= [键值]学生

create trigger t1 on Student
after insert
as
declare @x int
begin
insert into Audit
(ServerUserName, Date, Note)
select SUSER_SNAME(), getdate(),SUSER_SNAME()+'Insert New Row with Key'+@x+'in Student '
from Student t
end
go

我怎么能用@x做这个,我的意思是@x是等于键

1 个答案:

答案 0 :(得分:0)

首先,删除declare @x int行。您无法将参数传递给触发器。如果您想要插入行,可以像inserted一样选择它;

create trigger t1 on Student
after insert
as
begin
    insert into Audit
    (ServerUserName, Date, Note)
    select SUSER_SNAME(), getdate(),SUSER_SNAME()+'Insert New Row with Key'+cast(t.Id as nvarchar(10))+'in Student '
    from Student t where Id IN (select Id from inserted)
end
go