您的位置:首页 > 数据库

PL/SQL 控制结构

2010-05-24 17:55 344 查看
在PL/SQL中引入了控制结构,包括选择结构,循环结构和跳转结构

一 选择结构

1,IF 语句

在PL/SQL中,选择结构可以通过if语句来实现,也可以通过Case语句(oracle9i中)

利用if语句实现选择控制的语法为:

if condition1 then statements1;

[else if condition2 then statements2;]

......

[else else_statements];

end if;

由于PL/SQL 中的逻辑运算结果有true,false 和null 三种,因此在进行选择条件的判断时,要考虑条件为null的情况

2,CASE 语句

在Oracle9i中提供了另一种选则控制结构,即case语句。case 语句有两种形式,一种只进行等值比较,另一种可以进行多条件比较。

(1)只进行等值比较的case语句;

Case test_value

when value1 then statements1;

when value2 then statements2;

......

when valuen then statementsn;

[else else_statements;]

end case;

case 语句判断test_value 的值是否与value值相等。如果相等,则执行其后的语句。

(2) 可以多条件比较case 语句

case

when condition1 then statements1;

when condition2 then statements2;

......

when conditionn then statementn;

[ else else_statements;]
end case;

case 语句对每一个when条件进行判断,当条件为真时,执行其后的语句;如果所有的条件都为假,则执行else后的语句。

二 循环语句

在PL/SQL中,循环结构有三种形式,分别为简单循环,while循环,for循环。

1 ,简单循环

PL/SQL中简单循环是将循环条件包含在循环体中的循环,语法为:

Loop

sequence_of_statement;

exit [when condition];

end Loop;

注意:在循环体中一定要包含exit语句,否则程序会进入死循环。

例如: 利用循环向Book表中插入50条记录,程序为:

declare
v_counter Binary_Integer :=50;
begin
Loop
insert into Book(bookid,Bookname,Bookauth,bookprice) values (v_counter,'bookname'||v_counter,'alice',888);
v_counter:=v_counter+1;
exit when v_counter>100;
end Loop;
end;

2,while 循环

利用 while 语句进行循环时,先判断循环条件,只有满足循环条件才能进入循环体进行操作,其语法为:

while condition Loop

sequence_of_statement;

end Loop;

例如:利用while循环,向Book表中插入50条数据

declare
v_counter Binary_Integer:=101;
begin
while v_counter<=150 Loop
insert into Book(bookid,Bookname,Bookauth,bookprice)
values(v_counter,'bookname'||v_counter,'alice',v_counter);
v_counter:=v_counter+1;
end Loop;
end;

3,FOR循环

在for循环中,不需要定义循环变量,系统自动定义一个循环变量,每次循环时该变量值自动增1或减1,以控制循环的次数。

for循环的语法为:

for loop_counter in [reverse] low_bound..high_bound Loop

Sequence_of_statement;

end loop;

其中,loop_counter 为 循环变量,low_bound为循环变量的下界(最小值),high_bound 为循环变量的上届(最大值)

注意:循环变量的类型为 binary_integer类型(系统隐含声明),而且它的作用范围是 循环体中使用,不能再循环外使用该变量。

系统默认时,循环变量为自增,如果使用reverse关键字,则表示自减。

例如:利用for循环向Book表中插入50条记录

begin
for v_counter in 151..200 Loop
insert into Book(bookid,Bookname,Bookauth,bookprice)
values(v_counter,'bookname'||v_counter,'alice',v_counter);
end Loop;
end;

三 跳转结构

所谓跳转结构是指利用goto 语句实现程序流程的强制跳转。例如(插入50条记录):

declare
v_counter Binary_Integer :=201;
begin
<<label>>
insert into Book(bookid,Bookname,Bookauth,bookprice)
values(v_counter,'bookname'||v_counter,'alice',v_counter);
v_counter:=v_counter+1;
if v_counter<=250 then
goto label;
end if;
end;

注意:PL/SQL 块内部可以跳转,内层块可以跳到外层块,但外层块不能跳到内层块;

不能从if语句外部跳转到if语句内部,不能从循环体外跳到循环体内,不能从子程序外部跳到子程序内部;

由于goto语句破坏了程序的结构化,因此建议尽量少用甚至不用goto语句;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: