在SQL Server存储过程中声明变量列表

时间:2013-02-22 18:55:18

标签: sql sql-server-2012

我想删除每个删除语句具有相同条件(where子句)的多个表中的数据。

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%'

但它抱怨

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

请指教,谢谢。

3 个答案:

答案 0 :(得分: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)

您也可以使用临时表,它看起来是一样的,但是不是@ids,而是需要#ids,并且您需要在作业完成后删除临时表。

要在临时表(物理表)或表变量(像表这样的内存)之间进行选择,您确实需要进行一些测试,但根据定义,复杂数据在临时表中的效果更好。如果您只需要在短时间内保留少量ID,我非常确定表变量更好。

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

答案 1 :(得分: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 :(得分: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)

如果您有超过数百条记录,则可以使用临时表而不是表变量。