为什么我需要取两次

时间:2019-12-10 07:37:07

标签: sql sql-server database database-cursor

我有以下几行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永远存在!为什么要重复。

2 个答案:

答案 0 :(得分:3)

第一个FETCH用于获取WHILE之前的第一个值。只要先前的提取成功,在FETCH中的第二个WHILE就会提取。

请参见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

答案 1 :(得分:1)

一个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;