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

Implementation of element shuttle frame performance optimization

Table of contents background Solution New Questio...

Sample code for easily implementing page layout using flex layout

Without further ado, let's get straight to th...

Vue+SSM realizes the preview effect of picture upload

The current requirement is: there is a file uploa...

How to reference external CSS files and iconfont in WeChat applet wxss

cause The way to import external files into a min...

Vue conditional rendering v-if and v-show

Table of contents 1. v-if 2. Use v-if on <temp...

Two methods to disable form controls in HTML: readonly and disabled

In the process of making web pages, we often use f...

Summary of uncommon js operation operators

Table of contents 2. Comma operator 3. JavaScript...

Tutorial diagram of installing mysql8.0.18 under linux (Centos7)

1 Get the installation resource package mysql-8.0...

Use label tag to select the radio button by clicking the text

The <label> tag defines a label (tag) for an...

A brief discussion on common operations of MySQL in cmd and python

Environment configuration 1: Install MySQL and ad...

Incredible CSS navigation bar underline following effect

The first cutter in China github.com/chokcoco Fir...

MySQL complete collapse query regular matching detailed explanation

Overview In the previous chapter, we learned abou...