基本的 LOOP 语句会重复执行一序列语句。语法格式如下:

    1. LOOP
    2. statement [, statement ]...
    3. END LOOP;

    其中,LOOP 和 END LOOP 之间的语句中,至少要有一个语句包含 EXIT 语句;否则 LOOP 语句会一直重复永不停止。

    EXIT 语句可以带一个可选的 WHEN 子句,表示当条件为 TRUE 的时候,执行 EXIT 语句并将控制跳转到的 END LOOP 语句后。

    示例:使用基本的 LOOP 和 EXIT WHEN 语句

    1. delimiter /
    2. CREATE OR REPLACE PROCEDURE sp_test_loop_exit_when
    3. AS
    4. i_counter number := 10;
    5. BEGIN
    6. LOOP
    7. dbms_output.put_line('In the loop i_counter is ' || to_number(i_counter) );
    8. i_counter := i_counter - 1;
    9. EXIT WHEN i_counter <= 0;
    10. END LOOP;
    11. dbms_output.put_line('Out of the loop i_counter is ' || to_number(i_counter) );
    12. EXCEPTION
    13. WHEN OTHERS THEN
    14. NULL;
    15. END;
    16. /
    17. delimiter ;
    18. obclient>
    19. obclient> set serveroutput on;
    20. Query OK, 0 rows affected (0.00 sec)
    21. obclient> call sp_test_loop_exit_when();
    22. Query OK, 0 rows affected (0.05 sec)
    23. In the loop i_counter is 10
    24. In the loop i_counter is 9
    25. In the loop i_counter is 8
    26. In the loop i_counter is 7
    27. In the loop i_counter is 6
    28. In the loop i_counter is 5
    29. In the loop i_counter is 4
    30. In the loop i_counter is 3
    31. In the loop i_counter is 2
    32. In the loop i_counter is 1
    33. Out of the loop i_counter is 0
    34. obclient>

    注意

    EXIT WHEN 语句的顺序可以根据子程序的业务逻辑调整,如果它在改变条件变量的语句的前面,将会多进入循环一次。