且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008-多个级联FK-我需要触发器吗?

更新时间:2023-02-03 08:20:22

SQL Server选择哪个路径都不是问题,它不允许这样做,这样它就不会折衷.当我们遇到这种情况时,我们不得不诉诸触发器.

It's not a matter of which path will SQL Server choose, it does not allow it so that it won't wind up in a compromising position. When we ran into this situation, we had to resort to a trigger.

1)如错误消息所述,将 Users_PostHelpfuls FK更改为 ON DELETE NO ACTION .

1) As the error message stated, change the Users_PostHelpfuls FK to ON DELETE NO ACTION.

2)向用户添加 INSTEAD OF DELETE 触发器:

2) Add an INSTEAD OF DELETE trigger to Users:

CREATE TRIGGER dbo.Users_IO_Delete 
ON dbo.Users
INSTEAD OF DELETE
AS
BEGIN;
    DELETE FROM dbo.PostHelpfuls WHERE UserId IN (SELECT UserId FROM deleted);

    DELETE FROM dbo.Users WHERE UserId IN (SELECT UserId FROM deleted);
END;

现在,FK仍将强制执行DRI,但触发器将级联删除而不是FK约束.

Now, the FK will still enforce DRI, but the trigger is cascading the delete rather than the FK constraint.

在上述步骤中,您可以将 PostHelpfuls 替换为 Posts .但是在执行此操作时,***使用触发器删除不太独立的实体的记录.换句话说,帖子 Users PostHelpfuls 旁边的表相关的可能性大于 PostHelpfuls 用户帖子旁边的表格.

You could replace PostHelpfuls with Posts in the above steps. But when doing this it's best to use the trigger to remove the less independent entity's records. In other words, it's more likely that Posts are related to tables beside Users and PostHelpfuls than PostHelpfuls is related to tables beside Users and Posts.