PL/SQL 中 CASE 语句的使用

来源:互联网 发布:vb中tab是什么意思 编辑:程序博客网 时间:2024/06/02 07:31

http://www.oracle.com/technology/global/cn/sample_code/tech/pl_sql/htdocs/x/Case/start.htm

虽然 CASE 结构基本上没有给出任何新的语义,但它们的确接受一种更简洁的表示法,并且相对于 IF 结构表示法而言消除了一些重复。看下面的判定表的执行情况,是依据特殊表达式的值来决定执行情况。程序段…

case n
when 1 then Action1;when 2 then Action2;when 3 then Action3;else ActionOther;
end case;

…和…

ifn = 1 then Action1;
elsif n = 2 then Action2;
elsif n = 3 then Action2;
else ActionOther;
end if;

… 在语义是几乎是相同的。但编码最佳实践专家通常会推荐 CASE 表示法,因为它更直接地反映了概念。通过将判定表达式 n 放在开始位置并且只写一次,程序员的目的变得更清晰了。这对校对员和编译器都很有意义,因此为生成高效代码提供了更好的信息。比如说,编译器可以立即知道判定表达式只需校核一次。而 IF 表示法在每个情况段重复决策表达式,所以出现输入错误的风险更大,并且这种错误很难找出。

此外,CASE 表示法可以明确指出只有已编写代码的情况才需要处理(参见以下关于 case_not_found 异常的讨论)。

大多数编程语言都提供 CASE 结构。Oracle9i 将它们引入了 PL/SQL(和 SQL)中。

CASE 表达式

CASE 表达式选择一种结果并将之返回。CASE 表达式使用一个选择器来选择结果,选择器是一个表达式,它的值用来在几个选项中作出选择。分析一下两个语义上几乎相同的程序段

text := case n
when 1 then one when 2 then two when 3 then three else otherend case;

…和

ifn = 1 then text := one;    elsif n = 2 then text := two;    elsif n = 3 then text := three;else             text := other;
end if;

CASE 表示法明确指出该程序段的目的是为 text 提供一个值。此示例说明了在 PL/SQL 中使用 CASE 表达式。

除 CASE 表达式外还可选用 CASE 语句,其中每一个 WHEN 子句都可以作为一个完整的 PL/SQL 程序块。

Searched CASE 语句和 Searched CASE 表达式

对 CASE 语句和 CASE 表达式两者而言,searched 变量在每一个分支下测试一个任意的布尔表达式,而不是测试一个所有分支下公共的单个表达式的相等性,如下所示

case
when n = 1 then Action1;
when n = 2 then Action2;
when n = 3 then Action3;
when ( n > 3 and n < 8 ) then Action4through7;
else ActionOther;
end case;

…和…

text := case
when n = 1 then one when n = 2 then twowhen n = 3 then three when ( n > 3 and n < 8 ) then four_through_seven else otherend;

注意:在使用 CASE 表示法与使用 IF 表示法时一样,为特定数值选出的分支一般都依赖于分支编写的顺序。试分析…

casewhen this_patient.pregnant = 'Y'     then Action1;when this_patient.unconscious = 'Y'  then Action2;when this_patient.age < 5            then Action3;when this_patient.gender = 'F'       then Action4;else                                      ActionOther;end case;

一位失去知觉的孕妇将接受 Action1。此示例说明了在 PL/SQL 中使用 Searched CASE 结构。

CASE_NOT_FOUND 异常

当 ELSE 程序段被遗漏时,CASE 结构和相应的 IF 结构会有微妙的差别。使用 IF 结构时,如果没有选择任何分支,那么就不会有操作。但使用 CASE 结构时,如果没有选择任何分支,那么 case_not_found 异常(ORA-06592:在执行 CASE 语句时,没有发现 CASE£?就会触发,如下所示#133;
  ...
p:=0; q:=0; r:=0;
case
when p = 1 then Action1;
when r = 2 then Action2;
when q > 1 then Action3;
end case;
exception
when case_not_found
then Dbms_Output.Put_Line ( 'Trapped:case_not_found' );
...

此示例说明了在 PL/SQL 中捕获该异常。

Bryn Llewellyn,PL/SQL 产品经理,Oracle Corp
最新更新时间为 2003 年 1 月 7 日

原创粉丝点击