7.6.6. WHILE …​ DO

Used for

Looping constructs

Available in

PSQL

Syntax

  1. WHILE <condition> DO
  2. <compound_statement>
Table 85. WHILE …​ DO Parameters
ArgumentDescription

condition

A logical condition returning TRUE, FALSE or UNKNOWN

single_statement

A single statement terminated with a semicolon

compound_statement

Two or more statements wrapped in BEGIN …​ END

A WHILE statement implements the looping construct in PSQL. The statement or the block of statements will be executed until the condition returns TRUE. Loops can be nested to any depth.

Example

A procedure calculating the sum of numbers from 1 to I shows how the looping construct is used.

  1. CREATE PROCEDURE SUM_INT (I INTEGER)
  2. RETURNS (S INTEGER)
  3. AS
  4. BEGIN
  5. s = 0;
  6. WHILE (i > 0) DO
  7. BEGIN
  8. s = s + i;
  9. i = i - 1;
  10. END
  11. END

Executing the procedure in isql:

  1. EXECUTE PROCEDURE SUM_INT(4);

the result is:

  1. S
  2. ==========
  3. 10

See also

IF …​ THEN …​ ELSE, LEAVE, EXIT, FOR SELECT, FOR EXECUTE STATEMENT