3-7. Iterating Until a Condition Evaluates to FALSE

Problem

You want to iterate over a series of statements until a specified condition no longer evaluates to TRUE.

Solution

Use a WHILE statement to test the condition, and execute the series of statements if the condition evaluates to TRUE; otherwise, skip the statements completely. The following example shows a WHILE statement evaluating the current value of a variable and looping through until the value of the variable reaches ten. Within the loop, this variable is being multiplied by two and printing out its current value.

DECLARE
  myValue    NUMBER := 1;
BEGIN
WHILE myValue < 10 LOOP
      DBMS_OUTPUT.PUT_LINE('The current value is: ' || myValue);
      myValue := myValue * 2;
  END LOOP;
END;

Here are the results:

The current value is: 1
The current value is: 2
The current value is: 4
The current value is: 8

PL/SQL procedure successfully completed.

The important thing to note in this example is that the value of myValue is increased with each iteration of the loop as to eventually meet the condition specified in the WHILE loop.

How It Works

The WHILE loop tests a condition at the top of the loop, and if it evaluates to TRUE, then the statements within the loop are executed, and control is returned to the start of the loop where the condition is tested again. If the condition does not evaluate to TRUE, the loop is bypassed, and control goes to the next statement after the END LOOP. If the condition never fails, then an infinite loop is formed, so it is important to ensure that the condition will eventually evaluate to FALSE.

It is important to note that the statements in the loop will never be executed if the condition evaluates to FALSE during the first pass. This situation is different from the simple loop that always iterates at least once because the EXIT condition is usually evaluated elsewhere in the loop.

To ensure that a WHILE loop is always executed at least one time, you must ensure that the condition evaluates to TRUE at least once. One way to do this is to use a flag variable that is evaluated with each iteration of the loop. Set the flag equal to FALSE prior to starting the loop, and then set it to TRUE when a certain condition is met inside the loop. The following pseudocode depicts such a solution:

BEGIN
  flag = FALSE;
  WHILE flag = TRUE LOOP
    Perform statements
    flag = Boolean expression;
    END LOOP;
END;

As mentioned previously, the boolean expression that is assigned to the flag in this case must eventually evaluate to FALSE; otherwise, an infinite loop will occur.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.87.35