如何在SQL Server 2008上创建插入更新触发器

时间:2011-07-08 04:40:30

标签: sql-server tsql triggers

您好我有2个表名称EmpOneNotificationEmp1这两个表具有相同的列名相同的结构,我想在插入更新时使用触发器在NotificationEmp1表中插入更新记录记录到EmpOne

2 个答案:

答案 0 :(得分:1)

好吧,我没有看到触发器使得表的副本完全同步,并且你提供了非常模糊的规格,但我会试一试。

CREATE TRIGGER dbo.tr_EmpOne
ON dbo.EmpOne
FOR INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    INSERT dbo.NotificationEmp1(columns)
        SELECT columns 
        FROM inserted AS i
        WHERE NOT EXISTS
        (SELECT 1 FROM deleted WHERE key_column = i.key_column);

    UPDATE n
        SET col1 = i.col1,
            col2 = i.col2 --, etc etc
    FROM dbo.NotificationEmp1 AS n
    INNER JOIN inserted AS i
    ON i.key_column = n.key_column
    INNER JOIN deleted AS d
    ON i.key_column = d.key_column;
END
GO

现在不要忘记,当从EmpOne中删除行时,您需要从NoticiationEmp1中删除行。此外,这里根本没有错误处理 - 作为示例(并且这不会引发错误),考虑直接从NotificationEmp1删除行并且稍后在EmpOne中更新的情况,它将通过裂缝落空这里...

答案 1 :(得分:0)

在触发器中,您有一个名为“已插入”和“已删除”的逻辑(概念)表,用于保存已修改的记录。所以你可以插入这些记录。

CREATE TRIGGER [dbo].[Employee_Write_Audit] 
   ON  [dbo].[EmpOne]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- all new inserted records and updated.
    Insert into NotificationEmp1 select * from Inserted
    -- just the deleted ones not the updated rows that are being removed.
    Insert into NotificationEmp1 select * from Deleted where EmpOneId not in  (select EmpOneId from inserted)
END