转载:https://blog.csdn.net/qq_24520119/article/details/79148682
DECODE语法:
1、decode(value,if1,then1,if2,then2,if3,then3,…,else),表示如果value=if1时,decode函数的结果返then1,…,如果不等于任何一个if值,则返回else。可以用函数或表达式来替代value,if,then,else。
2、decode(value,if,then,else),如果value=if则返回then,否则返回else。
【示例】products表
如果产品类型为1则返回’book’,如果为2则返回’video’,如果为3则返回’dvd’,如果为4则返回’cd’,否则返回’magazine’。
SELECT p.*,decode(p.product_type_id,1,‘book’,2,‘video’,3,‘dvd’,4,‘cd’,‘magazine’) type_name
FROM products p;
CASE WHEN语法:
case表达式和decode函数具有同样的功能。decode是Oracle数据库特有的函数,而case表达式则是符合SQL/92标准的语法。
case表达式有两种类型:
1,case expression
when exp1 then result1
when exp2 thenresult2
…
elsedefault
end
【示例】
products表
如果产品类型为1则返回’book’,如果为2则返回’video’,如果为3则返回’dvd’,如果为4则返回’cd’,否则返回’magazine’。
select p.*,CASE p.product_type_id
WHEN 1 THEN ‘book’
WHEN 2 THEN ‘video’
WHEN 3 THEN ‘dvd’
WHEN 4 THEN ‘cd’
ELSE ‘magazine’
END type_name
from products p;
2,case
when condition1 then result1
when condition2 then result2
……
else default
end
condition是待求值的表达式,如果它的返回值是真,则返回对应的result。
【示例】改写上个示例
condition中可以使用各种比较运算符。
【示例】products表。如果价格超过15,则显示’expensive’,否则显示’cheap’。
select p.*,CASE WHEN p.product_type_id=1 THEN ‘book’
WHEN p.product_type_id=2 THEN ‘video’
WHEN p.product_type_id=3 THEN ‘dvd’
ELSE ‘magazine’
END type_name
from products p;
SELECT p.*,CASE WHEN p.price>15
THEN ‘expensive’
ELSE ‘cheap’
END price_desc
FROM products p;
decode 与case when 的比较
1decode 只有Oracle 才有,其它数据库不支持;
2.case when的用法, Oracle、SQL Server、 MySQL 都支持;
3.decode 只能用做相等判断,但是可以配合sign函数进行大于,小于,等于的判断,case when可用于=,>=,<,<=,<>,is null,is not null 等的判断;
4.decode 使用其来比较简洁,CASE 虽然复杂但更为灵活;
5.在decode中,null和null是相等的,但在case when中,只能用is null来判断,示例如下:
–emp表中有一列comm,如果这列为null,则显示为0,否则,显示为原值:
select ename,decode(comm,null,0,comm) comma from emp;
select ename,(case when comm is null then 0 else comm end) comm from emp;
–必须使用is 不然实现不了。