Oracle nvl、nvl2、nullif、decode、case函数详解

发布时间:2020-07-16 00:24:45 作者:oracle梦想
来源:网络 阅读:1052

1、NVL函数

    nvl(expr1,expr2),如果expr1为空,则返回expr2;


2、NVL2函数

    nvl2(expr1,expr2,expr3),如果expr1为空,则返回expr3,否则返回expr2;


3、NULLIF函数

    nullif(expr1,expr2),如果expr1=expr2,返回空,否则返回expr1,要求两个表达式数据类型一致;


    SQL> insert into t1 values(9);

说明1:NVL和NVL2函数在进行空值判断的时候,都会将函数内的表达式执行一次。


4、DECODE函数:

     是oracle数据库独家提供的函数功能,不是sql标准,

     相当于程序语言中的 if 1=1 then 1 else 1!=1的执行效果;

      DECODE(value, if1, then1, if2,then2, if3,then3, . . . else )

5、CASE函数

            case expr 

                        when comparison_expr1 then return_expr1

            when comparison_expr2 then return_expr2

            when comparison_expr3 then return_expr3

                        ......

                        when comparison_exprN then return_exprN

             end

关于nvl、nvl2、decode函数执行性能比较

    SQL> create table t1 (i int);--创建t1临时表

    SQL> insert into t1 values(9);

    SQL> insert into t1 values(9);--插入3行数据,数据值都是9

    SQL> create or replace function sleep_now return number is

      2  i number;

      3  begin

      4  i :=0;

      5  while8

      6  i<=1000000

      7  loop

      8  i :=i+1;

      9  end loop;

     10  return i;

     11  end;

     12  /                         --创建一个sleep_now函数,目的是为了加长sql执行的时间

    SQL> set timing on;            --设置sqlplus命令执行时间

    SQL> select  nvl(i,sleep_now()) from t1;

     

    NVL(I,SLEEP_NOW())

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

                     9

                     9

                     9

     

    Executed in 0.343 seconds  --判断t1表中的i字段是否为空,为空则执行sleep_now()函数;

    sql执行时间是0.343秒;

    SQL> select  nvl2(i,sleep_now(),1) from t1;

     

    NVL2(I,SLEEP_NOW(),1)

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

                  1000001

                  1000001

                  1000001

     

    Executed in 0.343 seconds  --同样使用nvl2函数进行测试


    --使用decode进行相同测试,执行时间是0.063秒

    SQL> select decode(i,null,sleep_now(),1111) from t1;

     

    DECODE(I,NULL,SLEEP_NOW(),1111

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

                              1111

                              1111

                              1111

     

    Executed in 0.063 seconds

总结:错误的、不恰当的使用nvl函数,后患无穷!

推荐阅读:
  1. Oracle中的一些函数
  2. Oracle专题5之Oracle的单行函数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

oracle 空值判断函数 nullif

上一篇:windows必知命令

下一篇:Zabbix iostat 监控配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》