Oracle之PL/SQL编程_流程控制语句
选择语句
1. if...then 语句
语法:
if < condition_expression > thenplsql_sentenceend if;
condition_expression:表示一个条件表达式,其值为 true 时,程序会执行 if 下面的 PL/SQL 语句;
如果其值为 false,则程序会跳过if 下面的语句而 直接执行 end if 后边的语句。
plsql_sentence:condition_expression 为 true 时,要执行的语句。
2. if...then...else 语句
语法:
if < condition_expression > thenplsql_sentence_1;elseplsql_sentence_2;end if;
3.if...then...elsif 语句
语法:
if < condition_expression1 > thenplsql_sentence_1;elsif < condition_expression2 > thenplsql_sentence_2;...elseplsql_sentence_n;end if;
4. case 语句
语法:
case < selector >whenthen plsql_sentence_1;when then plsql_sentence_2;...when then plsql_sentence_n;[else plsql_sentence;]end case;
selector:一个变量,用来存储要检测的值,通常称之为选择器。
该选择器的值需要与 when 子句中的表达式的值进行匹配。
expression_1:第一个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时,
程序将执行 plsql_setence_1 语句。
expression_2:第二个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时,
程序将执行 plsql_setence_2 语句。
expression_n:第 n 个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时,
程序将执行 plsql_setence_n 语句。
plsql_sentence:一个 PL/SQL 语句,当没有与选择器匹配的 when 常量时,程序将执行该 PL/SQL 语句,
其所在的 else 语句是一个可选项。
例:
指定一个季度数值,然后使用 case 语句判断它所包含的月份信息并输出。
代码:
declareseason int:=3;aboutlnfo varchar2(50);begincase seasonwhen 1 thenaboutlnfo := season||'季度包括1,2,3 月份';when 2 thenaboutinfo := season||'季度包括4,5,6 月份';when 3 thenaboutinfo := season||'季度包括7,8,9 月份';when 4 thenaboutinfo := season||'季度包括10,11,12 月份';elseaboutinfo := season||'季节不合法';end case;dbms_output.put_line(aboutinfo);end;
结果:3季度包括7,8,9 月份
循环语句
1. loop 语句
语法:
loopplsql_sentence;exit when end_condition_expend loop;
plsql_sentence:循环体中的PL/SQL 语句。至少被执行一遍。
end_condition_exp:循环结束条件表达式,当该表达式为 true 时,则程序会退出循环体,否则程序将再次执行。
例:
使用 loop 语句求得前 100 个自然数的和,并输出到屏幕。
SQL> set serveroutput on;SQL> declaresun_i int:=0;i int:=0;beginloopi:=i+1;sum_i:=sum_i +1;exit when i =100;--当循环 100次,程序退出循环体。end loop;dbms_output.put_line('前100个自然数和:'||sum_i);end;/2. while 语句
语法:
while condition_expression loopplsql_sentence;end loop;
condition_expression: 表示一个条件表达式,但其值为 true 时,程序执行循环体。
否则 程序退出循环体,程序每次执行循环体之前,都判断该表达式是否为 true。
plsql_sentence:循环内的plsql语句。
例:
使用while 语句求得 前100 个自然数的和,并输出到屏幕。
declare sum_i int:=0;i int:=0;beginwhile i<=99 loop i:=i+1; sum_i:=sum_i+1;end loop;dbms_output.put_line('前100 个自然数的和是:'||sum_i);end;/3. for 语句
语法:
for variable_counter_name in [reverse] lower_limit..upper_limit loopplsql_sentence;end loop;
variable_counter_name:表示一个变量,通常为整数类型,用来作为计数器。
默认情况下 计数器的值会递增,当在循环中使用 reverse 关键字时,计数器的值会随循环递减。
lower_limit:计数器下限值,当计数器的值小于下限值时,退出循环。
upper_limit:计数器上限值,当计数器的值大于上限值时,退出循环。
plsql_sentence:循环内的plsql语句。
例:
使用for语句求得前 100个自然数中偶数之和,并输出到屏幕。
declaresum_i int:= 0;beginfor i in reverse 1..100 loopif mod(i,2)=0 then--判断是否为偶数 sum_i:=sum_i+i;end if;end loop;dbms_output.put_line('前100个自然数中偶数和:'||sum_i);end;/