PL/SQL - 嵌套循环



PL/SQL 允许在一个循环内使用另一个循环。下面的部分展示了几个示例来阐释该概念。

PL/SQL 中嵌套基本 LOOP 语句的语法如下所示 −

LOOP 
   Sequence of statements1 
   LOOP 
      Sequence of statements2 
   END LOOP; 
END LOOP;

PL/SQL 中嵌套 FOR LOOP 语句的语法如下所示 −

FOR counter1 IN initial_value1 .. final_value1 LOOP 
   sequence_of_statements1 
   FOR counter2 IN initial_value2 .. final_value2 LOOP 
      sequence_of_statements2 
   END LOOP; 
END LOOP;

Pascal 中嵌套 WHILE LOOP 语句的语法如下所示 −

WHILE condition1 LOOP 
   sequence_of_statements1 
   WHILE condition2 LOOP 
      sequence_of_statements2 
   END LOOP; 
END LOOP; 

示例

下面的程序使用一个嵌套基本循环来找出 2 到 100 之间的质数 −

DECLARE 
   i number(3); 
   j number(3); 
BEGIN 
   i := 2; 
   LOOP 
      j:= 2; 
      LOOP 
         exit WHEN ((mod(i, j) = 0) or (j = i)); 
         j := j +1; 
      END LOOP; 
   IF (j = i ) THEN 
      dbms_output.put_line(i || ' is prime'); 
   END IF; 
   i := i + 1; 
   exit WHEN i = 50; 
   END LOOP; 
END; 
/

当在 SQL 提示符下执行上述代码时,它会产生以下结果 −

2 is prime 
3 is prime 
5 is prime 
7 is prime 
11 is prime 
13 is prime 
17 is prime 
19 is prime 
23 is prime 
29 is prime 
31 is prime 
37 is prime 
41 is prime 
43 is prime 
47 is prime  

PL/SQL procedure successfully completed. 
plsql_loops.htm
广告