2017-05-19 116 views
2

我有很長的腳本從表中的大量(超過100+)刪除某些特定的數據,它看起來像這樣更好的辦法:處理許多delete語句

...

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) 
+1

請記住,如果單個事務嘗試從任何給定表中刪除超過5000行,SQL Server將執行**鎖升級**。這會在該表上放置一個**獨佔鎖**,甚至在該事務被提交(或回滾)之前阻止從該表中選擇「SELECT」。儘量避免一次刪除超過5000行 –

回答

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 
+0

非常感謝,這爲我節省了很多時間:) – Rubiano

0

另一個解決方案是在select語句和每個結果實體運行適當的變量DELETE語句來創建一個遊標。

+0

如果有其他方法,不應該推薦使用遊標。 http://stackoverflow.com/questions/287445/why-do-people-hate-sql-cursors-so-much –

+0

我沒有說這是推薦的方法。我說「另一種解決方案是」,這意味着這是一個選擇。 – Dave