Skip to content
Advertisement

Delete from child table with two parents without cascade delete in sql server

I need your guidance. I create a script to delete from 3 tables separately. meaning when I created the script is to delete from table3 (child) then delete from 2 (child), then delete from table1(parent) I am having problem with Table3 since table2 has foreign key both for table2 and table1 so I cannot delete it before I delete table2 and if I delete table2 first then I lose reference that I use to find the rows to be delete then I delete 0 from table3 and table1.

The script looks like following

the above delete 0 since I delete table 2 before deleting from

It does not delete from table1 either since the script looks up where does not exist in table2

Advertisement

Answer

Try something like this:

Haven’t got the tables, etc. to try it but looks like it should be ok.

I’m also presuming here that those rows aren’t possibly changing while you’re doing this, otherwise you have potential race conditions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement