Labeled LOOP Statements

About this task

All forms of the LOOP statement, including the FOR LOOP, WHILE LOOP, and simple LOOP statements can have statement labels. You can create a labeled LOOP statement in the following steps:
  1. Write a valid LOOP, FOR LOOP, or WHILE LOOP statement.
  2. Create a statement label by enclosing an SQL identifier (that is not already the name of a label in the same SPL routine) between angle brackets (<<loop_label>>) immediately before the first line of the LOOP, FOR LOOP, or WHILE LOOP statement.
  3. Enter the same SQL identifier, but without angle bracket delimiters, immediately after the END LOOP keywords that terminate the statement, which is now a labeled loop statement.
One advantage of labeled LOOP statements is that they can be referenced in EXIT statements. When the EXIT label statement executes, program control passes from the EXIT statement to the statement that follows the specified loop label.
In the following example, a labeled WHILE LOOP loop, whose loop label identifier is endo, is part of the statement block of a labeled LOOP statement whose loop label identifier is voort. If the conditional EXIT statement EXIT endo WHEN x = 7: detects that its condition is true, program control passes to the LET x = x + 1 statement that follows the END LOOP endostatement. If the conditional EXIT statement EXIT voort WHEN x > 9: detects that its condition is true, program control passes to the LET x = x + 1 statement that follows the END LOOP voortstatement, and the value of x is not incremented by the LET statement,
 <<voort>>
 LOOP
    LET x = x+1;
    <<endo>>
    WHILE ( i < 10 ) LOOP
       LET x = x+1; 
          EXIT endo WHEN x = 7;
          EXIT voort WHEN x > 9;
          END LOOP endo;
       LET x = x+1;
    END LOOP voort;
uses FOR statement syntax to specify a variable and a range of values that the variable can take. The loop iterates until the specified limit to these values is reached, or until control is transferred outside the loop, as by the unconditional EXIT statement in the following example:
FOR i IN (1 TO 5) LOOP
   IF i = 5 THEN EXIT;
   ELSE
   CONTINUE;
END LOOP;
In the FOR LOOP statement, the FOR keyword can follow the EXIT or CONTINUE keyword, but the FOR keyword is not required, as it is in an ordinary FOR statement.
The following example replaces the IF statement with a functionally equivalent conditional EXIT statement:
FOR i IN (1 TO 5) LOOP
   EXIT WHEN i = 5;
   END LOOP;

Related Statements

<< Label >> statement, FOR, WHILE