以下的文章主要是介绍Oracle case的实际用法,我们大家都知道case表达式是可以在SQL中来实现if-then-else型的相关实际应用逻辑,而不一定非得使用PL/SQL。Oraclecase的工作方式与DECODE()类似,但应该使用case,因为它与ANSI兼容。
case有两种表达式:
1. 简单Oraclecase表达式,使用表达式确定返回值.
语法:
case search_expression
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
ELSE default_result
END
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
例:
select product_id,product_type_id,
case product_type_id
when 1 then 'Book'
when 2 then 'Video'
when 3 then 'DVD'
when 4 then 'CD'
else 'Magazine'
end
from products
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
结果:
PRODUCT_ID PRODUCT_TYPE_ID OraclecasePROD
---------- --------------- --------
1 1 Book
2 1 Book
3 2 Video
4 2 Video
5 2 Video
6 2 Video
7 3 DVD
8 3 DVD
9 4 CD
10 4 CD
11 4 CD
12 Magazine
12 rows selected.
2. 搜索case表达式,使用条件确定返回值.
语法:
case
WHEN condition1 THEN result1
WHEN condistion2 THEN result2
...
WHEN condistionN THEN resultN
ELSE default_result
END
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
例:
select product_id,product_type_id,
Oraclecase
when product_type_id=1 then 'Book'
when product_type_id=2 then 'Video'
when product_type_id=3 then 'DVD'
when product_type_id=4 then 'CD'
else 'Magazine'
end
from products
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
结果与上相同.
【编辑推荐】