本来对存储过程不是很精,我们现在做的项目,基本上好多都是使用存储过程来完成一些业务逻辑的处理等。
这里举例使用存储过程来实现支付完成后商品库存减少的功能:
这里使用到了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来获取商品id
DECLARE 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 ) DO
set 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,'}&