且构网

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

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

更新时间:2023-02-03 07:58:13

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.但是这样做时***使用触发器来删除不太独立的实体的记录.换句话说,与 PostHelpfulsUsersPostHelpfuls 旁边的表相关的可能性更高用户帖子旁边的表格.

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.