ALTER TRIGGER tr_EMPLOYEE2_FORINSERT
ON EMPLOYEE2
FOR INSERT
AS
BEGIN
-- SELECT * FROM INSERTED --INSERTED Table is a special table created for the purposes of Triggers, it is available only in the context of the trigger.
DECLARE @ID INT
SELECT @ID = ID FROM INSERTED
INSERT INTO EMPAUDIT
VALUES('New Employee with id = ' + cast(@id as nvarchar(5)) + ' is added at ' + cast(getdate() as nvarchar(20)))
END
答案 0 :(得分:0)
一个。我们不知道您的EMPAUDIT
表格是什么样的。但是假设它有多个列(大多数表都有),你应该为你的INSERT
语句使用列列表:
INSERT INTO EMPAUDIT (Column_To_Insert_Into)
VALUES('New Employee with id = ' + cast(@id as nvarchar(5)) +
' is added at ' + cast(getdate() as nvarchar(20)))
湾然而,触发它实际上仍然被打破。为什么?因为inserted
可以包含多个行(或没有行)。所以实际上我们想要的是:
INSERT INTO EMPAUDIT (Column_To_Insert_Into)
SELECT 'New Employee with id = ' + cast(i.id as nvarchar(5)) +
' is added at ' + cast(getdate() as nvarchar(20))
FROM inserted i
然后您不需要在触发器中编写的其余代码