千家信息网

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

发表于:2024-09-24 作者:千家信息网编辑
千家信息网最后更新 2024年09月24日,1、NVL函数nvl(expr1,expr2),如果expr1为空,则返回expr2;2、NVL2函数nvl2(expr1,expr2,expr3),如果expr1为空,则返回expr3,否则返回ex
千家信息网最后更新 2024年09月24日Oracle nvl、nvl2、nullif、decode、case函数详解

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函数,后患无穷!

0