将查询返回的数字列表存储到变量中
Store a list of numbers returned by a query into a variable
我想将这样的查询返回的 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。
使用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
我想将这样的查询返回的 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。
使用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