将查询返回的数字列表存储到变量中

问题描述 投票:1回答:2

我想将这样的查询返回的Ids存储到变量中:

SELECT FooId FROM Bar; -- FooId is of type int

所以我稍后可能会说:

DELETE FROM Foo WHERE Id IN @TheFooIdsIGotFromThePreviousQueryAbove;

我怎么做?具体来说,我必须声明这样的列表变量是什么数据类型?

请注意,我可以简单地完成:

DELETE FROM Foo WHERE Id IN (SELECT FooId FROM Bar);

但是我不能因为那些简单地使问题复杂化的原因而做不到这一点。

我正在使用Microsoft SQL Server 2014。

sql sql-server sql-server-2014
2个回答
1
投票

使用temp tabletable variable来存储Id

-- declare table variable
declare @IDS table (Id int)

-- insert into the table variable
insert into @IDS (Id) SELECT FooId FROM Bar

-- join the table variable to the table you want to delete
DELETE d
FROM   Foo d
       INNER JOIN @IDS i ON d.Id = i.Id

1
投票

也可以使用临时表

SELECT FooId AS ID INTO #tmp_bar FROM Bar 

--#tmp_bar can be used as a normal table
SELECT ID FROM #tmp_bar 
© www.soinside.com 2019 - 2024. All rights reserved.