3-11. Iterating in Increments Other Than One

Problem

Rather than iterating through a range of numbers one at a time, you want to increment by some other value. For example, you might want to increment through even values such as 2, 4, 6, and so forth.

Solution

Multiply the loop index by two (or by whatever other multiplier you need) to achieve the effect of incrementing through all even numbers. As you can see in the following example, an even number is always generated when the index is multiplied by two:

BEGIN
  FOR idx IN 1..5 LOOP
    DBMS_OUTPUT.PUT_LINE('The current index is: ' || idx*2);
  END LOOP;
END;

Here is the result:

The current index is: 2
The current index is: 4
The current index is: 6
The current index is: 8
The current index is: 10

PL/SQL procedure successfully completed.

How It Works

Unlike some other languages, PL/SQL does not include a STEP clause that can be used while looping. To work around that limitation, you will need to write your own stepping algorithm. In the solution to this recipe, you can see that the algorithm was quite easy; you simply multiply the index by two to achieve the desired result. In this solution, assigning the range of 1..5 as the index produces the effect of iterating through all even numbers from 2..10 when the current index is multiplied by two.

Using similar techniques, you can increment through ranges of numbers in various intervals. However, sometimes this can become troublesome if you are attempting to step by anything other than even numbers. You can see an example of this in the next recipe.

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

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