FOR 循环中的上界在循环中不会改变,为什么?

发布于 2024-08-28 13:27:09 字数 353 浏览 15 评论 0原文

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

根据逻辑循环应该无限,因为 v_num 的值总是比 i 早 1,但是循环执行了三次。请解释一下

这是代码

    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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风轻花落早 2024-09-04 13:27:09

此行为如文档中所指定:

FOR 循环
...
首次进入 FOR 循环时会计算范围,并且不会重新计算。

(Oracle 文档)

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)

感情洁癖 2024-09-04 13:27:09

一般来说,FOR 循环是固定迭代

对于不确定循环,请使用 WHILE

这不是不是 Oracle 特有的,以及为什么有单独的循环结构。

Generally, FOR loops would be fixed iterations

For indeterminate looping, use WHILE

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

你又不是我 2024-09-04 13:27:09

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

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.

生生漫 2024-09-04 13:27:09

没有什么可以阻止语言设计者说“for 循环的上限仅计算一次”。这似乎是 plsql 在这里遵循的规则。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文