天天看點

ORACLE中decode、case when差別

轉載: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 不然實作不了。