2014-10-08 15 views
0

我有大約40個刪除查詢語句的過程中用於從多個表中爲外鍵記錄刪除記錄。多個刪除SQL Server中的過程中的查詢

例如

Create Proc usp_delete_record(@id int) 
    as 
    Begin 

    Delete from table1 where [email protected]; 
    Delete from table2 where [email protected]; 
    Delete from table3 where [email protected]; 
    Delete from table4 where [email protected]; 
    Delete from table5 where [email protected]; 
    Delete from table6 where [email protected]; 
    Delete from table7 where [email protected]; 
    Delete from table8 where [email protected]; 
    .................... 

    ................. 
    Delete from table40 where [email protected]; 


    End 

這是非常慢或掛起執行。

如何處理?

+0

你在表格上有適當的索引? (id列) – Recursive 2014-10-08 05:23:23

+0

檢查下面的鏈接使用單個查詢從多個表中刪除:http://stackoverflow.com/questions/20417303/single-query-to-delete-from-multiple-tables-in-sql-server – 2014-10-08 05:49:28

回答

0

USE ON DELETE CASCADE:

CREATE TABLE parent (parent_id integer primary key); 

CREATE TABLE child (child_name TEXT primary key,parent_id integer REFERENCES parent (parent_id) ON DELETE CASCADE); 
0

沒有需要一個過程的,因爲u有它作爲一個外鍵。只需在父級表中刪除級聯。

因此重新創建的所有子表foriegn鍵

ALTER TABLE <childtables> WITH CHECK 
ADD CONSTRAINT <fk_blah_blah> FOREIGN KEY(id) 
REFERENCES <parenttable> (id) 
ON DELETE CASCADE 

一旦你有了這個之後,就可以刪除父表中的單記錄等所有40個表中的數據被刪除