mysql游标嵌套循环例子

CREATE PROCEDURE finance_reciveDetail(customer_id varchar(20))
BEGIN
  DECLARE done INT DEFAULT 0;
  DECLARE id_a bigint;
  DECLARE pre_recv_remain_a decimal(12,2);
	DECLARE storageId_a varchar(20);
  DECLARE pre_recv_remain_b decimal(12,2);
  DECLARE storageId_b varchar(20);
  DECLARE cur1 CURSOR FOR SELECT id,pre_recv_remain,storage_id
			 FROM `t_fin_pre_recive` WHERE 
			 pre_recv_customer_id = customer_id
			 AND pre_recv_remain>0  ORDER BY create_time ASC;

DECLARE cur2 CURSOR FOR SELECT ABS(pre_recv_remain),storage_id FROM 
				`t_fin_pre_recive` WHERE  pre_recv_remain<0 AND pre_recv_customer_id=customer_id;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  -- OPEN cur1;
  OPEN cur2;
	WHILE done = 0 DO -- 要有不然循环一次
		FETCH cur2 INTO pre_recv_remain_b,storageId_b; -- 退款的
    IF NOT done THEN  -- 要有不然循环一次
      OPEN cur1; 
			WHILE done = 0 DO  -- 要有不然循环一次
			FETCH cur1 INTO id_a, pre_recv_remain_a,storageId_a;
			IF NOT done THEN  -- 要有不然循环一次
			IF (pre_recv_remain_a < pre_recv_remain_b AND storageId_b=storageId_a)  THEN
          INSERT INTO `t_fin_pre_recive_order` (
		            pre_recv_id,
		            order_id,
		            order_amount,
		            order_type,
		            create_time
		            ) VALUES  (id_a,'',pre_recv_remain_a,2,NOW());
				UPDATE `t_fin_pre_recive` set pre_recv_remain ='0' WHERE id=id_a;
       ELSEIF pre_recv_remain_a = pre_recv_remain_b AND storageId_b=storageId_a THEN 
          INSERT INTO `t_fin_pre_recive_order`(
		            pre_recv_id,
		            order_id,
		            order_amount,
		            order_type,
		            create_time
		            ) VALUES  (id_a,'',pre_recv_remain_a,2,NOW());
				UPDATE `t_fin_pre_recive` set pre_recv_remain ='0' WHERE id=id_a;
			ELSEIF pre_recv_remain_a > pre_recv_remain_b AND storageId_b=storageId_a THEN
				INSERT INTO `t_fin_pre_recive_order` (
		            pre_recv_id,
		            order_id,
		            order_amount,
		            order_type,
		            create_time
		            ) VALUES  (id_a,'',pre_recv_remain_b,2,NOW());
				UPDATE `t_fin_pre_recive` set pre_recv_remain =(pre_recv_remain_a-pre_recv_remain_b) WHERE  id= id_a;
       END IF;
    END IF;
		END WHILE ;
		CLOSE cur1;
		SET done = 0 ; -- 重点设置为0 继续循环不然done=1时直接不循环了,外层的也不循环了
  END IF; 
END WHILE;
  CLOSE cur2;
END

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值