mysql 游标 会多循环一次_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;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值