Example of MySQL error handling

  • 2020-05-09 19:26:48
  • OfStack

from http://www.devshed.com/c/a/MySQL/Error-Handling-Examples/
Error Handler Examples
Here are some examples of handler declarations:
If any error condition arises (other than a NOT FOUND ), continue execution after setting l_error=1 :
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET l_error=1;
If any error condition arises (other than a NOT FOUND ), exit the current block or stored program after issuing a ROLLBACK statement and issuing an error message:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'Error occurred ';
END;
If MySQL error 1062 (duplicate key value) is encountered, continue execution after executing the SELECT statement (which generates a message for the calling program):
DECLARE CONTINUE HANDER FOR 106 2
SELECT 'Duplicate key in index';
If SQLSTATE 23000 (duplicate key value) is encountered, continue execution after executing the SELECT statement (which generates a message for the calling program):
DECLARE CONTINUE HANDER FOR SQLSTATE '23000'
SELECT 'Duplicate key in index';
When a cursor fetch or SQL retrieves no values, continue execution after setting l_done=1 :
DECLARE CONTINUE HANDLER FOR NOT
FOUND
SET l_done=1;
Same as the previous example, except specified using a SQLSTATE variable rather than a named condition:
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000 '
SET l_done=1;
Same as the previous two examples, except specified using a MySQL error code variable rather than a named condition or SQLSTATE variable:
DECLARE CONTINUE HANDLER FOR 1329
SET l_done=1;

Error handling example
There are several forms of error handling declaration:
§ if there is any error (not NOT FOUND), set l_error to 1 and continue:
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET l_error=1;
§ if any error occurs (not NOT FOUND), execute ROLLBACK and exit the current block or stored procedure after generating an error message.
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'Error occurred, terminating';
END;
§ if an MySQL 1062 error (duplicate key) occurs, execute the SELECT statement (send a message to the caller) and continue execution
DECLARE CONTINUE HANDER FOR 106 2
SELECT 'Duplicate key in index';
§ if the SQLSTATE 2300 error (duplicate key) occurs, execute the SELECT statement (send 1 message to the caller) and continue
DECLARE CONTINUE HANDER FOR SQLSTATE '23000'
SELECT 'Duplicate key in index';
§ when the cursor or SQL select statement does not return a value, l_done=1 continues execution
DECLARE CONTINUE HANDLER FOR NOT
FOUND
SET l_done=1;
§ this example is similar to the previous example except that the variable SQLSTATE is used instead of the naming condition
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000 '
SET l_done=1;
§ this example is similar to the previous two examples except that the error code variable of MySQL is used instead of the naming condition or SQLSTATE variable
DECLARE CONTINUE HANDLER FOR 1329
SET l_done=1;

Related articles: