sql-server - 从循环存储过程返回单个记录集
问题描述
我不太喜欢将查询放入循环中,但是我需要运行一个循环并执行存储过程的查询。
我已经完成的工作,但是结果将在单独的结果集中返回,其方式通常是多个查询一个接一个地运行。
我需要一个结果集中的所有结果,就像 UNION 给我的方式一样。
这是我所拥有的一个例子:
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
SELECT @id
fetch next from cur into @id
END
close cur
deallocate cur
这将返回以下内容:
-----------
1
(1 row(s) affected)
-----------
2
(1 row(s) affected)
-----------
3
(1 row(s) affected)
但是我需要:
id
-----------
1
2
3
(3 row(s) affected)
解决方案
您可以将结果放入#Temp 表中吗?
将临时表添加到您的例程中
Create Table #tbl
(
id Int
)
你的日常
-- Insert statements for procedure here
declare @id int
--declare @field2 int
declare cur CURSOR LOCAL for
-- Build examples to loop through
SELECT 1 AS id
UNION
SELECT 2 AS id
UNION
SELECT 3 AS id
open cur
fetch next from cur into @id
while @@FETCH_STATUS = 0 BEGIN
--execute your stored procedure on each row
Insert Into #Tbl SELECT @id --ON EACH LOOP, INSERT ID to TEMP TABLE
fetch next from cur into @id
END
Select * From #Tbl --Present the results of the TEMP TABLE
close cur
deallocate cur
Drop Table #tbl --Drop your TEMP TABLE
结果:
id
1
2
3
推荐阅读
- r - 如何在 R 中计算此数据框的差异
- javascript - 用户输入的时间为零,即使在 javascript 中应该更多
- r - 尝试显示散点矩阵时提取变量中的模型公式无效
- python - 通过 L0 范数/GEKKO 中的非零元素数约束混合整数非线性优化问题
- python - 如何构造嵌套的for循环?
- r - 使用 dplyr 计算频率
- python - Tensorflow 2.4 - 导入 _pywrap_tensorflow_internal 时 DLL 加载失败
- javascript - VueJS 计算回报最佳实践
- python - 在 Python 中评估决策树模型时出现 TypeError(预期序列或类似数组)
- c++ - 将 Boost Spirit 解析器从 boost::variant 转换为 std::variant 2