当前位置:网站首页>Detailed analysis on the use of MySQL stored procedure loop
Detailed analysis on the use of MySQL stored procedure loop
2022-06-29 18:07:00 【1024 Q】
brief introduction
Scene description
Solution
Case study
summary
brief introduction The syntax of every database language is basically similar , But for their own characteristics ( function 、 Stored procedure, etc ) The usage of is not the same , like Oracle And Mysql Stored procedures are written in many different ways , Here is mainly to share with you MySql The method of using cursor loop in stored procedure .
Let's take a simple scenario , First of all, we may have such a situation , Test results (t_achievement) There's a pile of sql Script processing , Need to rely on another student table (t_student) The data is used to summarize the test scores of some students and record them in the score summary table (t_achievement_report).
One way is to get the student table data to be summarized through code priority , Then the student information data will be transferred to the score summary business code for processing one by one according to the score summary process .
Another way is also our topic today , That is to do it through stored procedures .
Case studyCreate table statement :
-- Student information sheet DROP TABLE IF EXISTS t_student;CREATE TABLE `t_student` ( `id` BIGINT(12) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ', `code` VARCHAR(10) NOT NULL COMMENT ' Student number ', `name` VARCHAR(20) NOT NULL COMMENT ' full name ', `age` INT(2) NOT NULL COMMENT ' Age ', `gender` CHAR(1) NOT NULL COMMENT ' Gender (M: male ,F: Woman )', PRIMARY KEY (`id`), UNIQUE KEY UK_STUDENT (`code`)) CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;-- Student transcript DROP TABLE IF EXISTS t_achievement;CREATE TABLE `t_achievement` ( `id` BIGINT(12) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ', `year` INT(4) NOT NULL COMMENT ' school year ', `subject` CHAR(2) NOT NULL COMMENT ' subject (01: Chinese language and literature ,02: mathematics ,03: English )', `score` INT(3) NOT NULL COMMENT ' score ', `student_id` BIGINT(12) NOT NULL COMMENT ' Student id', PRIMARY KEY (`id`) ) CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;-- Summary of grades DROP TABLE IF EXISTS t_achievement_report;CREATE TABLE `t_achievement_report` ( `id` BIGINT(12) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ', `student_id` BIGINT(12) NOT NULL COMMENT ' Student id', `year` INT(4) NOT NULL COMMENT ' school year ', `total_score` INT(4) NOT NULL COMMENT ' Total score ', `avg_score` DECIMAL(4,2) NOT NULL COMMENT ' average ', PRIMARY KEY (`id`) ) CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;Initialization data :
INSERT INTO t_student(id, CODE, NAME, age, gender) VALUES(1, '2022010101', ' Xiao Zhang ', 18, 'M'),(2, '2022010102', ' petty thief ', 18, 'F'),(3, '2022010103', ' Xiao Ming ', 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);

stored procedure :
Take the above scenario as an example , Use stored procedure loops to process data . Write a stored procedure , Summarize the above data and the scores of each student .
-- If the stored procedure exists , Delete the stored procedure first DROP PROCEDURE IF EXISTS statistics_achievement;DELIMITER $$-- Define stored procedures CREATE PROCEDURE statistics_achievement()BEGIN -- Define whether the variable record cycle processing is completed DECLARE done BOOLEAN DEFAULT FALSE; -- Define variables to pass to students idDECLARE studentid BIGINT(12);-- Define cursors DECLARE cursor_student CURSOR FOR SELECT id FROM t_student;-- Definition CONTINUE HANDLER, When the loop ends done=trueDECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=TRUE;-- Open cursor OPEN cursor_student;-- Iterate through REPEAT -- One read at a time cursor FETCH cursor_student INTO studentid; -- Calculate the total score 、 The average score is inserted into the summary table 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`;-- End of cycle , It means to wait until done=true when , End of cycle REPEATUNTIL done END REPEAT;-- Query results , Only the last one found will be shown SELECT studentid;-- Close cursor CLOSE cursor_student;END$$DELIMITER ;-- Execute stored procedures CALL statistics_achievement();Execution results , Return query results 3, The last student record id


Stored procedures also have powerful functions , If it's a DBA So writing stored procedures is a matter of minutes , But as a yard farmer who specializes in business, I still It is not recommended to use stored procedures to write business code . Former company colleagues adapted to writing stored procedures , If there are business changes, you can directly use stored procedures from time to time , In the end, it's just a lot of stored procedure code , A stored procedure has hundreds or thousands of lines sql I feel dizzy when I see the wharf , If something goes wrong, it is very difficult to maintain , People who are a little unfamiliar dare not act rashly , Today, I just give you a chestnut to explain the loop in the stored procedure. Please don't mind .
In short, I think stored procedures are mainly used to temporarily process some data for convenience , In particular, some businesses have been transformed greatly , If you need to cut data, you can't write business code one by one .
This is about MySql This is the end of the detailed analysis of the use of stored procedure loops , More about MySql For the content of stored procedure loop, please search the previous articles of SDN or continue to browse the related articles below. I hope you can support SDN more in the future !
边栏推荐
- 基于注解和拦截器防止表单重复提交
- Configure the local domain name through the hosts file
- 小白月赛51 补题 E G F
- Abc253 D fizzbuzz sum hard (tolerance exclusion theorem)
- What is the SRM system? How do I apply the SRM system?
- js两个一维数组合并并去除相同项(整理)
- 两种Controller层接口鉴权方式
- Visio标注、批注位置
- MaxCompute字符串替换函数-replace
- 2022 spring summer collection koreano essential reshapes the vitality of fashion
猜你喜欢

位图的详细介绍及模拟实现

两种Controller层接口鉴权方式

ABC253 D FizzBuzz Sum Hard(容斥定理)

Parental delegation mechanism

Wechat applet development reserve knowledge

Proxmox VE Install 7.2

JS merge two 2D arrays and remove the same items (collation)

ISO 32000-2 international standard 7.7

DevCloud加持下的青软,让教育“智”上云端

Opencv+yolo-v3 for target tracking
随机推荐
3h精通OpenCV(七)-颜色检测
kubekey2.2.1 kubernetes1.23.7离线包制作+harbor部暑并上传镜像
What is a SCM system? What are the advantages of a supply chain management system?
Fill in the next right node pointer of each node [make good use of each point - > reduce the space-time complexity as much as possible]
软件测试——基础理论知识你都不一定看得懂
Bloom filter:
Opencv+yolo-v3 for target tracking
MySql存储过程循环的使用分析详解
【目标跟踪】|stark配置 win otb
Inherit Chinese virtues, pay attention to the health of the middle-aged and the elderly, and Yurun milk powder has strong respect for the elderly
Test dble split function execution + import time-consuming shell script reference
codeforces每日5题(均1700)-第二天
Function independent watchdog (iwdg) experiment based on stm32f103zet6 Library
3H proficient in opencv (VIII) - shape detection
Selenium upload file
测试dble split功能执行+导入耗时shell脚本参考
EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
Visual studio plug-in coderush officially released v22.1 -- visual tool for optimizing debugging
MATLAB 最远点采样(FPS)
JS merge two 2D arrays and remove the same items (collation)