FOR 循环
Loop FOR 适用于与其他循环类似的规则。FOR 循环执行的次数非常精确,这个数字在开头就已知 - 下限和上限直接在代码中设置。在此示例的每个步骤中,循环递增 1。
简单的例子:
DECLARE
v_counter NUMBER(2); --declaration of counter variable
BEGIN
v_counter := 0; --point of start, first value of our iteration, execute of variable
FOR v_counter IN 1..10 LOOP --The point, where lower and upper point of loop statement is declared - in this example, loop will be executed 10 times, start with value of 1
dbms_output.put_line('Current iteration of loop is ' || v_counter); --show current iteration number in dbms script output
END LOOP; --end of loop declaration
END;
结果是:
Current iteration of loop is 1
Current iteration of loop is 2
Current iteration of loop is 3
Current iteration of loop is 4
Current iteration of loop is 5
Current iteration of loop is 6
Current iteration of loop is 7
Current iteration of loop is 8
Current iteration of loop is 9
Current iteration of loop is 10
Loop FOR 有额外的属性,它正在反向工作。在循环的下限和上限的声明中使用附加单词 REVERSE
允许这样做。每次执行 v_counter 的循环递减值为 1。
例:
DECLARE
v_counter NUMBER(2); --declaration of counter variable
BEGIN
v_counter := 0; --point of start
FOR v_counter IN REVERSE 1..10 LOOP
dbms_output.put_line('Current iteration of loop is ' || v_counter); --show current iteration number in dbms script output
END LOOP; --end of loop declaration
END;
结果如下:
Current iteration of loop is 10
Current iteration of loop is 9
Current iteration of loop is 8
Current iteration of loop is 7
Current iteration of loop is 6
Current iteration of loop is 5
Current iteration of loop is 4
Current iteration of loop is 3
Current iteration of loop is 2
Current iteration of loop is 1