代码之家  ›  专栏  ›  技术社区  ›  Kiel

提取未完成空白

  •  1
  • Kiel  · 技术社区  · 6 年前

    我有个问题 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 回复  |  直到 6 年前
        1
  •  1
  •   Andrea    6 年前

    尝试添加 FETCH NEXT FROM 之间 OPEN 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