Navigating the results of a stored procedure via a cursor using T-SQL

点点圈 提交于 2019-12-05 12:19:17

You could drop the results from the stored proc into a temp table and select from that for your cursor.

CREATE TABLE #myResults
(
    Col1 INT,
    Col2 INT
)

INSERT INTO #myResults(Col1,Col2)
EXEC my_Sp

DECLARE sample_cursor CURSOR
FOR
 SELECT
    Col1,
    Col2
 FROM
    #myResults

Another option may be to convert your stored procedure into a table valued function.

DECLARE sample_cursor CURSOR
FOR
  SELECT
     Col1,
     Col2
  FROM
     dbo.NewFunction('foo', 'bar')

You use INSERT ... EXEC to push the result of the procedure into a table (can be a temp #table or a @table variable), the you open the cursor over this table. The article in the link discusses the problems that may occur with this technique: it cannot be nested and it forces a transaction around the procedure.

You could execute your SP into a temporary table and then iterate over the temporary table with the cursor

create table #temp (columns)

insert into #temp exec my_stored_proc ....

perform cursor work

drop table #temp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!