Search code examples
sqloracle-databasefor-loopplsqlfor-in-loop

For In loop in Oracle PL/SQL


In PL/SQL, I can use a FOR IN loop to iterate from 1-20 by saying:

FOR counter IN 1..20

What I'm wondering is, is there a simple alteration I can make to this that will allow me to iterate through the loop on only the even values between 1-20? i.e. the counter would go 2, 4, 6, ... 20


Solution

  • Adding to Gordon's comment...

    This is the syntax so no built-in way

    http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/controlstatements.htm#LNPLS411

    [ label ] FOR index IN [ REVERSE ] lower_bound..upper_bound LOOP
      statements
    END LOOP [ label ];
    

    You can simulate the STEP Clause in FOR LOOP Statement

    http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/controlstatements.htm#BCGJHACI

    DECLARE
      step  PLS_INTEGER := 5;
    BEGIN
      FOR i IN 1..3 LOOP
        DBMS_OUTPUT.PUT_LINE (i*step);
      END LOOP;
    END;