首页 > 解决方案 > 从循环存储过程返回单个记录集

问题描述

我不太喜欢将查询放入循环中,但是我需要运行一个循环并执行存储过程的查询。

我已经完成的工作,但是结果将在单独的结果集中返回,其方式通常是多个查询一个接一个地运行。

我需要一个结果集中的所有结果,就像 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)

标签: sql-serverstored-proceduresdatabase-cursor

解决方案


您可以将结果放入#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

推荐阅读