1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > mysql 存储过程中游标cur和while循环的嵌套使用

mysql 存储过程中游标cur和while循环的嵌套使用

时间:2020-06-05 18:27:07

相关推荐

mysql 存储过程中游标cur和while循环的嵌套使用

本来对存储过程不是很精,我们现在做的项目,基本上好多都是使用存储过程来完成一些业务逻辑的处理等。

这里举例使用存储过程来实现支付完成后商品库存减少的功能:

这里使用到了while循环和cur游标的循环嵌套。

main:BEGIN#处理付款成功减库存功能#传递参数是订单id(oid)DECLARE tpid varchar(100);#DECLARE rt int default 0;DECLARE tpoid varchar(100);DECLARE topprop varchar(100);DECLARE tcnt int default 0;declare done int default 0;DECLARE t_error INT DEFAULT 0;#根据toid来获取商品idDECLARE cur CURSOR FOR SELECT pid,opprop,cnt from 表 where oid = tpoid;DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;while( locate(',',toid) >0 ) DOset tpoid = left(toid,locate(',',toid)-1);set toid=substr(toid,locate(',',toid)+1);#遍历商品中指定规格商品数量open cur;fetch cur into tpid,topprop,tcnt;update 库存表 set stock=stock-tcnt where proid=tpid and itemvalues=CONCAT('{',topprop,'}');close cur;end while;#获取参数toid,toid中可能包含多个订单号,用逗号分隔,所以要先处理#逗号第一出现的位置#set rt=locate(',',toid);if(locate(',',toid) = 0)then set tpoid = toid;#遍历商品中指定规格商品数量open cur;fetch cur into tpid,topprop,tcnt;update 库存表 set stock=stock-tcnt where proid=tpid and itemvalues=CONCAT('{',topprop,'}');close cur;end if;END

这里刚开始把repeat循环和while循环同时使用了,总是执行一次,多个订单的话,就执行第一个订单,后面的不执行。

while( locate(',',toid) >0 ) DOset tpoid = left(toid,locate(',',toid)-1);set toid=substr(toid,locate(',',toid)+1);#遍历商品中指定规格商品数量open cur;repeatfetch cur into tpid,topprop,tcnt;if(!done) thenupdate 库存表 set stock=stock-tcnt where proid=tpid and itemvalues=CONCAT('{',topprop,'}');end if;until doneend repeat;close cur;end while;

这里使用了repeat来循环游标cur,直到游标到最后时,done=1。造成了repeat和while循环混用。

mysql存储过程中的三种循环方法:while ,loop,repeat三种。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。