How to delete rows from tables which is referenced each other?

230 Views Asked by At

I want to do this:

delete from table1 a,table2 b, table3  c 
 where a.col1 = b.col1 
   and b.col2 = c.col2 
   and a.co3 <> 8001;

But its giving me an error.

4

There are 4 best solutions below

1
On

delete the lowest level first and move up from there, one delete per level, to the highest level:

DELETE FROM ChildTable WHERE ParentID=...

DELECT FROM ParentTable WHERE ParentID=...
0
On

Since you did not specify to what each table has a foreign key and on which field, I'll take a guess:

Delete TableC
Where Exists( Select 1 From TableA Where TableA.Col1 = TableC.Col2 And TableA.Col3 <> '8001' )

Delete TableB
Where Exists( Select 1 From TableA Where TableA.Col1 = TableB.Col2 And TableA.Col3 <> '8001' )

Delete TableA
Where Col3 <> '8001'
3
On

You could turn cascade deletes on then delete the parent record.

0
On

delete A from table1 a,table2 b, table3 c
where a.col1 = b.col1
and b.col2 = c.col2
and a.co3 <> 8001;