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

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

有没有一种方法可以声明一个列表,以存储上述选择语句中的ID?
我尝试过: ```python my_list = [] my_list.append(SELECT id FROM table) ``` 但它不起作用。
declare @ids int
set @ids = select x.id from tblX x where name like N'%test%'

但它抱怨说

子查询返回的值超过1个。当子查询跟随=,!=,<,<=,>,>=时,或者当子查询用作表达式时,不允许出现这种情况。

请给予建议,谢谢。


想一想为什么排名第一的答案能够解决这个问题。http://stackoverflow.com/questions/11232751/sql-error-subquery-returned-more-than-1-value - Tim
3个回答

10

无论如何,您都需要一个表格,但至少通过每次执行like操作来避免大量的处理:

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

SQL Server中临时表和表变量之间有什么区别?


表变量不仅仅存在于内存中,这是一个误解。关于非神话般的差异,请参见我的回答 - Martin Smith
我并不是真的那个意思,而且还发布了一个链接来说明区别。 - lolol

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)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接