Oracle中case用法總結


--case語句的種類:
1.簡單case語句
語法:
   case exp when comexp then returnvalue
            ...
            when comexp then returnvalue
            else returnvalue
    end
      
  case到end之間相當於一個具體的值,可以做運算,取別名,嵌套case 等等。
  只要把case到end當作一個運算結果的表達式就可以了。

舉例:
   select cust_last_name,
          case credit_limit when 100 then 'low'
                            when 5000 then 'high'
                            else 'medium'
          end
     from customers;
     
2.搜索case語句
語法:
    case when boolean then return value
         ...
         when boolean then return value
         else retur nvalue
     end
     
舉例:
select case when id between 1 and 10 then 'low'
            when id between 20 and 30 then 'mid'
            when id between 40 and 50 then 'high'
            else 'unknow'
       end
from product;

--簡單case和搜索case之間的區別:
1. 簡單case只能是when后面的表達式完全匹配case后的表達式,相當於 =,所以也不能匹配null。
2. searched case可以作為比較條件,那么可以使用like、!=between ..and<=is nullis not null等,比簡單case的使用更加廣泛,完全可以替代簡單case。

--注意事項:
1.case 表達式返回的是一個確定的value,若前面的都不匹配,則返回else中的項.
2.簡單case 中的表達式,when 后面的表達式類型應該全部保持一致.
3.所有的then 后面的return_value類型要保持一致.
4.對於簡單case 表達式,也就是case 表達式 when…那么when null 總是取不到。也就是case 后面的表達式如果值為null,不會與when null 匹配,只會與else匹配.
5.對於searched case來說,有自動類型轉換,只要條件成立就可以。
如:select case when 1='1' then 1 end from dual; 其中1='1'條件成立

值得一提的是: sql中的case語句與pl/sql中的case語句的不同之處:
前者的else不是必須的,如果沒有匹配就返回null;后者的else不寫,則報case_not_found異常.

--case中嵌套子查詢
Case語句中可以使用子查詢,但是必須返回一行,不可以是多行.
如:
select case (select count(*) as s1 from t1 where a = 1)
           when (select count(*) as s2 from t1, t2 where t1.a = t2.a and t2.a = 1) then '相等'
           else '不相等'
       end
  from dual;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM