Iterative control
With the LOOP, WHILE, FOR, and EXIT statements, you can control the flow of execution of your NZPLSQL program iteratively.
LOOP statement
[<<label>>]
LOOP
statements
END LOOP;
The optional label can be used by EXIT statements of nested loops to specify which level of nesting is terminated.
EXIT statement
EXIT [ label ] [ WHEN expression ];
If you do not specify a label, the innermost loop is terminated and the statement that follows END LOOP runs next. If you specify a label, it must be the label of the current or an upper level of nested loop or blocks. Then the named loop or block is terminated and control continues with the statement after the corresponding END of the loop or blocks.
LOOP
-- some computations
IF count > 0 THEN
EXIT; -- exit loop
END IF;
END LOOP;
LOOP
-- some computations
EXIT WHEN count > 0;
END LOOP;
BEGIN
-- some computations
IF stocks > 100000 THEN
EXIT;
END IF;
END;
WHILE statement
[<<label>>]
WHILE expression LOOP
statements
END LOOP;
WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
-- some computations here
END LOOP;
WHILE NOT boolean_expression LOOP
-- some computations here
END LOOP;
FOR statement
[<<label>>]
FOR name IN [ REVERSE ] expression .. expression LOOP
statements
END LOOP;
The variable name is automatically created as type integer and exists only inside the loop. The two expressions for the lower and upper bound of the range are evaluated only when entering the loop. The iteration step is always 1.
FOR i IN 1 .. 10 LOOP
-- some expressions here
RAISE NOTICE 'i is %',i;
END LOOP;
FOR i IN REVERSE 10 .. 1 LOOP
-- some expressions here
END LOOP;