MySQL Rollback in transaction

风流意气都作罢 提交于 2020-01-05 07:29:29

问题


I have defined a function like this -

...
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK; 
DECLARE EXIT HANDLER FOR SQLWARNING ROLLBACK SET error_key = 1 AND error_message = 'Failed -- Rollback.';
BEGIN
     SELECT 'Insert Failed.';
     CALL log_error(error_key,  error_message);
 END ; 

START TRANSACTION;

     DECLARE EXIT HANDLER FOR 1062 SET error_key = 02 AND error_message = 'Insert Failed';
     BEGIN
        SELECT 'Attempt to create a duplicate entry in the follow table.';
        CALL log_error(error_key,  error_message);
      END; 
      INSERT INTO `user_table` (...) VALUES (...);

      /* Call the trigger to update the profile table */
      CALL updateAnotherTable(@result1);
      CALL updateAnotherTable1(@result2);

IF @retsult1=0 OR @retsult2=0 THEN
  ROLLBACK;
ELSE
  COMMIT;
END IF; 
...

I am getting the following error --

  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK; DECLARE EXIT HANDLER FOR SQL

EDIT

I updated my proc I am still getting the error ..

 DECLARE exit handler for sqlexception sqlwarning 
 BEGIN        
       SET error_key = 901;
       SET error_message = 'Insert Failed.';
       CALL log_error(error_key,  error_message);
       ROLLBACK;
 END; 

回答1:


When using compound statements in a handler you need to embed them in a BEGIN ... END block:

DECLARE EXIT HANDLER FOR 1062
BEGIN
    SET error_key = 02;
    SET error_message = 'Insert Failed';
END

Refer to the DECLARE HANDLER section of the MySQL manual for more information.



来源:https://stackoverflow.com/questions/13538436/mysql-rollback-in-transaction

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