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 ...

Get Oracle and PL/SQL Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.