📜  PL / SQL-循环

📅  最后修改于: 2020-11-26 05:52:51             🧑  作者: Mango


在本章中,我们将讨论PL / SQL中的循环。在某些情况下,您需要多次执行一个代码块。通常,语句是按顺序执行的:函数的第一个语句首先执行,然后第二个执行,依此类推。

编程语言提供了各种控制结构,允许更复杂的执行路径。

循环语句使我们可以多次执行一个语句或一组语句,以下是大多数编程语言中循环语句的一般形式-

循环架构

PL / SQL提供以下类型的循环来处理循环需求。单击以下链接以查看其详细信息。

S.No Loop Type & Description
1 PL/SQL Basic LOOP

In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

2 PL/SQL WHILE LOOP

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

3 PL/SQL FOR LOOP

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

4 Nested loops in PL/SQL

You can use one or more loop inside any another basic loop, while, or for loop.

标记PL / SQL循环

可以标记PL / SQL循环。标签应该用双尖括号(<<和>>)括起来,并出现在LOOP语句的开头。标签名称也可以出现在LOOP语句的末尾。您可以使用EXIT语句中的标签退出循环。

以下程序说明了概念-

DECLARE 
   i number(1); 
   j number(1); 
BEGIN 
   << outer_loop >> 
   FOR i IN 1..3 LOOP 
      << inner_loop >> 
      FOR j IN 1..3 LOOP 
         dbms_output.put_line('i is: '|| i || ' and j is: ' || j); 
      END loop inner_loop; 
   END loop outer_loop; 
END; 
/

当以上代码在SQL提示符下执行时,将产生以下结果-

i is: 1 and j is: 1 
i is: 1 and j is: 2 
i is: 1 and j is: 3 
i is: 2 and j is: 1 
i is: 2 and j is: 2 
i is: 2 and j is: 3 
i is: 3 and j is: 1 
i is: 3 and j is: 2 
i is: 3 and j is: 3  

PL/SQL procedure successfully completed. 

循环控制语句

循环控制语句从其正常顺序更改执行。当执行离开作用域时,在该作用域中创建的所有自动对象都将被销毁。

PL / SQL支持以下控制语句。标签循环还有助于使控件脱离循环。单击以下链接以查看其详细信息。

S.No Control Statement & Description
1 EXIT statement

The Exit statement completes the loop and control passes to the statement immediately after the END LOOP.

2 CONTINUE statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 GOTO statement

Transfers control to the labeled statement. Though it is not advised to use the GOTO statement in your program.