【问题标题】:Returning a single recordset from a looping stored procedure从循环存储过程返回单个记录集
【发布时间】:2019-08-07 16:06:55
【问题描述】:

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

我已经完成的工作,但是结果在不同的结果集中返回,这通常是多个查询一个接一个地运行。

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

【问题讨论】:

  • 您可以在循环之前创建一个#temptable,然后执行INSERT INTO #temptable SELECT @id,然后在循环之后执行SELECT * FROM #temptable
  • 您能否更改存储过程,使其接收table valued parameter 而不是标量值?您不仅可以简化代码,还可以获得更好的性能。
  • 您的问题可能过于简单化了。要思考的第一个问题是您的“内部”存储过程作为输出产生了什么。它会生成单个结果集吗?多个结果集?输出变量?打印消息?或者它不会产生任何输出,使您的问题在这一点上没有意义?

标签: sql-server stored-procedures database-cursor


【解决方案1】:

您能否将结果放入#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

【讨论】:

  • 这就是我的做法,尽管我可能会使用 table var,具体取决于数据的大小和我们正在谈论的行数。
猜你喜欢
  • 1970-01-01
  • 2014-01-04
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多