且构网

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

SQL Server:自引用 FK,触发器而不是 ON DELETE CASCADE

更新时间:2023-02-02 22:54:26

FOR DELETE 触发器在 原始 DELETE 执行后被引发.要递归删除,您需要编写一个 INSTEAD OF DELETE 触发器.

The FOR DELETE trigger is raised after the original DELETE has been executed. To delete recursively, you need to write an INSTEAD OF DELETE trigger.

算法是这样的:

  • 将已删除的 PK 插入临时表

  • Insert the PKs from deleted into a temp table

在临时表中查找记录的详细记录

Find detail records of records in temp table

循环直到找不到更多记录

Loop until no more records are found

通过连接临时表删除表中的记录.

DELETE records in the table by joining with temp table.

我在我的博客中描述了递归删除一>.

更新

我想您只需要从类别中的递归外键中删除 ON DELETE CASCADE 标志即可.来自 CAT_SCH 的外键上的 CASCADE 标志应该无关紧要.

I guess you just need to drop that ON DELETE CASCADE flag from your recursive foreign key in Categories. The CASCADE flag on the foreign key from CAT_SCH should not matter.