Using the WHENEVER Statement

Writing code to check the value of the SQLCODE variable after each Embedded SQL statement becomes burdensome, especially when writing large programs. Another method for checking the status of the SQLCA data structure fields is the WHENEVER statement. The WHENEVER statement is not an executable statement—it is a directive to the Embedded SQL precompiler to automatically generate code to handle errors after each executable Embedded SQL statement, and it specifies the next action to be taken. The WHENEVER statement allows one of three actions (CONTINUE, GOTO, or CALL) to be registered for each of the three possible SQLCODE conditions (SQLWARNING, SQLERROR, or NOT FOUND).

A WHENEVER statement in the program code supersedes the conditions of all previous WHENEVER statements.

This is an example of a WHENEVER statement:


EXEC SQL WHENEVER sqlerror GOTO errormessage1;

EXEC SQL DELETE FROM homesales
    WHERE equity < 10000;

EXEC SQL DELETE FROM customerlist
    WHERE salary < 40000;

EXEC SQL WHENEVER sqlerror CONTINUE;

EXEC SQL UPDATE homesales
    SET equity = equity - loanvalue;

EXEC SQL WHENEVER sqlerror GOTO errormessage2;

EXEC SQL INSERT INTO homesales (seller_name, sale_price)
    real_estate('Jane Doe', 180000.00);
        .
        .
        .
errormessage1:
    printf("SQL DELETE error: %ld\n, sqlcode);
exit();

errormessage2:
    printf("SQL INSERT error: %ld\n, sqlcode);
exit();

For more information about the WHENEVER statement, see WHENEVER in Chapter 3, "Embedded SQL Statements."