Oracle 流程控制语句

分为选择语句循环语句两大类;
一 选择语句
1 if then ...end;
set serveroutput on
declare
var_name1 varchar2(50):='East';
var_name2 varchar2(50):='xiaoke';
begin
if length(var_name1)<length(var_name2) then
dbms_output.put_line('字符串"'||var_name1||'"的长度比"'||var_name2||'"的长度小');
end if;
end;

2 if then ... else ... end;
set serveroutput on ;
declare
var_age int:=55;
begin
if var_age>=56 then
dbms_output.put_line('您可以申请退休了');
else
dbms_output.put_line('您小于56岁,不可以申请退休');
end if;
end;

3 if then ... elsif ... elsif ... elsif ... end;
set serveroutput on
declare
var_month int:=10;
begin
if var_month>=0 and var_month<=3 then
DBMS_OUTPUT.PUT_LINE('这是春季');
elsif var_month>3 and var_month<=6 then
DBMS_OUTPUT.PUT_LINE('这是夏季');
elsif var_month>6 and var_month<=9 then
DBMS_OUTPUT.PUT_LINE('这是秋季');
elsif var_month>9 and var_month<=12 then
DBMS_OUTPUT.PUT_LINE('这是冬季');
else
dbms_output.put_line('您输入的月份不合法!!!');
end if;
end;

4 case .. when .. then ..when .. then .. end;
set serveroutput on
declare
var_season int:=3;
aboutinfo varchar2(50);
begin
case var_season
when 1 then
aboutinfo:=var_season||'季度包括1,2,3月份';
when 2 then
aboutinfo:=var_season||'季度包括4,5,6月份';
when 3 then
aboutinfo:=var_season||'季度包括7,8,9月份';
when 4 then
aboutinfo:=var_season||'季度包括10,11,12月份';
else
aboutinfo:=var_season||'季节不合法';
end case;
DBMS_OUTPUT.PUT_LINE(aboutinfo);
end;

二 循环语句
1 loop.. exit when .. end loop... end;
loop语句会先执行一次循环体,然后再判断 exit when 关键字后面的条件表达式的值是否为true 还是false;如果为true则退出循环体,否则继续执行循环体,使得程序至少能够执行一次循环体;
set SERVEROUTPUT ON
declare
sum_i int:=0;
i int:=0;
begin
loop
i:=i+1;
sum_i:=sum_i+i;
exit when i=100000;
end loop;
DBMS_OUTPUT.PUT_LINE('前100000个自然数的和是'||sum_i);
end;

2 while语句根据条件表达式的值执行零次或者多次循环体。每次执行循环体之前,首先要判断表达式的值是否为true;如果为true则执行循环体;否则退出while循环,继续执行while语句后面的其他代码;
while 条件表达式 loop ... end loop ... end;
set SERVEROUTPUT ON
declare
sum_i int:=0;
i int:=0;
begin
while i<=99 loop
i:=i+1;
sum_i:=sum_i+i;
end loop;
dbms_output.put_line('前100个自然数的和为'||sum_i);
end;

3 for语句 是一个可以预置循环次数的控制语句,有一个循环计数器,通常是一个整形变量,通过这个循环计数器来控制循环的次数。

set SERVEROUTPUT ON
declare
sum_i int:=0;
begin
for i in reverse 1..100 loop
if mod(i,2)=0 then
sum_i:=sum_i+i;
end if;
end loop;
dbms_output.put_line('前100个自然数的偶数和为'||sum_i);
end;

原文地址:https://www.cnblogs.com/yachao1120/p/7507603.html