DB2 Version 10.1 for Linux, UNIX, and Windows

WHENEVER <condition> DO <action> statements

C and C++ embedded SQL applications can use the WHENEVER condition DO action statement to take a specified action when an exception condition occurs.

The WHENEVER statement specifies the action to be taken when a specified exception condition occurs. The following syntax diagram shows the WHENEVER condition DO action statement syntax:
Read syntax diagramSkip visual syntax diagram
>>-EXEC SQL WHENEVER--+-SQLERROR---+--DO--+-BREAK-----------+--><
                      +-SQLWARNING-+      +-CONTINUE--------+   
                      '-NOT FOUND--'      '-function-name()-'   

The WHENEVER statement handles the following conditions:
SQLERROR
Identifies any condition where SQLCODE < 0.
SQLWARNING
Identifies any condition where SQLWARN(0) = W or SQLCODE > 0 but is not equal to 100.
NOT FOUND
Identifies any condition where SQLCODE = 100.
In each WHENEVER statement conditions, the following DO action can take place:
DO
Causes additional action in the form of a function call, break statement, or continue statement to take place.
BREAK
Specifies the C break statement. The C break statement exits the do, for, switch, or while statement block.
CONTINUE
Specifies the C continue statement. The C continue statement passes control to the next iteration of the do, for, switch, or while statement block.
function-name()
Specifies the C function that is to be called. The function must have a void return value and cannot accept any arguments. The function name must end with a set of parentheses "(" and ")". The name of the function is limited to 255 bytes.

The function name resolution takes place during the compilation of a C and C++ embedded SQL application. The DB2® precompiler does not resolve the function name.

The following C example uses the WHENEVER condition DO action statement:
void sqlError(void)
{
    switch (sqlca.sqlcode)
    {
        case -999: // some SQLCODE code
            printf ("Error related to -999 occurred\n");
            break;
        case -888: // some SQLCODE code
            printf ("Error related to -888 occurred\n");
            break;
        default:
            printf ("Unknown error occurred\n");
            break;
    }
    exit(-3);
}

int func1() // DO function-name

    ...
    EXEC SQL WHENEVER NOT FOUND DO sqlError();
    ...
    while(sqlca.sqlcode == SQL_RC_OK)
    {
        // some application logic
    }
    ...
}

int func2() // DO BREAK
{
    ...
    EXEC SQL WHENEVER SQLWARNING DO BREAK;
    ...
    while(...)
    {
        // some application logic
    }
    // Causes the next sequential instruction of the source program 
    // to be executed. Basically voids effect of previous WHENEVER.
    EXEC SQL WHENEVER SQLWARNING CONTINUE;
    ...
}

int func3() // DO CONTINUE
{
    ...
    EXEC SQL WHENEVER NOT FOUND DO CONTINUE;
    ...
    while(...)
    {
        // some application logic
    }
    ...
}