注意点:
1、以CASE开头,以END结尾
2、分支中WHEN后跟条件,THEN为显示结果
3、ELSE为除此之外的默认情况,类似于高级语言程序中switch case的default,可以不加
4、END后跟别名
CASE有两种表达式:
1.简单CASE表达式,使用表达式确定返回值.
语法:
CASE search_expression
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
ELSE default_result
END
例:
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
结果:
PRODUCT_ID PRODUCT_TYPE_ID CASEPROD
---------- --------------- --------
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
例:
select product_id,product_type_id,
case
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
结果与上相同.
本文深入探讨了SQL中的CASE表达式,包括其工作原理、语法结构和具体应用案例,帮助读者理解如何利用CASE表达式实现if-then-else型逻辑,避免使用PL/SQL。通过实例展示了CASE表达式的两种形式,以及如何根据产品类型ID来分类产品类型。
1426

被折叠的 条评论
为什么被折叠?



