Can I get the results of a stored procedure into a cursor within another stored procedure in SQL

谁都会走 提交于 2019-11-30 23:52:45

问题


I'm trying to put the results of a stored procedure into a cursor to use within the current procedure. I've added my code below but I'm not sure if this is possible or if my syntax is correct?

DECLARE cursorIDList CURSOR FOR
    EXEC spGetUserIDs
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID

I receive the following error: Incorrect syntax near 'EXEC'. Expecting SELECT, '(' or WITH.

Thanks in advance.


回答1:


You can do it like this:

DECLARE @t TABLE (ID INT)
INSERT INTO @t
EXEC spGetUserIDs

DECLARE cursorIDList CURSOR FOR
    SELECT * FROM @t
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID



回答2:


in my opinion very interesting approach would be to use cursor as parameter (although if you not going to update table i don't think its better choice):

create Table dbo.MyTable
(
    i int 
);
Insert Into dbo.MyTable (i) values (1)
Insert Into dbo.MyTable (i) values (2)
Insert Into dbo.MyTable (i) values (3)
Insert Into dbo.MyTable (i) values (4)
Go
Set NoCount ON;
Go
Create Proc dbo.myProc 
(
    @someValue int,
    @cur Cursor Varying Output
)
As
Begin 
    declare @x int;

    Set @cur = Cursor for
        Select i From dbo.MyTable
        Where i < @someValue;

    open @cur
End
Go
-- Use of proc
declare @cur cursor;
declare @x int;
Exec dbo.myProc 3, @cur output


fetch next from @cur into @x
while @@fetch_status = 0
begin
    print 'value: ' + cast(@x as varchar)
    fetch next from @cur into @x
end

close @cur;
Deallocate @cur;

Go
--Cleanup
Drop Proc dbo.myProc 
Drop Table dbo.MyTable



回答3:


The syntax of cursor in SQL-Server is:

DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR FOR select_statement   

After FOR you must write a SELECT.

For more info see: https://msdn.microsoft.com/it-it/library/ms180169.aspx



来源:https://stackoverflow.com/questions/11342306/can-i-get-the-results-of-a-stored-procedure-into-a-cursor-within-another-stored

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