0

我想用事务编写存储过程。假设 proc1 正在事务块中调用另一个 proc(proc2)。proc2 还包含回滚/提交。如果回滚发生在 proc1 中,那么回滚是否也发生在 proc2 中?我尝试了以下示例,但没有成功。这是以下代码

test1.sql

DELIMITER $$
DROP PROCEDURE IF EXISTS `debug`.`test1`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `test1`()

begin

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET @errorOccurred :=2;

set @errorOccurred :=1;

START TRANSACTION;

insert into Table1 values("table1_1");

insert into debug values("insertStatement_1");

insert into Table1 values(1,2);

call test2();

if (@errorOccurred=2) then
ROLLBACK;
else
COMMIT;
end if;

end$$

DELIMITER ;

==========================================

test2.sql

DELIMITER $$
DROP PROCEDURE IF EXISTS `debug`.`test2`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test2`()
begin
START TRANSACTION;

create table Table2 (msg varchar(255)) ENGINE=InnoDB;

insert into Table2 values("table2_value");

COMMIT;

end$$

DELIMITER ;

你能帮我解决我的问题吗?

先感谢您。

4

1 回答 1

0

Here is something interesting: Once you run START TRANSACTION, any open transaction will implicitly commit. I wrote about this in the DBA StackExchange: March 15, 2013 : MySQL backup InnoDB.

SUGGESTION : I would remove START TRANSACTION; and COMMIT; from test2.sql.

Give it a Try !!!

UPDATE 2013-10-28 09:16 EDT

If you can calling a transaction within a transaction, you cannot do START TRANSACTION a second time. If you want to rollback from test2 and keep test1 in a transaction from the point of calling test2, you should look into using SAVEPOINT and ROLLBACK TO SAVEPOINT in the MySQL Docuementation.

Basically, you would create the SAVEPOINT in test1 just before calling test2. You would rollback to the SAVEPOINT if test2 fails in anyway.

于 2013-10-28T12:56:50.737 回答