views:

63

answers:

4

Now I know you can't directly compare NULL to anything (as null is unknown) so how would I achieve the following:

select  *
    from    Material as m
    where   MtrlCode = 826 and
            Exposlimit <> 'compareMe'

Where Exposlimit MAY be NULL or it may not be. 'compareMe' may also be NULL.

Therefore how do I compare the two? Both sides could be either text or NULL.

A: 
select  *
    from    Material as m
    where   (MtrlCode = 826 or MtrlCode IS NULL)  and
            (Exposlimit <> 'compareMe' or Exposlimit IS NULL)
Naeem Sarfraz
+1  A: 

Use IFNULL function for such cases.

i.e.

WHERE IFNULL(FieldA, 'MagicConstant') = IFNULL(FieldB, 'MagicConstant')

Michael Pakhantsov
Does IFNULL exist in T-SQL? Even if you use ISNULL, the optimizer will struggle to use any indexes you may have defined.
Paul Spangle
@Paul, yes sql-server have not function-based indexes, and workaround (http://www.sqlservercentral.com/scripts/T-SQL+Aids/31906/) look very ugly.
Michael Pakhantsov
+2  A: 
select  * 
from    Material as m 
where   MtrlCode = 826 
    and (Exposlimit <> 'compareMe'
         or (Exposlimit is null and compareme is not null) 
         or (Exposlimi is not null and compareme is null))
RedFilter
Works beautifully, thanks very much.
m.edmondson
A: 

Did you try this?

select  *
    from    Material as m
    where   MtrlCode = 826 and
            Exposlimit IS NOT NULL AND 'compareMe' IS NOT NULL AND Exposlimit <> 'compareMe'
Lee Sy En