mysql存储过程之循环遍历查询结果集

版权声明:本文为博主(yjclsx)的原创文章,未经博主允许不得转载。 https://blog.csdn.net/yjclsx/article/details/84566009
-- 创建存储过程之前需判断该存储过程是否已存在,若存在则删除
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;
		-- 当s等于1时表明遍历以完成,退出循环
		end while;
	-- 关闭游标
	close report;
END;
-- 执行存储过程
call init_reportUrl()

猜你喜欢

转载自blog.csdn.net/yjclsx/article/details/84566009
今日推荐