为什么我需要取两次

Why do I need to fetch twice

我有这些行 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;

在循环 (while) 中,如果我删除该行,那么 myloop 将永远运行!为什么重复。

第一个FETCH是取WHILE之前的第一个值。 WHILE 中的第二个 FETCH 会在前一个抓取成功后抓取。

请参阅 official documentation 中的示例:

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

while 循环一直持续到达到退出条件为止。在这种情况下,当没有更多记录要处理时,循环应该退出。

因此

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;
    --Fetch is needed to proceed with the next record in order to check if its even and finally exit when there are no more any records left to be processed
 end;