我想将这样的查询返回的Id
s存储到变量中:
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。
使用temp table
或table 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
也可以使用临时表
SELECT FooId AS ID INTO #tmp_bar FROM Bar
--#tmp_bar can be used as a normal table
SELECT ID FROM #tmp_bar