How do I handle nulls in NOT IN and NOT LIKE statements in Oracle?

北城余情 提交于 2019-12-22 09:07:13

问题


I have a long piece of PL/SQL which is working well except for one small part of the where clause.

I'm expecting that one row should be returned but, because the fields the where clause checks are null, the row is not being returned despite meeting the criteria.

I read a very good note here :
http://jonathanlewis.wordpress.com/2007/02/25/not-in/

It explains how Nulls affect NOT IN statements and I presume it's the same for NOT LIKE as well.

What I haven't been able to find is the comparable replacement I need. Do I need to somehow switch this into an IN and LIKE or provide something to return the row if NUll?

Here is a simplified version of my code.

SELECT * FROM Temp_Table T
WHERE -- Other where constraints
AND (T.Col_One NOT LIKE 'AString'
     OR T.Col_Two NOT IN ('BString','CString'))

In my situation the row would have nulls in both Col_One and Col_Two.

Any help is greatly appreciated.

Thanks.


回答1:


Try this:

AND (NVL(T.Col_One,'NuLl') NOT LIKE 'AString'
      OR NVL(T.Col_Two,'NuLl') NOT IN ('BString','CString')) 



回答2:


Something like this should work:

T.Col_One IS NULL OR T.Col_One NOT LIKE 'AString'
OR T.Col_Two IS NULL OR T.Col_Two NOT IN ('BString','CString')

Please note that...

T.Col_Two NOT IN ('BString','CString') 

...is equivalent to...

T.Col_Two <> 'BString' AND T.Col_Two <> 'CString'

...which "collapses" to NULL in case T.Col_Two is NULL.




回答3:


By convention NULL is not like or equal to anything - the only valid test would be IS NULL which will return true.




回答4:


Check the NVL function in Oracle documentation in : http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions105.htm



来源:https://stackoverflow.com/questions/11215542/how-do-i-handle-nulls-in-not-in-and-not-like-statements-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!