日期:2014-05-16  浏览次数:20417 次

oracle case when else 语法和用法

case when else 基本结构:
case n
? when 1 then Action1;
when 2 then Action2;
when 3 then Action3;
else??????? ActionOther;
end;
示例一:
SELECT col1, col2,??
?????? CASE??
????????? WHEN col3 > 1 AND col3 <2??
???????????? THEN '1'??
????????? WHEN col3 > 2 AND col3 <3??
???????????? THEN '2'??
????????? WHEN col3 > 3 AND col3 <4??
???????????? THEN '3'??
????????? ELSE '4'??
?????? END mylevel??
FROM table_51xit
case when else语法要点说明如下:
1、以CASE开头,以END结尾
2、分支中WHEN 后跟条件,THEN为显示结果
3、ELSE 为除此之外的默认情况,类似于高级语言程序中switch case的default,可以不加
4、END 后跟别名
示例:更复杂的示例代码:
select d.districtcode,(case when (substr(d.districtcode,3,6) = '0000') then ('100000'||substr(d.districtcode,1,2))
???????????????????? when (substr(d.districtcode,5,6) = '00') then ('100000'||substr(d.districtcode,1,2)||'00'||substr(d.districtcode,3,2))
???????????????????? else? ('100000'||substr(d.districtcode,1,2)||'00'||substr(d.districtcode,3,2)||'00'||substr(d.districtcode,5,2))
???????????????????? end) unitcode From vcmdistrictcode d where
not exists
(
select 1 From vcmunitinfo u where u.unitdistrictcode=d.districtcode
and u.unitcode=(case when (substr(d.districtcode,3,6) = '0000') then ('100000'||substr(d.districtcode,1,2))
???????????????????? when (substr(d.districtcode,5,6) = '00') then ('100000'||substr(d.districtcode,1,2)||'00'||substr(d.districtcode,3,2))
???????????????????? else? ('100000'||substr(d.districtcode,1,2)||'00'||substr(d.districtcode,3,2)||'00'||substr(d.districtcode,5,2))
???????????????????? end)
)
转自:http://tanw.iteye.com/blog/701023