12

我正在尝试将存储过程的结果放入游标中以在当前过程中使用。我在下面添加了我的代码,但我不确定这是否可行或者我的语法是否正确?

DECLARE cursorIDList CURSOR FOR
    EXEC spGetUserIDs
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID

我收到以下错误:“EXEC”附近的语法不正确。期待 SELECT、'(' 或 WITH。

提前致谢。

4

3 回答 3

12

你可以这样做:

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
于 2012-07-05T10:49:25.223 回答
0

在我看来,非常有趣的方法是使用游标作为参数(尽管如果你不打算更新表,我认为它不是更好的选择):

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
于 2012-07-05T12:41:00.737 回答
0

SQL-Server 中游标的语法是:

DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR FOR select_statement   

之后FOR你必须写一个SELECT.

有关详细信息,请参阅: https ://msdn.microsoft.com/it-it/library/ms180169.aspx

于 2016-12-14T11:59:18.617 回答