PL/SQL流程控制
–if分支:语法如下
if 条件 then
. . .
end if;
–if else:语法如下
if 条件 then
. . .
else
. . .
end if;
–if else if:语句如下
if 条件 then
. . .
elsif 条件 then
. . .
end if;
案例:
1.判断张三和李四的年龄
declare
zhangsan number(3):=30;
lisi number(3):=25;
begin
if zhangsan >lisi then
dbms_output.put_line('张三比李四年龄大');
end if;
end;
2.判断两个值的大小
declare
a number(3):=10;
b number(3):=50;
begin
if a>b then
dbms_output.put_line('a大于b');
else
dbms_output.put_line('a小于b');
end if;
end;
3.判断每个月有多少天
declare
month number(2):=2;
begin
if month=1 or month=3
or month=5 or month=7
or month=8 or month=10
or month=12 then
dbms_output.put_line(month || '月份有31天');
elsif month=2 then
dbms_output.put_line(month || '月份有28天');
else
dbms_output.put_line(month || '月份有30天');
end if;
end;
–CASE WHEN:相当于java中的switch … case分支
语法:
case 匹配变量
when 匹配值 then 执行语句
when 匹配值 then 执行语句
else 默认执行语句
end case;
或者
case
when 条件 then 执行语句
when 条件 then 执行语句
else 默认执行语句
end case;
案例:
查询成绩等级所对应的分值范围
declare
grade char(1):='A'
begin
case grade
when 'A' then
dbms_output.put_line('90~100分为A等级');
when 'B' then
dbms_output.put_line('80~89分为B等级');
when 'C' then
dbms_output.put_line('70~79分为C等级');
else
dbms_output.put_line('70分以下为D等级');
end case;
end;
或
declare
grade char(1):='A'
begin
case
when grade='A' then
dbms_output.put_line('90~100分为A等级');
when grade= 'B' then
dbms_output.put_line('80~89分为B等级');
when grade ='C' then
dbms_output.put_line('70~79分为C等级');
else
dbms_output.put_line('70分以下为D等级');
end case;
end;
第二种方式相对灵活,when 后面可以跟任意条件语句,只要为true既能执行then后面的执行语句.
–PL/SQL循环控制
–基本循环:loop
loop
循环体
end loop;
注意:该循环如果不加条件则是死循环,所以一般搭配IF语句使用
案例:
循环输出1-10的值
declare
x number:=1;
begin
loop
x:=x+1;
if x >=10 then
exit;
end if;
dbms_output.put_line(x);
end loop;
end;
注意:exit是结束循环,相当于java中的break;
–while循环
while 条件 loop
循环体
end loop;
案例:
使用while循环输出求1-10的和
declare
x number:=1;
resu number:=0;
begin
while x>10 loop
resu:=resu+x;
x:=x+1;
end loop;
dbms_output.put_line('1-10的和为:' || result);
end;
–loop exit when:该循环,类似于java中的do while,但又有区别,when 循环条件为退出的条件,而不是再次循环的条件,当条件为true则退出循环
loop
循环体
exit when 循环条件;
end loop;
案例:
声明i和total变量均为0,total等于自身加上i的值,当total 的值>1000的时候,i的值是几
declare
i number:=0;
total number:=0;
begin
loop
i:=i+1;
total:=total+i;
exit when total>1000;
end loop;
dbms_output.put_line('当total的值是'||total||'时,i的值是'||i);
end;
–for 循环
for 循环变量 in [reverse]起始值…终止值
loop
循环体
end loop;
注:reverse反转的意思,可以让循环变量的值反转执行,比如1-10,变为10-1递减.
案例:
输出循环变量
begin
for i in 1 .. 10 loop
dbms_output.put_line(i);
end loop;
end;
案例:
倒序输出循环变量
begin
for i in revsere 1 .. 10 loop
dbms_output.put_line(i);
end loop;
end;
案例:
循环输出变量,跳过3和5
begin
for i in 1 ..10 loop
if i=3 or i=5 then
continue;
end if;
dbms_output.put_line(i);
end loop;
end;
–声明常量:使用constant关键字声明,声明过的常量值不能改变,声明的同时赋值
案例:
declare
pi constant number:=3.1415926;
begin
dbms_output.put_line(pi);
pi:=pi+1;
end;
注意:以上案例会报错:报错的原因就是声明的pi是常量,但是在语句块内尝试改变pi的值,所以报错.