2015-12-05 52 views
1

如果發生錯誤(使用SIGNAL),我嘗試在過程中回滾事務。 我有兩個問題:MySQL - 在嵌入式過程的情況下回滾事務

  1. 欲停止執行聲明1,如果發生錯誤,
  2. 欲停止執行Stateemtn 2,如果在步驟(1)

過程中發生錯誤1:

CREATE DEFINER=`edgar`@`%` PROCEDURE some_sp (IN param INT) 
BEGIN 

    DECLARE `_rollback` BOOL DEFAULT 0; 

    DECLARE new_legal_entity_id INT; 

    DECLARE specialty CONDITION FOR SQLSTATE '45000'; 
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET _rollback = 1; 

    START TRANSACTION; 

    CASE -- Some condition 
     BEGIN 
      SIGNAL specialty 
      SET MESSAGE_TEXT = 'Error message'; 
     END; 
    ELSE BEGIN END; 
    END CASE; 

    INSERT INTO .... -- Statement 1 

    COMMIT; 
    END 

步驟2:

CREATE DEFINER=`edgar`@`%` PROCEDURE some_sp_1 (IN param INT) 
BEGIN 

    DECLARE `_rollback` BOOL DEFAULT 0; 

    DECLARE new_legal_entity_id INT; 

    DECLARE specialty CONDITION FOR SQLSTATE '45000'; 
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET _rollback = 1; 

    START TRANSACTION; 

    CALL some_sp(some_param); 
    INSERT INTO .... -- Statement 2 

    COMMIT; 
    END 

我已閱讀thisthis,但仍無法得到代碼工作

回答

0

嘗試:

DELIMITER $$ 

DROP TABLE IF EXISTS `t`$$ 
DROP PROCEDURE IF EXISTS `some_sp_1`$$ 
DROP PROCEDURE IF EXISTS `some_sp`$$ 

CREATE TABLE `t`(
    `id` INT UNSIGNED 
)$$ 

CREATE PROCEDURE `some_sp`(IN `param` INT) 
BEGIN 
    DECLARE `specialty` CONDITION FOR SQLSTATE '45000'; 
    IF `param` THEN 
    SIGNAL `specialty`; 
    END IF; 
    INSERT INTO `t` SELECT 1; 
END$$ 

CREATE PROCEDURE `some_sp_1`(IN `param` INT) 
BEGIN 
    DECLARE `_rollback` BOOL DEFAULT FALSE; 
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `_rollback` := TRUE; 
    START TRANSACTION; 
    CALL `some_sp`(`param`); 
    IF `_rollback` THEN 
    ROLLBACK; 
    ELSE 
    -- INSERT INTO `t1` SELECT 2; -- fail, t1 not exist 
    INSERT INTO `t` SELECT 2; 
    IF `_rollback` THEN 
     ROLLBACK; 
    ELSE 
     COMMIT; 
    END IF; 
    END IF; 
END$$ 

DELIMITER ; 

CALL `some_sp_1`(0); 
-- CALL `some_sp_1`(1); 

SELECT `id` FROM `t`; 
+0

不,@wchiquito,這似乎並沒有爲我工作。查看我的回答 –

+0

@ EdgarNavasardyan:[SQL Fiddle](http://sqlfiddle.com/#!9/348340/1),測試正在運行。 – wchiquito