Skip to content

WHILE

A WHILE loop constructs a loop that is repeatedly executed as long as the specified condition evaluates to TRUE.

WHILE is only valid within a scripting block.

See also: BREAK, CONTINUE.

Syntax

sql
WHILE (condition) DO
    statement;
    [statement; ... ]
END WHILE [label];

or

WHILE (condition) LOOP
    statement;
    [statement; ... ]
END LOOP [label];

Arguments

condition: An expression that returns a BOOLEAN value.


statement: One or more statements of the following types:

  • A single SQL statement (including CALL).
  • A control-flow statement (e.g., loop or branch).
  • A nested block.

label (optional): A label allows the definition of a jump target for a BREAK or CONTINUE statement.

Usage Notes

  • The condition in WHILE must be enclosed in parentheses.

WARNING

If no BREAK statement (or similar mechanism) is defined within a WHILE loop and the specified condition never equals FALSE, the loop will execute infinitely.

  • If the condition evaluates to NULL, it is treated as FALSE.
  • A loop can contain multiple statements. It's also possible (but not required) to use a BEGIN … END block to group the statements.

Example

sql
CREATE OR REPLACE PROCEDURE 
        mkw_doku.countdown(countdown_start INTEGER)
RETURNS INTEGER
AS
DECLARE
    counter INTEGER;     -- Iteration Counter
    countdown INTEGER;   -- Countdownvalue
BEGIN
    counter := 0;
    countdown := countdown_start;
        WHILE (countdown >= 0) DO
            countdown := countdown - 1;
            counter := counter + 1;
        END WHILE;
        RETURN counter;
END;

CALL mkw_doku.countdown(10);
txt
Procedure 'mkw_doku.countdown' was successfully executed