【问题标题】:What is the differece between my codes when I use cursor to fetch my data with repeat and do while?当我使用光标重复获取数据并执行时,我的代码有什么区别?
【发布时间】:2015-08-28 12:37:00
【问题描述】:

我使用游标来获取我的数据。我的数据数量是两个。但是我发现当我使用repeat 来获取我的数据时,它总是获取3次。而当我使用do while时,获取2次是正确的。这两种方式有什么不同?如何修复第一种方式?

--- The first way:wrong,have two datas but show 3 times
declare v_done tinyint default 0;
declare v_count int default 0;
declare v_id varchar(32);
declare v_result_cur cursor for select distinct(id) from book;
declare continue handler for not found set v_done = 1;
BEGIN
open v_result_cur;
repeat
 fetch v_result_cur into v_id;
 select v_id;  
until v_done end repeat;
close v_result_cur;
END;

第一种方法是错误的,第二种方法是正确的。

 --- The second way:right,have two datas but show 2 times
BEGIN
declare v_done tinyint default 0;
declare v_count int default 0;
declare v_id varchar(32);
declare v_result_cur cursor for select distinct(id) from book;
BEGIN
open v_result_cur;

 dept_loop:WHILE(v_done=0) DO
                 fetch v_result_cur into v_id;
                  select v_id; 
                 IF v_done=1 THEN
                    LEAVE dept_loop;
                 END IF;
END WHILE dept_loop;
close v_result_cur;
END;

【问题讨论】:

    标签: mysql stored-procedures cursor mysql-workbench


    【解决方案1】:

    只需在执行语句之前添加一个justment。

     open v_result_cur;
     repeat
     fetch v_result_cur into v_id;
     IF NOT v_done THEN
      select v_id; 
     END IF;
    until v_done end repeat;
    close v_result_cur;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2019-12-29
      • 2021-06-18
      • 2011-01-19
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      相关资源
      最近更新 更多