Handlers in an SQL procedure
If an error occurs when an SQL procedure executes, the procedure ends unless you include statements to tell the procedure to perform some other action. These statements are called handlers.
Handlers are similar to WHENEVER statements in external SQL application programs. Handlers tell the SQL procedure what to do when an error or warning occurs, or when no more rows are returned from a query. In addition, you can declare handlers for specific SQLSTATEs. You can refer to an SQLSTATE by its number in a handler, or you can declare a name for the SQLSTATE and then use that name in the handler.
DECLARE handler-type HANDLER FOR condition SQL-procedure-statement;
In general, the way that a handler works is that when an error occurs that matches condition, the SQL-procedure-statement executes. When the SQL-procedure-statement completes, Db2 performs the action that is indicated by handler-type.
Types of handlers
- CONTINUE
- Specifies that after SQL-procedure-statement completes, execution continues with the statement after the statement that caused the error.
- EXIT
- Specifies that after SQL-procedure-statement completes, execution continues at the end of the compound statement that contains the handler.
DECLARE CONTINUE HANDLER FOR NOT FOUND SET at_end=1;
DECLARE NO_TABLE CONDITION FOR '42704';
⋮
DECLARE EXIT HANDLER FOR NO_TABLE
SET OUT_BUFFER='Table does not exist';