在mysql中使用SavePoint的问题

时间:2010-12-29 05:08:15

标签: mysql

我正在尝试使用MySQL中的保存点,似乎出现了问题。

MySQL transaction conundrum

我收到错误,如下所示:

  

错误1305(42000):SAVEPOINT   sp_prc_work不存在

我有或没有保存点的程序完全相同。我所期望的是值'4','pqr'不应该出现在表中 整个交易将被回滚。但是,插入了3和4个ID。我理解为什么条目'3','pqr'在那里,但我想id'4'不应该在那里。

drop table if exists test.savepoint_test;
drop procedure if exists second_fail;
drop procedure if exists prc_work;

CREATE TABLE test.savepoint_test (
id int not null default '0',
name varchar(100),
primary key (id)
)engine=InnoDB;

insert into test.savepoint_test values ('1', 'abc');
insert into test.savepoint_test values ('2', 'xyz');

select * from test.savepoint_test;

delimiter $$

CREATE PROCEDURE second_fail()
BEGIN
        INSERT  into test.savepoint_test values ('3', 'pqr');
        INSERT  into test.savepoint_test values ('2', 'mnp');
END;

$$

CREATE PROCEDURE prc_work()
BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_prc_work;
        SAVEPOINT sp_prc_work;
        INSERT  into test.savepoint_test values ('4', 'pqr');
        INSERT  into test.savepoint_test values ('2', 'mnp');
END;

$$

delimiter ;


call second_fail();

select * from test.savepoint_test;

call prc_work();

select * from test.savepoint_test;

1 个答案:

答案 0 :(得分:4)

更改此行

    DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_prc_work;
    SAVEPOINT sp_prc_work;

    SAVEPOINT sp_prc_work;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_prc_work;

这应该解决问题,你告诉mysql回滚到一个不存在的保存点

http://dev.mysql.com/doc/refman/5.0/en/savepoint.html

DC

我已将您的示例重新设计为我认为您真正想要的内容

请注意开始交易

drop table if exists test.savepoint_test;
drop procedure if exists second_fail;
drop procedure if exists prc_work;

CREATE TABLE test.savepoint_test (
id int not null default '0',
name varchar(100),
primary key (id)
)engine=InnoDB;

delimiter $$

CREATE PROCEDURE second_fail()
BEGIN
        INSERT  into test.savepoint_test values ('3', 'pqr');
        INSERT  into test.savepoint_test values ('4', 'mnp');
END;

$$

CREATE PROCEDURE prc_work()
BEGIN
        SAVEPOINT sp_prc_work;
        BEGIN
                DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_prc_work;
                INSERT  into test.savepoint_test values ('5', 'cat');
                INSERT  into test.savepoint_test values ('2', 'dog');
        END;
        RELEASE SAVEPOINT sp_prc_work;
END;

$$

delimiter ;

START TRANSACTION;

select 'test point 1' as ``;

insert into test.savepoint_test values ('1', 'abc');      
insert into test.savepoint_test values ('2', 'xyz');

select * from test.savepoint_test;

select 'test point 2' as ``;

call second_fail();    

select * from test.savepoint_test;

select 'test point 3'  as ``;

call prc_work();

select * from test.savepoint_test;

select 'test point 4' as ``;

COMMIT;  

DC