1

我正在尝试更改 For 循环中上限的值,但循环一直运行到开始时定义的上限。

根据逻辑循环应该是无限的,因为 v_num 的值总是比 i 提前一个,但是循环执行了 3 次。请解释

这是代码

    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
4

4 回答 4

7

此行为在文档中指定:

FOR-LOOP
...
范围在首次进入 FOR 循环时进行评估,并且永远不会重新评估。

(甲骨文文档)

于 2010-04-12T18:44:22.973 回答
1

Generally, FOR loops would be fixed iterations

For indeterminate looping, use WHILE

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

于 2010-04-12T19:10:52.220 回答
0

虽然通常认为更改循环变量的值是个坏主意,但有时这似乎是唯一的方法。但是,您可能会发现循环已经过优化,这可能就是这里发生的情况。

于 2010-04-12T18:40:46.243 回答
0

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.

于 2010-04-12T18:44:41.010 回答