我想将查询返回的Id
存储到变量中:
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。
答案 0 :(得分:1)
使用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
答案 1 :(得分:1)
也可以使用临时表
SELECT FooId AS ID INTO #tmp_bar FROM Bar
--#tmp_bar can be used as a normal table
SELECT ID FROM #tmp_bar