MySQL - How to check if START TRANSACTION is active

痞子三分冷 提交于 2019-12-05 05:21:31

You can create a function that will exploit an error which can only occur within a transaction:

DELIMITER //
CREATE FUNCTION `is_in_transaction`() RETURNS int(11)
BEGIN
    DECLARE oldIsolation TEXT DEFAULT @@TX_ISOLATION;
    DECLARE EXIT HANDLER FOR 1568 BEGIN
        -- error 1568 will only be thrown within a transaction
        RETURN 1;
    END;
    -- will throw an error if we are within a transaction
    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
    -- no error was thrown - we are not within a transaction
    SET TX_ISOLATION = oldIsolation;
    RETURN 0;
END//
DELIMITER ;

Test the function:

set @within_transaction := null;
set @out_of_transaction := null;

begin;
    set @within_transaction := is_in_transaction();
commit;

set @out_of_transaction := is_in_transaction();

select @within_transaction, @out_of_transaction;

Result:

@within_transaction | @out_of_transaction
--------------------|--------------------
                  1 |                   0

With MariaDB you can use @@in_transaction

Tomaso Albinoni

From https://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html:

Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.

I suspect that the problem can be solved by using SET autocommit=0; instead of START TRANSACTION;. If autocommit is already 0, it will have no effect.

See also Does setting autocommit=0 within a transaction do anything?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!