2014-10-08 49 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个表中的数据被删除