Detailed explanation of MySQL stored procedures, cursors, and transaction examples

Detailed explanation of MySQL stored procedures, cursors, and transaction examples

Detailed explanation of MySQL stored procedures, cursors, and transaction examples

The following is a MySQL database stored procedure that I have written. I keep it for archiving and use it for reference in the future.

Among them, stored procedures, cursors (double loops), and transactions are involved.

[Note]: The comments in the code are only for the current business and can be ignored.

The code is as follows:

DELIMITER $$
DROP PROCEDURE IF EXISTS `transferEmailTempData`$$

CREATE PROCEDURE transferEmailTempData(IN jobId VARCHAR(24))
BEGIN
  DECLARE idval VARCHAR(24) DEFAULT '';
  DECLARE taskIdval VARCHAR(24) DEFAULT '';
  DECLARE groupIdval VARCHAR(24) DEFAULT '';
  DECLARE emailval VARCHAR(50) DEFAULT '';
  
  /*Identify whether there is an identical data in the formal table, i.e., groupId and email are the same*/
  DECLARE infoId VARCHAR(24) DEFAULT '';
  
  /*Transaction error*/
  DECLARE err INT DEFAULT 0;
  
  /*Submit when a certain number is reached, counter*/
  DECLARE counts INT DEFAULT 0;
  
  /*Identify whether it has been rolled back*/
  DECLARE isrollback INT DEFAULT 0;
  
  /*When the cursor is traversing, it is used as a mark to determine whether all records have been traversed*/
  DECLARE done INTEGER DEFAULT 0;
  
  /*Get the data of the task in the temporary table*/
  DECLARE cur CURSOR FOR SELECT id,taskId,groupId,email FROM `t_email_data_temp` WHERE taskId=jobId;
  
  /*Query whether there are identical records based on group id and email*/
  DECLARE cur2 CURSOR FOR SELECT id FROM `t_email_info` e WHERE e.`group_id` = groupIdval AND e.`email_address` = emailval; 
  
  /* Error occurs, set to 1, rollback as long as an exception occurs*/
  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err=1;
  
  /*Declare that when the cursor traverses all records, the flag variable will be set to a certain value*/
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET done=1;
  
  /*Start transaction*/
  START TRANSACTION;
  
  /*Open cursor*/
  OPEN cur;
  
  /*Use LOOP to loop through*/
  out_loop:LOOP
  
    /*Assign the field value corresponding to each result to the variable*/
    FETCH cur INTO idval,taskIdval,groupIdval,emailval;
    IF done = 1 THEN
      LEAVE out_loop;
    END IF;
    
    /*Open the second cursor*/
    OPEN cur2;
      SET done = 0;
      FETCH cur2 INTO infoId;
      
      /*If the official table does not have the same groupId and email record, add it to the official table*/
      IF done = 1 THEN
      
        /*Insert into the formal table*/
        INSERT INTO `t_email_info` VALUES(idval,emailval,groupIdval,0,'',NOW(),'admin',NOW(),'admin');
        
        /*Delete temporary data*/
        DELETE FROM `t_email_data_temp` WHERE id = idval;
        
        /*Counter, submit every 1000 items*/
        SET counts = counts + 1;
        
        /*Exception occurred, rollback*/
        IF err=1 THEN
          SET isrollback=1;
          ROLLBACK;
        ELSE
          IF counts = 1000 THEN
            COMMIT;
            /*After reaching 1000 submissions, reset the counter*/
            SET counts=0;
          END IF;
        END IF;
      ELSE
        /*If the same record already exists, delete it*/
        IF done=0 THEN
          DELETE FROM `t_email_data_temp` WHERE id = idval;
        END IF;
      END IF;
      FETCH cur2 INTO infoId;
    CLOSE cur2;
    
    /*Control the external loop. This step cannot be missing, otherwise it will end after only one loop*/
    SET done=0;
    
  END LOOP out_loop;
  CLOSE cur;
  
  /*If no rollback event has occurred, update the task status*/
  /*If the task is rolled back and the task status is not updated, the remaining uncommitted data will be added to the formal table again when the task is executed next time*/
  IF isrollback=0 THEN
    UPDATE `t_email_task` t SET t.`if_finish` = 1 WHERE t.`id`=jobId;
  END IF;
  
  END$$

DELIMITER ;

The above is an explanation of MySQL stored procedures, cursors, and transactions. If you have any questions, please leave a message or discuss in the community of this site. Thank you for reading and I hope it can help you. Thank you for your support of this site!

You may also be interested in:
  • Introduction to the use of MySQL stored procedure cursor loop
  • Example of exiting and continuing the cursor loop in MySQL stored procedures
  • Mysql stored procedure nested loop using cursor sample code
  • Example of using cursor in mysql stored procedure
  • MySQL dynamic cursor learning (MySQL stored procedure cursor)
  • Detailed explanation of the principle and usage of cursor (DECLARE) in MySQL stored procedure
  • Example of using cursor in Mysql stored procedure
  • Using cursor loop to read temporary table in Mysql stored procedure
  • Examples of using MySql stored procedures and cursors

<<:  Summary of solutions to common Linux problems

>>:  JavaScript custom plug-in to implement tab switching function

Recommend

MySQL 8.0.19 installation and configuration tutorial under Windows 10

I will be learning MySQL next semester. I didn...

CSS text alignment implementation code

When making forms, we often encounter the situati...

An example of the calculation function calc in CSS in website layout

calc is a function in CSS that is used to calcula...

WeChat applet implements a simple handwritten signature component

Table of contents background: need: Effect 1. Ide...

Detailed explanation of the usage and differences of MySQL views and indexes

MySQL Views Simply put, a MySQL view is a shortcu...

Complete Tutorial on Deploying Java Web Project on Linux Server

Most of this article refers to other tutorials on...

MySQL high availability solution MMM (MySQL multi-master replication manager)

1. Introduction to MMM: MMM stands for Multi-Mast...

Nginx builds rtmp live server implementation code

1. Create a new rtmp directory in the nginx sourc...

Use Docker Compose to quickly deploy ELK (tested and effective)

Table of contents 1. Overview 1.1 Definition 1.2 ...

Analysis of Linux kernel scheduler source code initialization

Table of contents 1. Introduction 2. Basic Concep...

Use Shell scripts to batch start and stop Docker services

Table of contents Start Docker Stop Docker Python...

Detailed installation tutorial of Docker under CentOS

Docker is divided into CE and EE. The CE version ...

Detailed explanation of Deepin using docker to install mysql database

Query the MySQL source first docker search mysql ...