mysql 游标 + while 多循环一次

什么鬼

在使用游标 + loop 或者游标 + while进行遍历操作的时候,往往会遇到多执行一次的情况。例如,select 出来的是 1 条数据,然而进行了两次循环。例如:

declare xxx int
declare done INT DEFAULT FALSE;
declare cursor cur for select xxx from xxx;
declare continue handler for not found set done = true;
open cur;
while not done do
  fetch cur into xxx;
   -- do someting
end while;
close cur;

这个鬼

其根本的原因是无论是游标 + loop 或者游标 + while都需要进程捕捉到not found的异常后才将 done = true,按道理说,应该执行完就结束了,但是还忘记了一点,我们使用的异常捕捉类型是continue,这种类型的特点是当日常发生后 mysql 的内核还会继续往下执行,直到执行到语句块的结束。所以表现为多循环了一次。
解决的方法:

  • 在执行 do something 的之前加一个对 done 的判断
  • 使用exit类型的异常捕捉
  • fetch cur into xxx;放到 do something 之后,这样当 not found 发生后,由于
    fetch cur into xxx;之后没有代码,所以也不会多执行一次。

画符咒

正确的写法如下:

declare xxx int
declare done INT DEFAULT FALSE;
declare cursor cur for select xxx from xxx;
declare exit handler for not found set done = true;
open cur;
while not done do
  fetch cur into xxx;
  if not done then
   -- do someting
  end if;
end while;
close cur;

或者

declare xxx int
declare done INT DEFAULT FALSE;
declare cursor cur for select xxx from xxx;
declare continue handler for not found set done = true;
open cur;
fetch cur into xxx;
while not done do
   -- do someting
  fetch cur into xxx;
end while;
close cur;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 创建游标首先在MySql中创建一张数据表: CREATE TABLE IF NOT EXISTS store (i...
    听说我很强阅读 4,887评论 0 1
  • 1.PLSQL入门 Oracle数据库对SQL进行了扩展,然后加入了一些编程语言的特点,可以对SQL的执行过程进行...
    随手点灯阅读 3,751评论 0 8
  • 之前在项目上遇到一个问题,实施人员在数据库中建了许多临时的测试数据,在正式客户环境中是要删掉的,但是产品页面上没有...
    Walkerc阅读 7,618评论 0 1
  • oracle存储过程常用技巧 我们在进行pl/sql编程时打交道最多的就是存储过程了。存储过程的结构是非常的简单的...
    dertch阅读 8,804评论 1 12
  • 1、Check规则 Check (Agebetween15and30 )把年龄限制在15~30岁之间 2、新SQL...
    姜海涛阅读 4,371评论 0 4