【问题标题】:Why do I need to fetch twice为什么我需要获取两次
【发布时间】:2019-12-10 07:37:07
【问题描述】:

我有这几行 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 已经从列中提取所有记录。

标签: sql sql-server database database-cursor


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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;
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 2019-12-17
      • 1970-01-01
      • 2018-01-20
      • 2019-08-07
      • 1970-01-01
      • 2023-04-09
      • 2015-04-03
      • 2019-11-20
      相关资源
      最近更新 更多