pl/sql条件和顺序控制

在前一篇blog,写了if的condition的控制,见:点击打开链接

接着这个话题,这里谈if和case。

if先。

几种常见的if组合:

1)if-then组合

语法:
if condition
then
statement;
end if;

注释:
最简单的if判断。

2)if-then-else组合

语法:
if condition_1
then
statement_1;
else
statement_2;
end if;

注释:
如果在两个互斥的行为中作出抉择,这或者不赖。因为if-then-else是一个“或者...或者”的结构,因此“两虎相斗,必有一伤”,一旦合适的被执行,控制权立即交割。

3) if-then-elsif组合

语法:
if condition_1
then
statement_1;
elsif condition_2
then
statement_2;
[else
statement_3; --else子句为可选项
]
end if;

注释:
9i之后,使用case语句会更好点。

逻辑较复杂的,或者会涉及到嵌套if。

if condition_1
then
  if condition_2
  then
    statement_2;
  else
    if condition_3
    then
      statement_3;
    elsif condition_4
    then
      statement_4;
    end if;
  end if;
end if;


如果条件逻辑所使用的嵌套已然超过3层,那么你可以考虑用函数等模块来隐藏最内层的if语句。嵌套if的一个好处就是可以延迟对于内层条件的求值,这也是我们使用它的主要理由,只有当另一个条件为true时,这个条件才会被执行。比如,劳动周令班干部去扫地:

if check_monitor(stu_id)
then
  if clean_room(stu_id)
  then
    dbms_output.put_line("劳动周全部由班干部去劳动哈");
  end if;
end if;


if 语法陷阱

一个if总要有一个匹配的end if,且在关键字end 和 if之间要有空格;
关键字elsif不要夹带“e”;
只在关键字end if后使用分号(;)

case 语句

1)类别
简单型的case语句
搜索型的case语句


2)简单型的case
定义:根据一个简单的表达式的结果来选择要执行的pl/sql语句
语法:
case expression
when result_1
then
statement_1;
when result_2
then
statement_2;
...
else
statement_n;
end case;
注释:
1)在case中,else的行为和在if中完全不一样!case中,若未定义else,而且when中没有能配得上case表达式的结果值,那么就会抛出case_not_found异常。
2)case语法,expression和result元素,既可以是标量,也可以是能够得到标量结果的表达式。
例子:
case true
when salary>=1000 and salary<=2000
then
give_bonus(employee_id,150);
when salary>2000 and salary<=4000
then
give_bonus(employee_id,100);
else
give_bonus(employee_id,0);
end case;

搜索型的case
定义:对一系列布尔表达式求值,一旦某个表达式求值结果为true,则执行和该表达式关联的pl/sql语句
语法:
case
when expression_1
statement_1;
when expression_2
statement_2;
...
else
statement_n;
end case;
注释:
1)when表达式,至上而下顺序求值。将最可能的when语句置顶,或者会额外地收获性能上的好处。
2)注意when表达式的边界重叠问题
例子:
case
when salary>4000
then
give_bonus(employee_id,150);
when salary>2000
then
give_bonus(employee_id,100);
else
give_bonus(employee_id,0);
end case;

case表达式。在前边blog已写。见:点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值