Oracle nvl、nvl2、nullif、decode、case函數詳解

來源:互聯網
上載者:User

標籤: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函數詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.