FETCH未完成空白

时间:2018-05-31 07:32:43

标签: sql-server tsql fetch

我遇到问题FETCH我正在使用它:

DECLARE Something CURSOR FOR  
SELECT * FROM tblSomething

OPEN Something

WHILE @@FETCH_STATUS = 0
    BEGIN   
        --CALL ANOTHER PROCEDURE
        FETCH NEXT FROM Something
    END 
CLOSE Something
DEALLOCATE Something

问题是表中有10行,11行出来,第11行是空白数据。我认为这是获取下一行并意识到没有下一行。我需要某种形式:

IF FETCH_ROWS = MAX then STOP

或类似的东西。

1 个答案:

答案 0 :(得分:1)

尝试在FETCH NEXT FROMOPEN之间添加WHILE

DECLARE Something CURSOR FOR  
SELECT * FROM tblSomething

OPEN Something
FETCH NEXT FROM Something   --  <== add this line
WHILE @@FETCH_STATUS = 0
    BEGIN   
        --CALL ANOTHER PROCEDURE
        FETCH NEXT FROM Something
    END 
CLOSE Something
DEALLOCATE Something

这是一个简单的演示,包含一个10行的表和一个读取每一行并打印相应ID的游标:

declare @tmp table (row_id int)
insert into @tmp values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10) 

DECLARE @myID as int;
DECLARE @wf_Cursor as CURSOR;
SET @wf_Cursor = CURSOR FOR SELECT row_id FROM @tmp

OPEN @wf_Cursor;
    FETCH NEXT FROM @wf_Cursor INTO @myID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            print('Reading row: ' + cast(@myID as nvarchar(10)));
            FETCH NEXT FROM @wf_Cursor INTO @myID;
        END
CLOSE @wf_Cursor;
DEALLOCATE @wf_Cursor;

输出:

enter image description here