| 
       
	本来对存储过程不是很精,我们现在做的项目,基本上好多都是使用存储过程来完成一些业务逻辑的处理等。 
	这里举例使用存储过程来实现支付完成后商品库存减少的功能: 
	 这里使用到了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,'}'); 
	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 ) DO 
	set tpoid = left(toid,locate(',',toid)-1); 
	set toid=substr(toid,locate(',',toid)+1); 
	#遍历商品中指定规格商品数量 
	open cur; 
	      repeat 
	fetch cur into tpid,topprop,tcnt; 
	if(!done) then 
	update 库存表 set stock=stock-tcnt where proid=tpid and itemvalues=CONCAT('{',topprop,'}'); 
	end if; 
	until done 
	end repeat; 
	close cur; 
	  end while; 
	这里使用了repeat来循环游标cur,直到游标到最后时,done=1。造成了repeat和while循环混用。 
	mysql存储过程中的三种循环方法:while ,loop,repeat三种。 
 | 
    
