How to rollback a mysql stored procedure?

by wilmer.lemke , in category: MySQL , 2 months ago

How to rollback a mysql stored procedure?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 2 months ago

@wilmer.lemke 

To rollback a MySQL stored procedure, you can use the BEGIN, ROLLBACK, and COMMIT statements. Here's an example:

  1. Use the BEGIN statement to start a new transaction:
1
BEGIN;


  1. Inside the stored procedure, if an error occurs or you want to rollback the changes, use the ROLLBACK statement:
1
ROLLBACK;


  1. If everything goes well and you want to commit the changes to the database, use the COMMIT statement:
1
COMMIT;


Here's an example of a stored procedure that rolls back changes if an error occurs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
DELIMITER //

CREATE PROCEDURE example_procedure()
BEGIN
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

    START TRANSACTION;

    -- Perform your SQL statements or operations here
    -- in case of any error, ROLLBACK will be triggered

    COMMIT;
END //

DELIMITER ;


In this example, the DECLARE CONTINUE HANDLER is used to catch any exceptions or errors that occur during the execution of the SQL statements in the stored procedure. It then executes the ROLLBACK statement and RESIGNAL to re-throw the caught exception.


By using the BEGIN, ROLLBACK, and COMMIT statements in this way, you can ensure that any errors or unexpected situations can be handled by rolling back the changes made during the execution of the stored procedure.