如何从头开始重用tsql中的游标

时间:2016-08-08 07:47:06

标签: sql sql-server

如何在不更改其定义的情况下从头开始重用tsql中的游标。

我看到了这个主题link,但我不知道在此之后该怎么做

 fetch first from c;

我在这段代码之后使用了:

WHILE @@FETCH_STATUS = 0 

        BEGIN 

        ...
            FETCH NEXT FROM c INTO @myVariable;
        END;

        CLOSE c;    
        DEALLOCATE c;

但它没有用。

2 个答案:

答案 0 :(得分:1)

您可以创建一个只读的滚动光标,并在需要时重置为光标的第一条记录。

例如:

DECLARE @T TABLE (Id int, Num int);
insert into @T values (1,0),(2,0),(3,0);

DECLARE @ID INT;
DECLARE @Num INT;
DECLARE @Counter INT = 0;
DECLARE c SCROLL CURSOR FOR (SELECT Id, Num FROM @T) FOR READ ONLY;

OPEN c;
FETCH NEXT FROM c INTO @ID, @Num;

WHILE @@FETCH_STATUS = 0 AND @Counter <= 3
BEGIN

    SET @Counter = @Counter + 1;
    UPDATE @T SET num = @Counter WHERE Id = @ID;

    IF @ID = 2
        BEGIN FETCH FIRST FROM c INTO @ID, @Num; END;
    ELSE 
        BEGIN FETCH NEXT FROM c INTO @ID, @Num; END;

END;

CLOSE c;

select * from @T;

获取:

Id  Num
1   3
2   4
3   0

请注意,从光标获得的值不会发生变化 因为只有1个打开和关闭。

答案 1 :(得分:0)

试试这个:

IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
    BEGIN 
        DROP TABLE #tmp;
    END;

CREATE TABLE #tmp (num INT IDENTITY(10,10))

-- **** execute separately ****
INSERT INTO #tmp DEFAULT VALUES
GO 10
-- ****************************
DECLARE c scroll cursor for select num FROM #tmp;
OPEN c;
DECLARE @i int = 1,
        @cursor_value INT;

 WHILE @i < 10
BEGIN

    IF @@FETCH_STATUS = 0 AND @i = 5 
    BEGIN
        FETCH FIRST FROM c INTO @cursor_value;
    END
    ELSE 
        FETCH NEXT FROM c INTO @cursor_value

    SELECT @i AS cntr, @cursor_value AS crsr

    SET @i +=1
END

close c
DEALLOCATE c