删除前的MS Sql Server触发器

时间:2016-12-05 17:25:21

标签: sql-server-2012

我创建了以下触发器

ALTER TRIGGER SystemClearConfiguration
ON Systems
FOR DELETE
AS 
BEGIN
    UPDATE Configurations SET ReceiverId = NULL WHERE ReceiverId = (SELECT deleted.Id from deleted);
    UPDATE Configurations SET SenderId = NULL WHERE SenderId = (SELECT deleted.Id from deleted);
END
GO

如果我进入数据库,右键单击Systems并单击“编辑前200”并尝试删除一行,我知道我总是在表配置上得到关于FK的错误。

我看到的唯一原因是删除前没有运行的触发器。在Oracle上我知道你可以明确地说BEFORE或AFTER,但是在SQL上我找不到这样的选项。

编辑1 - 2016-12-07

NOTE: DataTypes might not be correct

注意:DataTypes可能不正确

错误

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

以下触发器对我有用:

ALTER TRIGGER SystemClearConfiguration
ON Systems
INSTEAD OF DELETE
AS 
BEGIN
    UPDATE Configurations SET ReceiverId = NULL WHERE ReceiverId IN (SELECT deleted.Id from deleted);
    UPDATE Configurations SET SenderId = NULL WHERE SenderId IN (SELECT deleted.Id from deleted);
    DELETE Systems WHERE Id IN (SELECT deleted.Id from deleted);
END
GO