Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL "ON DELETE CASCADE" multiple foreign keys pointing to the same table?

Tags:

I have a problem where i need a cascade on multiple foreign keys pointing to the same table..

[Insights] | ID | Title        | | 1  | Monty Python | | 2  | Spamalot     |   [BroaderInsights_Insights] | broaderinsight_id | insight_id | | 1                 | 2          | 

Basically when either record one or two in the insights table is deleted i need the relationship to also be deleted..

I've tried this:

 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 

This results in the warning that the cascade "may cause cycles or multiple cascade path"

So ive tried adding a cascade to just the insight_id and this results in:

The DELETE statement conflicted with the REFERENCE constraint

Any ideas?

Thanks

Daniel

like image 849
Daniel Upton Avatar asked Feb 16 '11 15:02

Daniel Upton


People also ask

Can a table have multiple foreign keys from same table?

A table may have multiple foreign keys, and each foreign key can have a different parent table. Each foreign key is enforced independently by the database system. Therefore, cascading relationships between tables can be established using foreign keys.

Can a foreign key be pointing to same table?

FOREIGN KEY constraints can reference another column in the same table, and is referred to as a self-reference. A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.

What happens when specifying on delete cascade for a foreign key column?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.


1 Answers

You'll have to implement this as an INSTEAD OF delete trigger on insights, to get it to work. Something like:

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) 

Frequently with cascading deletes and lots of foreign keys, you need to spend time to work out a "cascade" order so that the delete that occurs at the top of a "tree" is successfully cascaded to referencing tables. But that isn't possible in this case.

like image 150
Damien_The_Unbeliever Avatar answered Oct 14 '22 15:10

Damien_The_Unbeliever