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

问题描述 投票:3回答:3

我想从每个删除语句的相同条件(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。当子查询跟随=,!=,<,<=,>,> =或子查询用作表达式时,不允许这样做。

请指教,谢谢。

sql sql-server-2012
3个回答
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?


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)

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

© www.soinside.com 2019 - 2024. All rights reserved.