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