如何在SQL Server中为更新表创建后删除触发器

时间:2015-08-26 22:31:49

标签: sql-server triggers

当我删除database.t_user中的一行时,我正在尝试创建一个从database.t_PMmessage更新行的触发器。

create trigger [dbo].[deleteUser]
 on [dbo].[t_user]
     after delete
      as
        BEGIN 
            update t_PMmessage set receiverID_FK = null
            where receiverID_FK IN(SELECT deleted.userID FROM deleted)
        END

但是当我从t_user删除时,我收到此错误: enter image description here

1 个答案:

答案 0 :(得分:0)

删除语句执行完后删除触发器触发后,因此删除语句在建议的触发器中的update语句之前执行,并且您将获得外键约束违规。

相反,触发器将触发而不是您发出的delete语句,并将首先更新t_PMmessage然后再更新delete语句。

也可以使用Exists运算符代替IN运算符。

你需要一个代替删除触发器的东西,比如......

create trigger [dbo].[deleteUser]
on [dbo].[t_user]
INSTEAD OF DELETE
as
BEGIN 

update t_PMmessage 
    set receiverID_FK = null
where EXISTS (SELECT 1 
              FROM deleted 
              WHERE  deleted.userID  = t_PMmessage.receiverID_FK )

DELETE FROM [dbo].[t_user]
where EXISTS (SELECT 1 
              FROM deleted 
              WHERE  deleted.userID  = [t_user].userID  )


END