PL/SQL 嵌套循環(huán)

2021-08-30 16:45 更新
PL/SQL允許在另一個循環(huán)中使用一個循環(huán)。 以下部分顯示了幾個例子來說明這個概念。

PL/SQL中嵌套的基本LOOP語句的語法如下:

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

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;
SQL

PL/SQL中嵌套的WHILE LOOP循環(huán)語句的語法如下:

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

示例

以下程序使用嵌套的基本循環(huán)來求出2100之間的素數(shù) -

SET SERVEROUTPUT ON SIZE 999999;
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

在SQLPlus中執(zhí)行上面示例代碼,得到以下結(jié)果 -

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 過程已成功完成。

 




以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號