Conditions and Handlers

Certain conditions may require specific handling. These conditions can relate to errors, as well as general flow control inside a routine.

DECLARE Conditions

DECLARE condition_name CONDITION FOR condition_value
condition_value:
    SQLSTATE [VALUE] sqlstate_value
  | mysql_error_code

This statement specifies conditions that will need specific handling. It associates a name with a specified error condition. The name can subsequently be used in a DECLARE HANDLER statement. See DECLARE Handlers.

In addition to SQLSTATE values, MySQL error codes are also supported.

DECLARE Handlers

DECLARE handler_type HANDLER FOR condition_value[,...] sp_statement
handler_type:
    CONTINUE
  | EXIT
  | UNDO
condition_value:
    SQLSTATE [VALUE] sqlstate_value
  | condition_name
  | SQLWARNING
  | NOT FOUND
  | SQLEXCEPTION
  | mysql_error_code

This statement specifies handlers that each may deal with one or more conditions. If one of these conditions occurs, the specified statement is executed.

For a CONTINUE handler, execution of the current routine continues after execution of the handler statement. For an EXIT handler, execution of the current routine is terminated. The UNDO handler_type is not yet supported. UNDO currently behaves like CONTINUE.

  • SQLWARNING is shorthand for all SQLSTATE codes that begin with 01.

  • NOT FOUND is shorthand for all SQLSTATE codes that begin with 02.

  • EXCEPTION is shorthand for all SQLSTATE codes not caught by SQLWARNING or NOT FOUND.

In addition to SQLSTATE values, MySQL error codes are also supported.

For example:

mysql> CREATE TABLE test.t (s1 int,primary key (s1));
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter |
mysql> CREATE PROCEDURE handlerdemo ()
    -> BEGIN
    ->   DECLARE CONTINUE HANDLER FOR '23000' SET @x2 = 1;
    ->   set @x = 1;
    ->   INSERT INTO test.t VALUES (1);
    ->   set @x = 2;
    ->   INSERT INTO test.t VALUES (1);
    ->   SET @x = 3;
    -> END;
    -> |
Query OK, 0 rows affected (0.00 sec)
mysql> CALL handlerdemo()|
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @x|
    +------+
    | @x   |
    +------+
    | 3    |
    +------+
    1 row in set (0.00 sec)

Notice that @x is 3, which shows that MySQL executed to the end of the procedure. If the line DECLARE CONTINUE HANDLER FOR '23000' SET @x2 = 1; had not been present, MySQL would have taken the default (EXIT) path after the second INSERT failed due to the PRIMARY KEY constraint, and SELECT @x would have returned 2.