標籤:oracle 空值判斷函數
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函數,後患無窮!
Oracle nvl、nvl2、nullif、decode、case函數詳解