Mysql 利用游标遍历查询结果集并操作

/*我们有时候会遇到需要对 从A表查询的结果集S_S 的记录 进行遍历并做一些操作(如插入),且这些操作需要的数据或许部分来自S_S集合*/
/*临时存储过程,没办法,不能直接在查询窗口做这些事。*/
drop procedure if exists proc_tmp;
create procedure proc_tmp()
BEGIN
/*这种写法也可以:
DECLARE
 
done 
INT
 
DEFAULT
 
FALSE
;
*/
declare done int default 0;  /*用于判断是否结束循环*/
declare hostId bigint; /*用于存储结果集S_S的记录(因为我这里S_S的记录只有一列且为bigint类型)*/

/*定义游标*/
declare idCur cursor for select id from wkp_order where source = '1';
/*定义 设置循环结束标识done值怎么改变 的逻辑*/
declare continue handler for not FOUND set done = 1; /*done = true;亦可*/

open idCur;  /*打开游标*/

/* 循环开始 */
REPEAT
/* 如果要fetch多列应该这样写,fetch cur/*对应下面的idCur*/ 
		/*into rowId, rowName; 但是注意rowId和rowName要先declare,且declare cur时也要select两列,且这两列和rowId、rowName对应 */
		fetch idCur into hostId;  /*这部分可以看看书,还可以fetch多列(假设结果集S_S的记录不是单列的话)*/
				if not done THEN  /*数值为非0,MySQL认为是true*/

        INSERT into wkp_trade_log ( user_id, change_direction , type, order_no, amount, create_time , account_before, account_after) select seller_user_id ,'in','pay',order_no, (total_amount * 0.99) total_amount , create_time, 0 , 0 from wkp_order where source = '1' and id = hostId;

				INSERT into wkp_trade_log ( user_id, change_direction , type, order_no, amount, create_time , account_before, account_after) select seller_user_id user_id ,'out','payFee',order_no, (total_amount * 0.01) total_amount , create_time, 0 , 0 from wkp_order where source = '1' and id = hostId;

				end if;
until done end repeat;

close idCur;  /*关闭游标*/
END
/* 循环结束 */

call proc_tmp();
drop procedure proc_tmp;  /*删除临时存储过程*/

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未来AI编程

共鸣===鼓励 打赏您随意

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值