【问题标题】:Can I get the results of a stored procedure into a cursor within another stored procedure in SQL我可以将存储过程的结果放入 SQL 中另一个存储过程中的游标中吗
【发布时间】:2012-07-05 10:21:02
【问题描述】:

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

DECLARE cursorIDList CURSOR FOR
    EXEC spGetUserIDs
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID

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

提前致谢。

【问题讨论】:

  • 是的,我收到一个错误:“EXEC”附近的语法不正确。期待 SELECT、'(' 或 WITH。

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


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 非常感谢。如果 sp 返回超过 1 列,它们可以在新声明的表中匹配吗?再次感谢
  • 没有。您需要创建具有与过程返回器一样多的列的表
  • 在SP返回结果之前,您必须已经有一个具有匹配列的表变量,您必须知道SP返回的数据集中列的数据类型,并据此在表中创建它们过程调用之前的变量。
【解决方案2】:

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

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】:

    SQL-Server中游标的语法是:

    DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR FOR select_statement   
    

    FOR 之后必须写一个SELECT

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多