1. 程式人生 > >Oracle坑之-空字串與NULL

Oracle坑之-空字串與NULL

空字串與NULL

首先有如下程式碼

SELECT *
  FROM Pdc_DataDomain DD
INNER JOIN Pdc_DD_Table DDT
    ON DD.DataDomainID = DDT.DataDomainID
   AND DD.ApplicationDBID = '3e7c6764d73f4c7786c99e5b72eb6912'
   AND DDT.TableName <> '#'
   AND NOT EXISTS
(SELECT *
          FROM pdc_Application_3e7c6764 A
         WHERE A.TableName = DDT.TableName
           AND A.FieldName = DDT.FieldName
           AND A.FieldType = DDT.FieldType
           AND nvl(A.FieldLength, '') = nvl(DDT.FieldLength, '')
           AND nvl(A.FieldScale, '') = nvl(DDT.FieldScale, ''))

核心重點在這句AND nvl(A.FieldScale, '') = nvl(DDT.FieldScale, '')上,這句當A的FieldScale和DDT的FieldScale都為空的時候,會出現兩者nvl後都返回'',但是Oracle的特性是''會被處理為null,而null不等於任何值,包括自己,,那麼就over了,如果出現上面這種應該如何處理呢,很簡單,轉化的時候可以將其轉化為一個程式中不會出現的值即可,如果程式邏輯沒有不會出現的值,就只有使用isnull來判斷了.

以下是參考資料:

-- oracle 將 空字串即''當成null,測試指令碼如下:

select nvl(null,-1) from dual;
sele'','-1') from dual;
select nvl(nvl(null,''),-1) from dual;
select nvl(trim('  '),'-1') from dual;ct nvl(

-- 但是要記住,null 與任何值做邏輯運算得結果都為 false,包括和null本身:

select nvl(max('1'),-1) from dual where null = '';
select nvl(max('1'),-1) from dual where null <> '';
select nvl(max('1'),-1) from dual where null = '-1';
select nvl(max('1'),-1) from dual where null <> '-1';
select nvl(max('1'),-1) from dual where null = null;
select nvl(max('1'),-1) from dual where null <> null;

-- 不過,用 is null 判斷時,空字串和 null 都 is null:

select nvl(max('1'),-1) from dual where '' is null;
select nvl(max('1'),-1) from dual where null is null;

-- 還要記住,null 和任何數值進行數學運算,結果都為 null:

select nvl(null + 0,-1) from dual;

-- 不過,可以使用 || 將空字串或 null 和字串連線

select 'a' || null || 'b' from dual;

-- 另,作為以下的 Oracle 內建的函式的引數時,結果也為 null:

select nvl(length(null),-1) from dual;
select nvl(trim(null),-1) from dual;
select nvl(ltrim(null),'-1') from dual;
select nvl(rtrim(null),'-1') from dual;
select nvl(rtrim(null,' '),'-1') from dual;
select nvl(soundex(null),'-1') from dual;
select nvl(SubStr(null,1),-1) from dual;
select nvl(InStr(null,1),-1) from dual;
select nvl(replace(null,'a','b'),'-1') from dual;

select nvl(min(null),'-1') from dual;
select nvl(max(null),'-1') from dual;
select nvl(sum(null),'-1') from dual;
select nvl(avg(null),'-1') from dual;
select nvl(sum(null),'-1') from dual;

-- 不過,作為以下的 Oracle 內建的函式的引數時,結果不為null:

select concat('a', null) from dual;
select concat(null, 'a') from dual;

select count(null) from dual;

-- 其他函式用的時候,也可以使用以上的方法測試