mysql存储过程之循环遍历查询结果集
-- 创建存储过程之前需判断该存储过程是否已存在,若存在则删除
DROP PROCEDURE IF EXISTS init_reportUrl;
-- 创建存储过程
CREATE PROCEDURE init_reportUrl()
BEGIN
-- 定义变量
DECLARE s int DEFAULT 0;
DECLARE report_id varchar(255);
DECLARE report_url varchar(256);
-- 定义游标,并将sql结果集赋值到游标中
DECLARE report CURSOR FOR select reportId,reportUrl from patrolReportHistory;
-- 声明当游标遍历完后将标志变量置成某个值
DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1;
-- 打开游标
open report;
-- 将游标中的值赋值给变量,注意:变量名不要和返回的列名同名,变量顺序要和sql结果列的顺序⼀致
fetch report into report_id,report_url;
-- 当s不等于1,也就是未遍历完时,会⼀直循环
while s<>1 do
-- 执⾏业务逻辑
update patrolreporthistory set reportUrl = CONCAT('patrolReport.html?monitorId=',substring(report_url,15,1),'&reportId=',report_id) where reportId=report_id;
-- 将游标中的值再赋值给变量,供下次循环使⽤
fetch report into report_id,report_url;
mysql存储过程使用-- 当s等于1时表明遍历以完成,退出循环
end while;
-- 关闭游标
close report;
END;
-- 执⾏存储过程
call init_reportUrl()
---------------------