1. 程式人生 > >case when 和 decode 的比較分析

case when 和 decode 的比較分析

fault sig cas 相等 from 圖片 簡潔 oracl oracle數據

一、case when

與 if - else 類似,語句如下:
CASE expr WHEN expr1 THEN return_expr1
[WHEN expr2 THEN return_expr2
...
WHEN exprn THEN return_exprn
ELSE else_expr]
END

且有兩種判斷方法,case 字段 whenthen return 值

else return 值 end

例如:

select bname , price, case when price > =10 and price <20 then ‘price1‘

when price > =20 and price <30 then ‘price2‘
when price >= 30 and price <40 then ‘price3‘

when price > =40 and price <50 then ‘price4‘

when price >= 50 and price <60 then ‘price5‘

else ‘price6‘ end "價格段"
from book;

技術分享圖片

二、 decode (Oracle數據庫獨有)

DECODE(col|expression, search1, result1
[, search2, result2,...,]
...
[, searchn, resultn,...,]
[, default])

也可以和 sign函數一起使用

也可以:decode(字段,判斷條件,返回值1,返回值2)

select decode(sign(arg1-arg2),-1, arg1, arg2) from dual;

註:sign()函數根據某個值是0、正數還是負數,分別返回0、1、-1

select price,decode(price,‘32.5‘,‘活著‘,‘其他‘ ) 書名 from book;

技術分享圖片

三、比較

 1.DECODE 是Oracle特有的;

 2.CASE WHEN 是Oracle, SQL Server,MySQL 都可用;

 3.DECODE 只能用做相等判斷,但是可以配合sign函數進行大於,小於,等於的判斷;CASE可用於=,>=,<,<=,<>,is null,is not null 等的判斷;

4.DECODE 使用其來比較簡潔,CASE 雖然復雜但更為靈活。

case when 和 decode 的比較分析