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

在SQL Server存储过程中声明变量列表,sql,sql-server-2012,Sql,Sql Server 2012,我想从多个表中删除数据,每个delete语句的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

我想从多个表中删除数据,每个delete语句的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%'
但它抱怨说

子查询返回了多个值。这是不允许的,因为 子查询后面是=,!=,=或者当子查询用作 表情


请告知,谢谢。

您无论如何都需要一张桌子,但至少您可以通过每次执行类似操作来避免大量的处理:

-- 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,我非常确定表变量更好


您可以声明一个临时表,然后在该表中选择要删除的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 
在SQLServer2008中+

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)

如果您有超过百分之一百的记录,可以使用temp table而不是table变量。

想想为什么top 1可以这样做。表变量不仅仅是内存。这是一个神话。对于非神话的差异,请看,我并不是真的这么想的,我还发布了一个指向这些差异的链接。