FOR
A FOR loop allows repeating a sequence of steps a defined number of times. The FOR statement is only valid within a scripting block.
Syntax | FOR number of iterations
Executes a FOR loop for a specific number of iterations:
sql
FOR counter_var IN [REVERSE] start_value TO end_value DO
statement;
[statement; ... ]
END FOR [label] ;
or
FOR counter_var IN [REVERSE] start_value TO end_value LOOP
statement;
[statement; ... ]
END LOOP [label] ;Arguments
counter_var: Variable name.
- The name counter_var is only valid within the scope of the FOR loop.
- If a variable with the same name is already declared outside the loop, the outer and loop variables are separate. Inside the loop, references to counter_var resolve to the loop-local variable.
- Modifying the value of counter_var inside the loop is technically possible, but not recommended.
start_value: The starting value of counter_var, either an INTEGER or an expression that results in an INTEGER.
end_value: The ending value of counter_var, either an INTEGER or an expression that results in an INTEGER. end_value must be greater than or equal to start_value. If end_value < start_value, the loop runs 0 times, even if the REVERSE keyword is used.
statement: One (or more) statements of the following types:
- A single SQL statement (including
CALL). - A control flow statement (e.g. loop or conditional).
- A nested block.
label (optional): A label defines a jump target for BREAK or CONTINUE statements.
Usage Notes
- The iteration range includes the end point. Example:
FOR i IN 1 TO 10will execute withi = 10on the last loop. - Using the
REVERSEkeyword makes the loop run “backwards”, including thestartvalue. - A loop can contain multiple statements. Optionally, a
BEGIN … ENDblock can be used to enclose them. - When using the
FOR ... DOform, useEND FORto close the loop. When usingFOR ... LOOP, useEND LOOP.
Example 1 | FOR with Number of Iterations
sql
CREATE PROCEDURE mkw_doku.for_with_count(count_iter INTEGER)
RETURNS INTEGER
AS
DECLARE
count INTEGER DEFAULT 0;
BEGIN
FOR i IN 1 TO :count_iter DO
LET count := :count + 1;
END FOR;
RETURN :count;
END;
CALL mkw_doku.for_with_count(3);txt
Procedure 'mkw_doku.for_with_count' was successfully executedExample 2 | FOR with REVERSE
sql
CREATE PROCEDURE mkw_doku.for_with_reverse(count_iter INTEGER)
RETURNS STRING
AS
DECLARE
count_text STRING DEFAULT '';
BEGIN
FOR i IN REVERSE 1 TO :count_iter DO
count_text := :count_text || ' ' || :i;
END FOR;
RETURN :count_text;
END;
CALL mkw_doku.for_with_reverse(3);txt
Procedure 'mkw_doku.for_with_reverse' was successfully executed