case when then與decode分析比較

來源:互聯網
上載者:User

case when 在不同條件需要有不同傳回值的情況下使用非常方便,可以在給變數賦值時使用,也可以在select查詢語句中使用

(有一個滿足,就立刻退出)


--搜尋格式,case後無內容

str:=case

when i=1 then 'a'

when i=2 then 'b'

else 'c'

end;    --此處賦值,為表達,不用end case。若不賦值給str,則需要用end case。


--表達語句格式。需要的變數放在case後,而不是when中

case var

when 1 then 'a'

when 2 then 'b'

else 'c'

end;

註:搜尋中when後是條件,表達中when後是值。中間無分號,是一整條連寫

(表達格式與decode類似,即各個以值來進行區分)

decode(var,1,'a',2,'b','c')


--select中使用

select case i when 1 then 'a'

when 2 then 'b'

when 3 then 'c'

else 'd'

end case from table1;


case when和decode可以用來做列轉行轉換

select Name,
      sum(decode(Course, '語文', Grade, 0)) 語文,
      sum(decode(Course, '數學', Grade, 0)) 數學,
      sum(decode(Course, '英語', Grade, 0)) 英語
from S
group by Name;

-------------

end與end case:在end後加與不加case

在運算式中要使用“end”,而在PL/SQL過程判斷中需要使用“end case”。


-------------------------

比較:

case 運算式

decode 函數

decode可避免多次掃描,提高效能;case為9i以後用法,提供if then else功能

用decode可以違反第3NF行不可再分,列不可再分,列不可重複):列重複


兩個基本差不多,只是在效能上稍微有些差別,以及寫法上的簡潔性。

Oracle在文檔中提到CASE語句的效率會更高一些,尤其是CASE運算式 WHEN 常量 THEN的文法,效率要比CASE WHEN運算式 THEN的文法更高一些。


本文出自 “奔跑的羚羊” 部落格,請務必保留此出處http://heshw.blog.51cto.com/5891747/1293709

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.