Skip to content

Instantly share code, notes, and snippets.

@anilahir
Created December 20, 2019 08:14
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save anilahir/d54f89d8f4edbc8b7e99ef2557371339 to your computer and use it in GitHub Desktop.
Save anilahir/d54f89d8f4edbc8b7e99ef2557371339 to your computer and use it in GitHub Desktop.
MySQL transaction within stored procedure example

Create stored procedure :

DROP PROCEDURE IF EXISTS sp_delete_users_till_date;

DELIMITER //

CREATE PROCEDURE sp_delete_users_till_date(location_id INT, till_date DATE)

BEGIN
    
    DECLARE track_no INT DEFAULT 0;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION, NOT FOUND, SQLWARNING
    
    BEGIN
    
        ROLLBACK;
        GET DIAGNOSTICS CONDITION 1 @`errno` = MYSQL_ERRNO, @`sqlstate` = RETURNED_SQLSTATE, @`text` = MESSAGE_TEXT;
        SET @full_error = CONCAT('ERROR ', @`errno`, ' (', @`sqlstate`, '): ', @`text`);
        SELECT track_no, @full_error;
    
    END;

    START TRANSACTION;

        SET FOREIGN_KEY_CHECKS = 0;
        SET track_no = 1;

        DELETE FROM users WHERE users.location_id = location_id AND DATE(users.created_at) <= till_date;
        SET track_no = 2;

        SET FOREIGN_KEY_CHECKS = 1;
        SET track_no = 3;

        SELECT track_no, 'Congrates!, successfully executed.';

    COMMIT;

END; //

DELIMITER ;

Call stored procedure :

call sp_delete_users_till_date(2, '2019-12-17');
@jdisla
Copy link

jdisla commented Jul 17, 2021

Simple, clear. Thank you.

@douglas2569
Copy link

Thank you, it helped a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment