MySql存储过程循环的使用分析详解

简介

每一门数据库语言语法都基本相似,但是对于他们各自的一些特性(函数、存储过程等)的用法就不大相同了,就好比oraclemysql存储过程写起来就很多不同的地方,在这里主要是跟大家分享一下mysql存储过程中使用游标循环的处理方法。

场景描述

我们举一个简单的场景,首先我们可能会有这样一种情况,考试成绩表(t_achievement)有一堆的sql脚本处理,需要依赖另一个学生表(t_student)数据对部分学生做考试成绩汇总记录到成绩汇总表(t_achievement_report)。

解决方案

  • 有一种方式就是通过代码优先将要汇总的学生表数据获取出来,然后按成绩汇总流程逐个将学生信息数据传递到成绩汇总业务代码进行处理。
  • 另一种方式也是我们今天的主题,那就是通过存储过程的方式去做。

案例

建表语句:

-- 学生信息表
drop table if exists t_student;
create table `t_student` (
  `id` bigint(12) not null auto_increment comment '主键',
  `code` varchar(10) not null comment '学号',
  `name` varchar(20) not null comment '姓名',
  `age` int(2) not null comment '年龄',
  `gender` char(1) not null comment '性别(m:男,f:女)',
  primary key (`id`),
  unique key uk_student (`code`)
) charset=utf8mb4 collate=utf8mb4_general_ci;
-- 学生成绩表
drop table if exists t_achievement;
create table `t_achievement` (
  `id` bigint(12) not null auto_increment comment '主键',
  `year` int(4) not null comment '学年',
  `subject` char(2) not null comment '科目(01:语文,02:数学,03:英语)',
  `score` int(3) not null comment '得分',
  `student_id` bigint(12) not null comment '所属学生id',
  primary key (`id`) 
) charset=utf8mb4 collate=utf8mb4_general_ci;
-- 成绩汇总表
drop table if exists t_achievement_report;
create table `t_achievement_report` (
  `id` bigint(12) not null auto_increment comment '主键',
  `student_id` bigint(12) not null comment '学生id',
  `year` int(4) not null comment '学年',
  `total_score` int(4) not null comment '总分',
  `avg_score` decimal(4,2) not null comment '平均分',
  primary key (`id`) 
) charset=utf8mb4 collate=utf8mb4_general_ci;

初始化数据:

insert into t_student(id, code, name, age, gender) values
(1, '2022010101', '小张', 18, 'm'),
(2, '2022010102', '小李', 18, 'f'),
(3, '2022010103', '小明', 18, 'm');
insert into t_achievement(year, subject, score, student_id) values
(2022, '01', 80, 1),
(2022, '02', 85, 1),
(2022, '03', 90, 1),
(2022, '01', 60, 2),
(2022, '02', 90, 2),
(2022, '03', 98, 2),
(2022, '01', 75, 3),
(2022, '02', 100, 3),
(2022, '03', 85, 3);

存储过程:

在这里主要以上面的场景为例,使用存储过程循环去处理数据。写一个存储过程,将以上数据每个学生的成绩进行汇总。

-- 如果存储过程存在,先删除存储过程
drop procedure if exists statistics_achievement;
delimiter $$
-- 定义存储过程
create procedure statistics_achievement()
begin
        -- 定义变量记录循环处理是否完成
	declare done boolean default false;
        -- 定义变量传递学生id
	declare studentid bigint(12);
	-- 定义游标
	declare cursor_student cursor for select id from t_student;
	-- 定义continue handler,当循环结束时 done=true
	declare continue handler for sqlstate '02000' set done=true;
	-- 打开游标
	open cursor_student;
	-- 重复遍历
	repeat 
		-- 每次读取一次游标
		fetch cursor_student into studentid;
                -- 计算总分、平均分插入汇总表
		insert into t_achievement_report(student_id, `year`, total_score, avg_score)
		select studentid, `year`, sum(score), round(sum(score) / 3, 2) from t_achievement t1 where student_id = studentid and not exists(
			select 1 from t_achievement_report t2 where student_id = studentid and t1.year = t2.year
		) group by `year`;
	-- 结束循环,意思是等到done=true时,结束循环repeat
	until done end repeat;
	-- 查询结果,仅会展示查出的最后一条
	select studentid;
	-- 关闭游标
	close cursor_student;
end$$
delimiter ;
-- 执行存储过程
call statistics_achievement();
  • 执行结果,返回查询结果3,即最后一条学生记录id

总结

存储过程也有很强大的功能,如果是一名dba那么写存储过程是分分钟的事,但是作为一名专做业务的码农还是不建议去使用存储过程写业务代码。前公司同事适应了写存储过程,有业务改动时不时的直接用存储过程搞定了,到最后直接就是一大堆堆存储过程代码,一个存储过程下来几百上千行sql代码头都看晕掉,出问题巨难维护,稍有不熟的人员都不敢轻举妄动,今天在这里也只是为了讲解存储过程中的循环而举了个栗子请别介意。

总之我认为存储过程主要还是用来临时处理一些数据方便而用一下,特别有些业务改造大,需要做数据割接总不能挨个去写一个业务代码吧。

到此这篇关于mysql存储过程循环的使用分析详解的文章就介绍到这了,更多相关mysql存储过程循环内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

(0)
上一篇 2022年7月1日
下一篇 2022年7月1日

相关推荐