Sql 将查询返回的数字列表存储到变量中
我想将类似这样的查询返回的Sql 将查询返回的数字列表存储到变量中,sql,sql-server,sql-server-2014,Sql,Sql Server,Sql Server 2014,我想将类似这样的查询返回的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 FRO
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
使用
temp table
或table variable
存储Id
您可以使用OUTPUT子句,但我不确定它是否存在于mysql中。Linkhttps://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-服务器-2017。并且可以使用表变量。@ch2019 output子句在这里没有帮助,问题不是关于mysql的。