处理许多删除语句的更好方法

时间:2017-05-19 07:42:51

标签: sql-server tsql

我有一个很长的脚本,用于删除大量(超过100个)表中的某些特定数据,它看起来像这样:

...

Delete from Table_name WHERE Company not in ('Company1','Company2')
Delete from Table_name WHERE Company not in ('Company1','Company2')
Delete from Table_name WHERE Company not in ('Company1','Company2')
Delete from Table_name WHERE Company not in ('Company1','Company2')

...

我想改变这一点,所以我不必更改每一行的变量,我希望能够在开头设置where语句,这将改变所有删除行

declare .....something something
SELECT CompanyID
FROM _Company
WHERE  Company in ('Company1','Company2') -- I want to change this where statement only

Delete from Table_name WHERE Company not in (variable)
Delete from Table_name WHERE Company not in (variable)
Delete from Table_name WHERE Company not in (variable)
Delete from Table_name WHERE Company not in (variable)

2 个答案:

答案 0 :(得分:3)

您需要表格变量。根据需要更改列名,数据类型:

DECLARE @idsToKeep TABLE ( CompanyID int );

INSERT @idsToKeep
SELECT CompanyID
FROM _Company
WHERE Company IN ('Company1','Company2'); -- change this one place

DELETE Table_name1 WHERE CompanyID NOT IN ( SELECT CompanyID FROM @idsToKeep ); 
DELETE Table_name2 WHERE CompanyID NOT IN ( SELECT CompanyID FROM @idsToKeep ); 
DELETE Table_name3 WHERE CompanyID NOT IN ( SELECT CompanyID FROM @idsToKeep ); 
-- etc

答案 1 :(得分:0)

另一个解决方案是在select语句上创建一个游标,并为每个结果实体运行带有适当变量的delete语句。