1
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
4

1 回答 1

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

然后您不需要在触发器中编写的其余代码

于 2013-10-30T07:26:53.400 回答