2012-02-21 71 views
0

我有一個表ParentTable,其中我有parentId作爲主鍵。在SQL Server 2008中對錶進行層級刪除

現在我有三個子表ChildTable1,ChildTable2ChildTable3

  • ChildTable1

    ,主鍵是ch1Id和外鍵是fkparentId(PK從ParentTable

  • ChildTable2

    ,主鍵是ch2Id和外鍵是fkparentIdfkch1Id(從ChildTable1主鍵)

  • in ChildTable3,主鍵是ch3Id,外鍵是fkparentId, fkch1Idfkch2Id(來自ChildTable2的主鍵)。

而且這樣下去..

我想編寫一個查詢以下列方式hierarchially刪除這些表。

首先刪除ChildTable3>然後刪除ChildTable2>然後刪除ChildTable1並最後刪除ParentTable

我有這樣類似

delete from ChildTable3 
where fkch2Id = ch2.ch2Id 
and fkch1Id = ch1.ch1Id 
and fkparentId = p.parentId 

則前進到ChildTable2刪除等的一個模糊的概念。希望我明確表示。

+0

要從ChildTable3中刪除哪些行?所有的行?滿足ChildTable3中某些條件的行或滿足其他表中某些條件的行? – 2012-02-21 07:18:46

+0

我想從ChildTable3和其他提到的表中刪除所有行。 – 2012-02-21 07:23:03

+1

然後你只需要從ChildTable3中刪除,然後從ChildTable2中刪除等等,最後你從ParentTable中刪除。無需加入其他表格。 – 2012-02-21 07:26:44

回答

2

通過在外鍵definitin上設置cascade on delete,可以在沒有任何查詢的情況下做同樣的事情。

如果你沒有在db上設置外鍵定義你可以像這樣刪除fkparentId上的記錄。

declare @parentId int = 3 

delete from ChildTable3 where fkparentId = @parentId; 
delete from ChildTable2 where fkparentId = @parentId; 
delete from ChildTable1 where fkparentId = @parentId; 
delete from ParentTable where parentId = @parentId; 
+0

好的。我會試試這個。謝謝。 – 2012-02-21 07:31:06