MySQL : transaction within a stored procedure

后端 未结 4 791
离开以前
离开以前 2020-11-27 13:13

The basic structure of my stored procedure is,

BEGIN

    .. Declare statements ..

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
              


        
4条回答
  •  北海茫月
    2020-11-27 13:57

    This is just an explanation not addressed in other answers

    At least in recent versions of Mysql, your first query is not committed.

    If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.

    What's going on?

    When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.

    So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE, UPDATE, INSERT or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).

    That's why the solution involves declaring handlers to immediately ROLLBACK when an error happens.

    Extra

    Inside the handler you can also re-raise the error using RESIGNAL, otherwise the stored procedure executes "Successfully"

    BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION 
            BEGIN
                ROLLBACK;
                RESIGNAL;
            END;
    
        START TRANSACTION;
            #.. Query 1 ..
            #.. Query 2 ..
            #.. Query 3 ..
        COMMIT;
    END
    

提交回复
热议问题