我有一个查询结果集(暂且标记它为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 FOR
SELECT a.city,a.current_people,b.last_people
FROM
(SELECT city,current_people from airport
where content_date = '2019'
) AS a
INNER JOIN
(SELECT city,current_people as last_people from airport
where content_date = '2018'
) as b
on 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;
参考文章: