case

case関数は、比較対象フィールドと、when以降の比較値とを比較し、等しい場合その比較値の代替値を返す関数です。いずれの比較値とも等しくない場合は、else以降のデフォルト値を返します。
書式は

case 比較対象フィールド when 比較値1 then 代替値1
                        [when 比較値2 then 代替値2]
                        .....
                        [else デフォルト値]
end
使用方法は

select 
case 3 when 3 then 'three'
       when 4 then 'four'
end as case
from   dual;
というように書きます。すると

    case
--------
   three

というように比較対象フィールドである3とマッチする比較値の代替値であるthreeが返ってきます。
比較対象フィールドがいずれの比較値とも等しくない場合は、以下のようにデフォルト値が返ってきます。

select 
case 5 when 3 then 'three'
       when 4 then 'four'
       else 'none'
end as case
from   dual;

case
----
none

また比較対象フィールドがいずれの比較値とも等しくない場合で、else文を省略している場合はnullが返ってきます。

select 
case 5 when 3 then 'three'
       when 4 then 'four'
end as case
from   dual;

case
----
null


初版2006/07/17 :最終更新2006/07/17
HOME