/*我们有时候会遇到需要对 从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; /*删除临时存储过程*/
Mysql 利用游标遍历查询结果集并操作
猜你喜欢
转载自blog.csdn.net/wxb880114/article/details/81017884
今日推荐
周排行