2013-02-22 78 views
3

我想在相同條件(WHERE子句)每個delete語句刪除多個表中的數據。聲明在SQL Server存儲過程變量列表

delete from tblA where id in (select x.id from tblX x where name like N'%test%') 
delete from tblB where id in (select x.id from tblX x where name like N'%test%') 
delete from tblC where id in (select x.id from tblX x where name like N'%test%') 
delete from tblD where id in (select x.id from tblX x where name like N'%test%') 

有沒有辦法從上面的select語句中聲明一個存儲id的列表?

我想:

declare @ids int 
set @ids = select x.id from tblX x where name like N'%test%' 

但抱怨

子查詢返回多個值。這是在子查詢 如下時不允許=,!=,<,< =,>,> =,或當子查詢用作 的表達式。

請指教,謝謝。

+0

想想爲什麼排名前1的人會這樣做。 http://stackoverflow.com/questions/11232751/sql-error-subquery-returned-more-than-1-value – Tim 2013-02-22 19:00:17

回答

9

您將需要反正一張桌子,但至少你做一個像每次避免噸的處理:

-- create a table variable 
declare @ids table 
(
    id int not null 
) 

-- insert the id into the table variable 
insert into @ids 
select id from table1 where column1 like '%something%' 

-- delete 
delete from tablen where id in (select * from @ids) 

你也可以使用一個臨時表,看起來一樣,但不是@ ID,你需要#ids,並且你需要在作業完成後刪除臨時表。

到一個臨時表(物理表)或表變量(記憶如表),你真的需要做一些測試之間進行選擇,而是通過定義複雜的數據在臨時表中工作得更好。如果你只需要在短時間內持有少量的ID,我很確定表變量更好。

What's the difference between a temp table and table variable in SQL Server?

+0

表變量不是隻讀存儲器。這是一個神話。對於非神話的差異,請參閱[我的答案在這裏](http://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-服務器/ 16386#16386) – 2013-02-23 13:48:51

+0

我沒有真正的意思,並張貼了一個鏈接到差異。 – lolol 2013-02-24 23:19:29

2

你可以聲明一個臨時表,然後選擇到該表中的ID,你會被刪除。

CREATE TABLE #IDS_from_tblA (id int) 
INSERT INTO #IDS_from_tblA(id) 
    SELECT x.id FROM tblA WHERE x.id in (select x.id from tblX x where name like N'%test%') 
delete from tblA where id in (select x.id from tblX x where name like N'%test%') 

(Do whatever you want to do with the ids) 

DROP TABLE #IDS_from_tblA 
2

在SQL Server 2008+

declare @IdList table (Id int primary key) 

insert into @IDList (Id) 
select x.id from tblX x where name like N'%test%' 

delete from tblA where id in (select x.id from @IDList x) 

如果您有記錄一些hundreeds更多,您可以使用臨時表,而不是表變量。

相關問題