MS SQL“ON DELETE CASCADE”多个外键指向同一个表?

时间:2011-02-16 15:06:51

标签: sql sql-server foreign-keys constraints cascading-deletes

你好 我有一个问题,我需要在指向同一个表的多个外键上级联..

[Insights]
| ID | Title        |
| 1  | Monty Python |
| 2  | Spamalot     | 

[BroaderInsights_Insights]
| broaderinsight_id | insight_id |
| 1                 | 2          |

基本上,当洞察表中的一个或两个记录被删除时,我也需要将该关系删除..

我试过这个:

 CREATE TABLE broader_insights_insights(id INT NOT NULL IDENTITY(1,1),
   broader_insight_id INT NOT NULL REFERENCES insights(id) ON DELETE CASCADE,
   insight_id INT NOT NULL REFERENCES insights(id) ON DELETE CASCADE,
   PRIMARY KEY(id))
Go

这导致警告级联“可能导致循环或多个级联路径”

所以我尝试添加一个级联到insight_id,这导致:

“DELETE语句与REFERENCE约束冲突”

有什么想法吗?

由于

丹尼尔

1 个答案:

答案 0 :(得分:28)

您必须在洞察中将其作为INSTEAD OF删除触发器来实现,以使其发挥作用。类似的东西:

create trigger T_Insights_D
on Insights
instead of delete
as
    set nocount on
    delete from broader_insights_insights
    where insight_id in (select ID from deleted) or
    broader_insight_id in (select ID from deleted)

    delete from Insights where ID in (select ID from deleted)

通常使用级联删除和大量外键,您需要花时间计算“级联”顺序,以便在“树”顶部发生的删除成功级联到引用表。但在这种情况下,这是不可能的。