2010-03-09 25 views
1

我想這樣做:如何刪除相互引用的表中的行?

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

但它給我的錯誤。

+0

什麼是錯誤(以及你想要發生什麼) – Mark 2010-03-09 15:36:15

+0

模式是什麼樣的?哪些表具有外鍵? – Thomas 2010-03-09 15:36:44

+0

a.col1主鍵 b.col1 forien鍵,主鍵 c.col2 foriend關鍵 – SmartestVEGA 2010-03-09 15:38:25

回答

3

先刪除的最低水平,並從那裏向上移動,一個每一級刪除,爲最高級別:

DELETE FROM ChildTable WHERE ParentID=... 

DELECT FROM ParentTable WHERE ParentID=... 
+0

+1:SQL Server不支持多表刪除 – 2010-03-09 15:40:24

+0

實際上,您可以使用thekaido提到的級聯函數來實現此功能 – super9 2010-03-09 15:45:47

1

既然你沒有指定什麼每個表都有一個外鍵和在其領域,我會猜測:

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' 
2

您可以打開級聯刪除,然後刪除父記錄。

+0

+1這實際上是最好的答案。 – JonH 2010-03-09 15:45:16

+0

+1我要寫完全相同的答案。這是刪除相關記錄的唯一自動化方式。其他選項在第一個答案中描述。 – mevdiven 2010-03-09 15:48:48

+1

明確是最好的答案。如果有人不情願地觸發它,「CASCADE ON DELETE」會導致問題,並且可以應用SQL Server 2005「CASCADE ON DELETE」,但在自引用關係時不起作用。 – 2010-03-09 15:49:37

0

從表1一個刪除A,表2 B,表3Ç
其中a.col1 = b.col1
和b.col2 = c.col2
和a.co3 <> 8001;

相關問題