How to use the case when expressions and decode function properly?

    相信很多小伙伴在开发过程中都有用到case when表达式和decode函数,那么会不会有小伙伴和我一样刚开始有很多疑虑,什么情况下用case when,什么情况下用decode呢?两者有什么区别呢?今天小编就带大家细分一下两者的区别:

    case when表达式不仅可以等值连接还可以范围判断;decode函数可以等值连接。

    这样说大家可能不能理解,举个例子吧,如下;
    创建一张表tmp1,列为dept表示部门信息,分别有10,20,30,40,50部门:
    ![](https://s1.51cto.com/images/blog/201905/29/120a4ff64fb1d8859ddad5488d15d82b.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

    用case when表达式判断,如果部门信息为10,则判断为A,部门信息为20,则判断为B,其他部门信息判断为C:
    select case when dept = 10 then 'A'
                      when  dept = 20 then 'B'
                      else 'C'
    from tmp1;
    或者:
    select case  dept  when  10 then 'A'
                        when  20 then 'B'
                        else 'C'
    from tmp1;
    用decode函数判断,如果部门信息为10,则判断为A,部门信息为20,则判断为B,其他部门信息判断为C:
    select decode(dept,10,'A',20,'B','C') from tmp1;

    而如果想判断部门信息为10或20时,判断为'A',部门信息为30或40时,判断为'B',其他则判断为'C'。这时只能用case when表达式:
    select  case when dept between 10 and 20 then 'A'
                            when dept between 30 and 40 then 'B'
                            else 'C'
                            end 
    from tmp1;

 注:这时sql不能再写为
    select  case dept when between 10 and 20 then 'A'
                            when between 30 and 40 then 'B'
                            else 'C'
                            end 
    from tmp1;
    这时会报错:  ORA-00936:缺失表达式

本篇文章已经结束了,你学会了吗?如若还有疑问,可留言给小编,看到必回复!

Guess you like

Origin blog.51cto.com/12777507/2401978