0

Is there a more elegant way to solve the problem of comparing dates in sql server where dates might be null? I don´t care about time.

DECLARE @validFrom DATE
DECLARE @validTo DATE
SET @validFrom = GETDATE()
SET @validTo = NULL
IF ((@validFrom is null AND @validTo IS NOT NULL) OR (@validTo is null AND @validFrom IS NOT NULL) OR DATEDIFF(day, @validFrom, @validTo) <> 0)
    PRINT 'not same'
ELSE
    PRINT 'same'
2
  • if both are NULL, what do you want ? Commented Feb 26, 2021 at 7:47
  • Then I whant same Commented Feb 26, 2021 at 7:58

3 Answers 3

2

You don't need to use DATEDIFF(DAY, ...) , you can compare the date directly since you have declared with DATE data type.

IF  @validFrom = @validTo
OR  (    -- when both are `NULL` consider same
        @validFrom  IS NULL 
    AND @validTo    IS NULL
    )
    PRINT 'same'
ELSE
    PRINT 'not same'
Sign up to request clarification or add additional context in comments.

Comments

0

RE: a more elegant way to solve the problem of comparing dates in sql server where dates might be null?

Use ISNULL.

CODE:

SELECT CASE 
    WHEN ISNULL(@validFrom, '1900-01-01') = ISNULL(@validTo, '1900-01-01') 
    THEN 'same' 
    ELSE 'not same' END

2 Comments

This will fail if one is null and other is 1900-01-01 ;) Unlikely but could happen
Thank you for the comment. You are correct, I made the assumption that dates were business dates. Overwhelmingly, businesses do not have dates from 120 years ago. If you have a different range, one solution is to change default date to a date outside the range. The above is the most common way of handling NULLs in comparisons of any data type. It is easy to read and easy to type. BTW, the solution also does not address the business rule if both dates are NULL. I view programming as engineering, not math. There are no perfect answers. But there are many good ones.
0

You can check for nullability and then go for comparison.

DECLARE @validFrom DATE
DECLARE @validTo DATE
SET @validFrom = GETDATE()
SET @validTo = NULL

IF ISNULL(@validFrom,'19000101') = ISNULL(@validTo,'19000101')
BEGIN
    PRINT 'same'
END
ELSE
BEGIN
    PRINT 'not same'
END

2 Comments

Thanks, but really not any more elegant and if both are null it should be same...
@KjartanValurÞórðarson, got it. updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.