transacción mysql-revertir cualquier excepción


¿Es posible revertir automáticamente si se produce algún error en una lista de comandos mysql?

Por ejemplo algo parecido a:

begin transaction;

insert into myTable values1 ...
insert into myTable values2 ...;  -- will throw an error

commit;

Ahora, al ejecutar quiero que toda la transacción falle, y por lo tanto debería NO ver values1 en MyTable. pero desafortunadamente la tabla está siendo pupulada con valores1 a pesar de que la transacción tiene errores.

¿Alguna idea de cómo hago para retroceder? (de nuevo, en cualquier error)?

EDITAR-cambiado de DDL a estándar SQL

Author: Urbanleg, 2013-11-11

2 answers

Puede usar 13.6.7.2. DECLARAR ... Sintaxis del MANEJADOR de la siguiente manera:

DELIMITER $$

CREATE PROCEDURE `sp_fail`()
BEGIN
    DECLARE `_rollback` BOOL DEFAULT 0;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `_rollback` = 1;
    START TRANSACTION;
    INSERT INTO `tablea` (`date`) VALUES (NOW());
    INSERT INTO `tableb` (`date`) VALUES (NOW());
    INSERT INTO `tablec` (`date`) VALUES (NOW()); -- FAIL
    IF `_rollback` THEN
        ROLLBACK;
    ELSE
        COMMIT;
    END IF;
END$$

DELIMITER ;

Para un ejemplo completo, marque el siguiente SQL Fiddle.

 39
Author: wchiquito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-11 13:59:51

Puede usar EXIT HANDLER si, por ejemplo, necesita SEÑALAR una EXCEPCIÓN SQL específica en su código. Por ejemplo:

DELIMITER $$

CREATE PROCEDURE `sp_fail`()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;  -- rollback any changes made in the transaction
        RESIGNAL;  -- raise again the sql exception to the caller
    END;

    START TRANSACTION;
    insert into myTable values1 ...
    IF fail_condition_meet THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Custom error detected.', MYSQL_ERRNO = 2000;
    END IF;
    insert into myTable values2 ...  -- this will not be executed
    COMMIT; -- this will not be executed
END$$

DELIMITER ;
 12
Author: KGs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-25 20:32:22