过程tr_EMPLOYEE2_FORINSERT,第10行插入错误:列名或提供的值数与表定义不匹配

时间:2013-10-30 06:58:51

标签: sql-server-2005-express

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

1 个答案:

答案 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

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