php mysql 游标_mysql 游标的使用总结

一、游标的基本概念 游标:游标是一个存储在Mysql服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。 本人,学习游标中,曾遇到一个问题,循环总是最后多执行一次。下面分析程序,这个是一个sql脚本程序 #if d=0 then #end if; 注

一、游标的基本概念

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

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

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

vendors 表中之前的数据为:

test.jsp?url=http%3A%2F%2Fimg.blog.csdn.net%2F20140509165927187%3Fwatermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hodWFjaDIwMDU%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast&refer=http%3A%2F%2Fblog.csdn.net%2Fchhuach2005%2Farticle%2Fdetails%2F25409023

图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次

test.jsp?url=http%3A%2F%2Fstatic.blog.csdn.net%2Fxheditor%2Fxheditor_emot%2Fdefault%2Fdoubt.gif&refer=http%3A%2F%2Fblog.csdn.net%2Fchhuach2005%2Farticle%2Fdetails%2F25409023,

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

结果正确

test.jsp?url=http%3A%2F%2Fstatic.blog.csdn.net%2Fxheditor%2Fxheditor_emot%2Fdefault%2Flaugh.gif&refer=http%3A%2F%2Fblog.csdn.net%2Fchhuach2005%2Farticle%2Fdetails%2F25409023

test.jsp?url=http%3A%2F%2Fimg.blog.csdn.net%2F20140509180903984%3Fwatermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hodWFjaDIwMDU%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast&refer=http%3A%2F%2Fblog.csdn.net%2Fchhuach2005%2Farticle%2Fdetails%2F25409023

test.jsp?url=http%3A%2F%2Fimg.blog.csdn.net%2F20140509180945578%3Fwatermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hodWFjaDIwMDU%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast&refer=http%3A%2F%2Fblog.csdn.net%2Fchhuach2005%2Farticle%2Fdetails%2F25409023

图2 图3

f68f2add0b68e4f9810432fce46917b7.png

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值