当前位置:网站首页>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 !
边栏推荐
- JS merge two 2D arrays and remove the same items (collation)
- Maidong Internet won the bid of Dajia Insurance Group
- 位图的详细介绍及模拟实现
- Detailed introduction and Simulation of bitmap
- Partial mock of static class of phpunit operation
- QQ如何开通在线客服
- kubekey2.2.1 kubernetes1.23.7离线包制作+harbor部暑并上传镜像
- Split palindrome string [dp + DFS combination]
- Codeworks 5 questions per day (1700 for each) - the next day
- 阿里云不同账号新旧服务器镜像迁移数据迁移同步
猜你喜欢

Let's start with a bug that was cheated by the app store

Serial port experiment based on stm32f103zet6 library function
![[target tracking] |stark configuration win OTB](/img/29/a6b3b99b7d2349499aede9e76ab29a.png)
[target tracking] |stark configuration win OTB

Top 30 open source software

Two controller layer interface authentication methods

Software testing - you may not understand the basic theoretical knowledge

小白月赛51 补题 E G F
![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]](/img/33/bda0a898bfe3503197026d1f62e851.png)
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]

YoloV6+TensorRT+ONNX:基于WIN10+TensorRT8+YoloV6+ONNX的部署

VB.Net读写NFC Ntag标签源码
随机推荐
MySql存储过程循环的使用分析详解
Shell tutorial circular statements for, while, until usage
[webdriver] upload files using AutoIT
ISO 32000-2 国际标准7.7
Detailed introduction and Simulation of bitmap
What value can SRM systems bring to the enterprise?
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
YoloV6+TensorRT+ONNX:基于WIN10+TensorRT8+YoloV6+ONNX的部署
VMware installation esxi
Walk with love, educate and run poor families, and promote public welfare undertakings
What is a SCM system? What are the advantages of a supply chain management system?
Split palindrome string [dp + DFS combination]
mongoTemplate - distinct 使用
MATLAB 最远点采样(FPS)
【TcaplusDB知识库】TcaplusDB系统用户组介绍
3H proficient in opencv (VI) - image stacking
shell教程之循环语句for,while,until用法
Proxmox VE Install 7.2
【TcaplusDB知识库】TcaplusDB单据受理-建表审批介绍
分布式 | 几步快速拥有读写分离