case when 和 decode 的比較分析

1、case when數據庫

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

且有兩種判斷方法,case  字段  when  值    then  return 值函數

                                 else    return 值  endspa

例如:code

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

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

when price > =40 and price <50 then 'price4'select

when price >= 50 and price <60 then 'price5'方法

else 'price6' end "價格段"
from book;im

2、 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

   select price,decode(price,'32.5','活着','其餘' ) 書名 from  book;     

3、比較

 1.DECODE 是Oracle特有的;

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

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

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

相關文章
相關標籤/搜索