mysql 游标的使用总结

一、游标的基本概念

       游标:游标是一个存储在Mysql服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。

      本人,学习游标中,曾遇到一个问题,循环总是最后多执行一次。下面分析程序,这个是一个sql脚本程序

       #if d=0 then   #end if; 注释掉这两行时,会发现,游标中的repeat循环总是多执行一次。

       vendors 表中之前的数据为:

                                                                       图1

二、程序及结果分析

delimiter //
create procedure procursor(in num int)
begin
  declare d boolean default 0;
  declare o int;
  declare t int;
  declare c int default 0;
  declare mycur cursor for select vend_id from vendors;
  declare continue handler for sqlstate '02000' set d =1 ;
  create table if not exists results(re_id int,re_num int);
  open mycur;
 repeat
  fetch mycur into o;
#if d=0 then
  select o;
  # set t=o*num;
  insert into results values(o,num*o);
  set c=c+1;
 select d;
# end if;
 until d end repeat;
   close mycur;
select * from results;
select c;
end //
 delimiter ;

注释 #if d=0 then 和# end if;  执行以上sql语句后,call procursor(100); 执行结果如图2所示;发现,游标的循环总是多执行了一次,执行了4次疑问,

分析发现,原因在于,最后一次fetch mycur into o;时,mycur 为空 ,o值未更改,所以,最后一组值,多执行了一次。此时若检测d的值,发现d为1。将#if d=0 then和# end if;注释去掉,做一个条件判断后的结果如图3所示。

结果正确大笑


          

                      图2                                                                                                图3

原文地址:https://www.cnblogs.com/chhuach2005/p/3961699.html