date inequality in sql

I have the following situation:

declare @b datetime 
declare @d datetime 
set @b='2014-01-31 00:00:00.000'
set @d='2014-01-31 00:00:00.000'--NULL

IF @b <> @d
    PRINT 'N'
ELSE
    PRINT 'Y'

The above code behaves fine when @b and @d are valid values. But it fails to compare when either of them is null. What then is the recommended way,since I have null to be a possible/acceptable case in an inequality check too?

I am using MSSQL2008

Answers


You can use

IF EXISTS(SELECT @b EXCEPT SELECT @d)
    PRINT 'N'
ELSE
    PRINT 'Y'

null is not a value in SQL - it is the lack of a value. Hence, when you compare it with any real value, the retsult is unkown, which does not evaluate to true.

If you want to handle nulls, you should do so explicitly. E.g.:

IF (@B IS NULL AND @d IS NOT NULL) OR (@B IS NOT NULL AND @d IS NULL) OR (@b <> @d))
    PRINT 'N'
ELSE
    PRINT 'Y'

You could change the settings to fit your requirements:

SET ANSI_NULLS OFF
declare @b datetime 
declare @d datetime 
set @b='2014-01-31 00:00:00.000'
set @d='2014-01-31 00:00:00.000'--NULL

IF @b <> @d
    PRINT 'N'
ELSE
    PRINT 'Y'

Need Your Help

treemap for no hierarchical data

r data-visualization treemap

I am new in R. I have a scenario, may be you can give me some hints.

Styling bootstrap rows & columns html

html css twitter-bootstrap web

I'm trying to style this html file so that I have a panel on the side (Members), and pictures on the right of that, lined up in rows of three. My questions are: