views:

53

answers:

4

Hi ALL, I am trying to change the value of upper bound in For loop ,but the Loop is running till the upper bound which was defined in the starting.

According to logic loop should go infinite, since value of v_num is always one ahead of i,But loop is executing three time.Please explain

This is the code

    DECLARE
    v_num number:=3;
    BEGIN
        FOR i IN 1..v_num LOOP
           v_num:=v_num+1;
           DBMS_OUTPUT.PUT_LINE(i ||'  '||v_num);
     END LOOP;
    END;
Ouput Coming

    1  4
    2  5
    3  6
A: 

While it is generally considered a bad idea to change the loop variable's value, sometimes it seems like the only way to go. However, you might find that loops are optimized, and that might be what is happening here.

MJB
+7  A: 

This behavior is as specified in the documentation:

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

(Oracle Documentation)

Heath Hunnicutt
A: 

There's nothing preventing the language designers from saying "The upper bound of the for loop is evaluated only once". This appears to be the rule that plsql is following here.

Yuliy
+1  A: 

Generally, FOR loops would be fixed iterations

For indeterminate looping, use WHILE

This isn't Oracle specific, and why there are separate looping constructs.

gbn