溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Oracle nvl、nvl2、nullif、decode、case函數(shù)詳解

發(fā)布時(shí)間:2020-07-16 00:24:45 來源:網(wǎng)絡(luò) 閱讀:1067 作者:oracle夢想 欄目:關(guān)系型數(shù)據(jù)庫

1、NVL函數(shù)

    nvl(expr1,expr2),如果expr1為空,則返回expr2;


2、NVL2函數(shù)

    nvl2(expr1,expr2,expr3),如果expr1為空,則返回expr3,否則返回expr2;


3、NULLIF函數(shù)

    nullif(expr1,expr2),如果expr1=expr2,返回空,否則返回expr1,要求兩個(gè)表達(dá)式數(shù)據(jù)類型一致;


    SQL> insert into t1 values(9);

說明1:NVL和NVL2函數(shù)在進(jìn)行空值判斷的時(shí)候,都會(huì)將函數(shù)內(nèi)的表達(dá)式執(zhí)行一次。


4、DECODE函數(shù):

     是oracle數(shù)據(jù)庫獨(dú)家提供的函數(shù)功能,不是sql標(biāo)準(zhǔn),

     相當(dāng)于程序語言中的 if 1=1 then 1 else 1!=1的執(zhí)行效果;

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

5、CASE函數(shù)

            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

關(guān)于nvl、nvl2、decode函數(shù)執(zhí)行性能比較

    SQL> create table t1 (i int);--創(chuàng)建t1臨時(shí)表

    SQL> insert into t1 values(9);

    SQL> insert into t1 values(9);--插入3行數(shù)據(jù),數(shù)據(jù)值都是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  /                         --創(chuàng)建一個(gè)sleep_now函數(shù),目的是為了加長sql執(zhí)行的時(shí)間

    SQL> set timing on;            --設(shè)置sqlplus命令執(zhí)行時(shí)間

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

     

    NVL(I,SLEEP_NOW())

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

                     9

                     9

                     9

     

    Executed in 0.343 seconds  --判斷t1表中的i字段是否為空,為空則執(zhí)行sleep_now()函數(shù);

    sql執(zhí)行時(shí)間是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函數(shù)進(jìn)行測試


    --使用decode進(jìn)行相同測試,執(zhí)行時(shí)間是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

總結(jié):錯(cuò)誤的、不恰當(dāng)?shù)氖褂胣vl函數(shù),后患無窮!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI