将游标调用到游标(嵌套游标)

时间:2015-07-20 07:16:59

标签: sql sql-server sql-server-2008

我在将光标调用光标时面临问题,它正在抛出"A cursor with the name 'ParentDetail' already exists."

这是我的SP,请看一下:

Alter PROCEDURE FetchChild
    @ChildID Int
AS
BEGIN
    SET NOCOUNT ON;
    Create Table #AllChilds
    (
        ID  Int,
        Name Varchar(100)
    )
    Declare @ID Int
    Declare @Name Varchar(100)

    Declare ParentDetail Cursor For 
            Select ID,Name From Contacts Where ISNULL(ParentID,0) = @ChildID
        Open ParnetDetail
            Fetch Next From ParentDetail Into @ID,@Name
            While @@FETCH_STATUS = 0
            Begin
                Insert Into #AllChilds
                Values(@ID,@Name)

                Insert Into #AllChilds
                EXEC FetchChild
                    @ChildID = @ID

                Fetch Next From ParentDetail Into @ID,@Name
            End
            Close ParentDetail
            Deallocate ParentDetail
            Select * From #AllChilds
END
GO

1 个答案:

答案 0 :(得分:0)

试试这个,改变

  

声明ParentDetail光标

  

声明ParentDetail Cursor Local