Stephen Walsh
Stephen Walsh

Reputation: 835

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

Upvotes: 3

Views: 7611

Answers (2)

Mohamed.Abdo
Mohamed.Abdo

Reputation: 2200

SET SERVEROUTPUT ON;--default buffer size is 1000 000
declare 
idx number:=0;
step number:=10000;
begin
DBMS_OUTPUT.ENABLE(Null);-- unlimited output buffer
for i in 1..3 loop
 DBMS_OUTPUT.PUT_LINE('idex: from [' ||idx|| ' ] to [' || (idx+step) || ']');
 --..... you loop logic
  select t.id, row_number() over(order by t.id) rw
         from t
         where rw >= idx and rw < (idx+step)
 idx:= idx+step; --increment step.
end loop;
end;

Upvotes: 0

uncaught_exception
uncaught_exception

Reputation: 1078

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;

Upvotes: 6

Related Questions