开发者社区 问答 正文

为什么需要取两次?

我有以下几行SQL:

begin
    declare @eid int;

    declare cursor_emp cursor for 
    select id from employee2;

        /*open the dam curson*/
        open cursor_emp;

    fetch next from cursor_emp  into @eid;

        /*0 =The FETCH statement was successful.*/
        while @@FETCH_STATUS =0 
        begin

                if (@eid %2 =0)
                 begin
                    print ('This one is even!');
                 end;
    /* I don't know why the repeating line necessary*/
    fetch next from cursor_emp  into @eid;
        end;
    close cursor_emp;
    deallocate cursor_emp
end

一切正常。应该检查id是否为偶数。我不明白为什么我需要两次

/* I don't know why the repeating line necessary*/ fetch next from cursor_emp into @eid; 在循环内(同时),如果我删除该行,则myloop永远存在!为什么重复。

展开
收起
心有灵_夕 2019-12-10 17:34:21 681 分享 版权
1 条回答
写回答
取消 提交回答
  • 第一个FETCH是获取之前的第一个值WHILE。只要先前的提取成功,第二个FETCH内部WHILE提取操作就会执行。

    请参阅官方文档中的以下示例:

    OPEN contact_cursor;  
    
    -- Perform the first fetch.  
    FETCH NEXT FROM contact_cursor;  
    
    -- Check @@FETCH_STATUS to see if there are any more rows to fetch.  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
       -- This is executed as long as the previous fetch succeeds.  
       FETCH NEXT FROM contact_cursor;  
    END  
    
    CLOSE contact_cursor;  
    DEALLOCATE contact_cursor;
    

    但是您也可以使用以下简单方法解决此问题SELECT:

    SELECT id, CASE WHEN id % 2 = 0 THEN 1 ELSE 0 END AS isEven 
    FROM employee2
    
    2019-12-10 17:34:51
    赞同 展开评论
问答地址: