更新触发器如何删除旧记录

时间:2016-06-10 11:30:41

标签: sql sql-server sql-server-2008 triggers

我在表A上创建了Insert触发器,只要在表A上发生插入,就会在表B中插入记录。这样可以正常工作但是如果我在表A上使用更新触发器,它会在表B中插入更新的记录,但不会删除旧的来自表B的记录。如何实现预期的结果?

ALTER TRIGGER trigger1 on tableA
FOR UPDATE

AS 
BEGIN

IF NOT EXISTS (SELECT C.column1 FROM  tableB C INNER JOIN INSERTED I ON C.column1 = I.column1 WHERE  C.column1 = I.column1 AND C.column2 = I.column2 )
 INSERT INTO tableB ( column1 , column2 )
    SELECT column1 , column2 
    FROM INSERTED I
    WHERE RecordTypeId IS NOT NULL
    GROUP BY column1 , column2 
    ORDER BY column1 , column2 

END

1 个答案:

答案 0 :(得分:1)

请检查使用内部已删除

从目标表中删除的SQL Server Update trigger
create TRIGGER trigger1 on tableA
FOR UPDATE

AS 
BEGIN

 DELETE tableB
 FROM tableB b
 INNER JOIN deleted d
    on b.column1 = d.column1
    and b.column2 = d.column2 


 INSERT INTO tableB ( column1 , column2 )
    SELECT column1 , column2 
    FROM INSERTED

请在使用前进行测试。