EXIT From FOR, LOOP, and WHILE Loops

If the EXIT statement is issued outside the FOREACH statement, it returns an error unless it is issued from the FOR, FOR LOOP, LOOP, WHILE LOOP, or WHILE statement as its innermost enclosing statement. In FOR or WHILE statements that do not include the LOOP keyword, the corresponding FOR or WHILE keyword is required after the EXIT keyword. Execution resumes at the first executable statement that follows the innermost loop from which the EXIT statement was issued.

The EXIT statement requires no other keyword when it is issued from the FOR LOOP, LOOP, or WHILE LOOP statement, with or without a loop label, but if you include the FOR, LOOP, or WHILE keyword after the EXIT keyword, that keyword must correspond to the type of loop from which the EXIT statement is issued.

If the EXIT keyword is followed by the identifier of a loop label, and no condition is specified, execution resumes at the first executable statement that follows the FOR, FOR LOOP, LOOP, WHILE LOOP, or WHILE statement whose label is specified. This enables the EXIT statement to exit from nested loops, if an outer loop is labeled.

If a WHEN condition follows the EXIT or EXIT label specification, EXIT has no effect unless the condition is true. If the condition is true, execution resumes after the labeled loop, or after the innermost loop, if no label is specified.

If the database server cannot find the specified loop or loop label, the EXIT statement fails. If EXIT is issued outside any FOR, FOREACH, LOOP, or WHILE statement, it generates errors.

The following example uses an EXIT FOR statement. In the FOR loop, when j becomes 6, the IF condition i = 5 in the WHILE loop is true. The FOR loop stops executing, and the SPL procedure continues at the next statement outside the FOR loop (in this case, the END PROCEDURE statement). In this example, the procedure ends when j equals 6:
CREATE PROCEDURE ex_cont_ex()
   DEFINE i,s,j, INT;
   FOR j = 1 TO 20
      IF j > 10 THEN 
         CONTINUE FOR;
      END IF
      LET i,s = j,0;
      WHILE i > 0
         LET i = i -1;
         IF i = 5 THEN
            EXIT FOR;
         END IF
      END WHILE
   END FOR
END PROCEDURE;
The following program fragment shows two conditional EXIT statements in a labeled WHILE LOOP statement that is nested within another labeled LOOP statement:
        <<outer>>
        LOOP
        LET x = x+1;
           <<inner>>
           WHILE ( i >10 ) LOOP
              LET x = x+1; 
              EXIT inner WHEN x = 2;
              EXIT outer WHEN x > 3;
              END LOOP inner;
        LET x = x+1;
        END LOOP outer;

When the x=2 condition is true, the EXIT inner statement transfers control to the LET statement that follows the loop whose label is inner. When the x>3 condition is true, the EXIT outer statement terminates execution of the outer loop.

Related Statements

<< Label >> statement, FOR, FOREACH, LOOP, WHILE