每次启动脚本时,将光标的位置重置为beginng

时间:2015-11-22 17:13:07

标签: sql sql-server tsql cursor

我目前正在研究T-SQL程序和游标,但我最近遇到了这个问题。如何重置到从过程返回的游标的beginnig位置(从中获取所有数据后)?我在以下上下文中有一个光标:

CREATE PROCEDURE dbo.my_procedure
    @curs CURSOR VARYING OUTPUT
AS
    SET @curs = CURSOR
    SCROLL FOR
        select book_name, author_lastname
        from dbo.books;
OPEN @curs;
go

declare @tmp_curs cursor;
declare @val_1 varchar(35), @val_2 varchar(35);


EXEC dbo.my_procedure @tmp_curs output;
WHILE (@@FETCH_STATUS = 0)
BEGIN
    print @val_1 + ' ' + @val_2 + ';'
    FETCH NEXT FROM @tmp_curs
    INTO @val_1, @val_2;
END;
CLOSE @tmp_curs;
DEALLOCATE @tmp_curs;
go

当我第一次运行这个脚本时,我得到了我需要的结果(光标中的条目)。但是当我下次运行时,我只得到结果

  

"(100行(s)受影响)"

而不是实际的条目,所以我必须重新启动Server Management Studio。

我尝试过 @@FETCH_STATUS, 重新执行程序,和 关闭开放游标,但似乎没有什么对我有用。每次运行此脚本时,如何获得相同的结果(光标中的条目)?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以使用FETCH FIRST FROM

DECLARE @tmp_curs cursor;
DECLARE @val_1 varchar(35), @val_2 varchar(35);

-- first run
EXEC dbo.my_procedure @tmp_curs output;
FETCH FIRST FROM @tmp_curs INTO @val_1, @val_2;
WHILE (@@FETCH_STATUS = 0)
BEGIN
    INSERT INTO books2 VALUES (@val_1, @val_2);
    FETCH NEXT FROM @tmp_curs
    INTO @val_1, @val_2; 
END;
CLOSE @tmp_curs;
DEALLOCATE @tmp_curs;

-- second run
EXEC dbo.my_procedure @tmp_curs output;
FETCH FIRST FROM @tmp_curs INTO @val_1, @val_2;
WHILE (@@FETCH_STATUS = 0)
BEGIN
    INSERT INTO books2 VALUES (@val_1, @val_2);
    FETCH NEXT FROM @tmp_curs
    INTO @val_1, @val_2;
END;
CLOSE @tmp_curs;
DEALLOCATE @tmp_curs;

-- checking
SELECT *
FROM books2;

SqlFiddleDemo