7.6.7. LEAVE

Used for

Terminating a loop

Available in

PSQL

Syntax

  1. [label:]
  2. <loop_stmt>
  3. BEGIN
  4. ...
  5. LEAVE [label];
  6. ...
  7. END
  8. <loop_stmt> ::=
  9. FOR <select_stmt> INTO <var_list> DO
  10. | FOR EXECUTE STATEMENT ... INTO <var_list> DO
  11. | WHILE (<condition>)} DO
Table 86. LEAVE Statement Parameters
ArgumentDescription

label

Label

select_stmt

SELECT statement

condition

A logical condition returning TRUE, FALSE or UNKNOWN

A LEAVE statement immediately terminates the inner loop of a WHILE or FOR looping statement. The label parameter is optional.

LEAVE can cause an exit from outer loops as well. Code continues to be executed from the first statement after the termination of the outer loop block.

Examples

  1. Leaving a loop if an error occurs on an insert into the NUMBERS table. The code continues to be executed from the line C = 0.

    1. ...
    2. WHILE (B < 10) DO
    3. BEGIN
    4. INSERT INTO NUMBERS(B)
    5. VALUES (:B);
    6. B = B + 1;
    7. WHEN ANY DO
    8. BEGIN
    9. EXECUTE PROCEDURE LOG_ERROR (
    10. CURRENT_TIMESTAMP,
    11. 'ERROR IN B LOOP');
    12. LEAVE;
    13. END
    14. END
    15. C = 0;
    16. ...
  2. An example using labels in the LEAVE statement. LEAVE LOOPA terminates the outer loop and LEAVE LOOPB terminates the inner loop. Note that the plain LEAVE statement would be enough to terminate the inner loop.

    1. ...
    2. STMT1 = 'SELECT NAME FROM FARMS';
    3. LOOPA:
    4. FOR EXECUTE STATEMENT :STMT1
    5. INTO :FARM DO
    6. BEGIN
    7. STMT2 = 'SELECT NAME ' || 'FROM ANIMALS WHERE FARM = ''';
    8. LOOPB:
    9. FOR EXECUTE STATEMENT :STMT2 || :FARM || ''''
    10. INTO :ANIMAL DO
    11. BEGIN
    12. IF (ANIMAL = 'FLUFFY') THEN
    13. LEAVE LOOPB;
    14. ELSE IF (ANIMAL = FARM) THEN
    15. LEAVE LOOPA;
    16. ELSE
    17. SUSPEND;
    18. END
    19. END
    20. ...

See also

EXIT