Sunday, December 22, 2013

For Loop PL/SQL Example Code and Syntax


For Loop Overview and Defintion


Whereas the number of iterations through a WHILE loop is unknown until the loop completes, the number of iterations through a FOR loop is known before the loop is entered. FOR loops iterate over a specified range of integers. The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP. A double dot (..) serves as the range operator. The syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP
sequence_of_statements
END LOOP;

Syntax For Loop In Oracle


FOR Conditions
Loop Statements
END LOOP

For Loop Evaluation Formula In Oracle PL/SQL


The range is evaluated when the FOR loop is first entered and is never re-evaluated.

As the next example shows, the sequence of statements is executed once for each integer in the range. After each iteration, the loop counter is incremented.

FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i
sequence_of_statements -- executes three times
END LOOP;

For Loop PL/SQL Example Code: Start With 1 to 10


BEGIN
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE('Current Number :'||i);
END LOOP;
END;
/

For Loop PL/SQL Example Code: Start With 10 to 17


BEGIN
FOR i IN 10..17 LOOP
DBMS_OUTPUT.PUT_LINE('Current Number :'||i);
END LOOP;
END;
/

For Loop PL/SQL Example Code: Start & End With variables value


DECLARE
StartValue NUMBER := 10;
EndValue   NUMBER := 20;
BEGIN
FOR i IN StartValue .. EndValue LOOP
DBMS_OUTPUT.PUT_LINE('Current Number :'||i);
END LOOP;
END;
/

No comments:

Post a Comment