case when 和 decode 的比較分析

來源:互聯網
上載者:User

標籤:server   圖片   ffffff   bsp   分享   活著   兩種   資料   image   

一、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  欄位  when  值    then  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 的比較分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.