问题
I have this sql:
select * from employees
where
lastname like '%smith%' and firstname like '%bob%' and middle like '%%'
The problem is the values of the name, particularly the middle name, can be null. So the statement above will find:
smith, bob mike
but will not find
smith, bob
because Bob's middle name is null (he has no middle name.)
I have this which works but I thought there was a better way and wanted input:
select * from employees
where
lastname like '%smith%'
and firstname like '%bob%'
and (middle like '%%' or middle is null)
edit:
middle is not always blank. Sometimes it will have a value so I have to keep the test for middle name in. It could be populated or null.
Thanks. I am using Oracle 11g if that matters.
回答1:
You can use nvl:
select * from employees
where
lastname like '%smith%' and firstname like '%bob%' and nvl(middle,'') like '%%'
But this is just the same as not checking the middle name at all as like '%%' will match anything other than null.
回答2:
But
middle like '%%' or middle is null
is always true: either middle is null, in which case middle is null is true, or it contains one or more characters, in which case middle like '%%' is true. So you can just write:
select * from employees
where
lastname like '%smith%' and firstname like '%bob%'
回答3:
Maybe you can just drop the "middle" constraint from the query?
It seems like you don not really mind what it's value will be, so why not just:
select * from employees
where
lastname like '%smith%' and firstname like '%bob%'
来源:https://stackoverflow.com/questions/8535916/how-can-i-test-for-null-and-not-null-at-the-same-time-in-sql