我有一个查询结果集(暂且标记它为t_tmp),如下所示:

另外,有一张原始表airport,它的last_people列是空的。

现在我想将我查询出来的结果集t_tmp中的last_people列填充到airport的last_people列。
由于需要一行一行对应的插入,所以想到了mysql的游标功能。下面是存储过程代码:
CREATE PROCEDURE fillLastPeople()BEGIN# 循环控制变量DECLARE done BOOLEAN DEFAULT 0;DECLARE tmp_city varchar(255);DECLARE tmp_current_people int;DECLARE tmp_last_people int;#定义游标DECLARE t_index cursor FORSELECT a.city,a.current_people,b.last_peopleFROM(SELECT city,current_people from airportwhere content_date = '2019') AS aINNER JOIN(SELECT city,current_people as last_people from airportwhere content_date = '2018') as bon a.city = b.city;#循环控制变量结束状态DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;#打开游标open t_index;REPEAT#捕获游标--对应上面声明时select语句有几列就into几列,并且保证类型正确FETCH t_index into tmp_city,tmp_current_people,tmp_last_people;#这里进行更新操作update airport set last_people=tmp_last_people where city=tmp_city and content_date='2019';UNTIL done END REPEAT;#关闭游标close t_index;END;
在mysql控制台输入上面这段存储过程代码前,需要输入delimiter // 保证;不会作为语句结束标记。
1、游标声明语法:
DECLARE 游标名称 cursor FOR select
2、 打开、关闭、使用游标
open 游标名称; close 游标名称; fetch 游标名称 into *
3、控制循环
DECLARE done BOOLEAN DEFAULT 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; REPEAT 具体逻辑 UNTIL done END REPEAT;
4、使用
delimiter ; call fillLastPeople(); //如果需要删除 drop PROCEDURE if EXISTS fillLastPeople;
参考文章:
