JustMe
JustMe

Reputation: 732

Using CASE with DATE Type in WHERE clause

I want to use CASE with DATE Type in WHERE clause, so when @birthFrom or @birthTo is NULL return all record.

DECLARE @birthFrom DATE= NULL --'19941012'
DECLARE @birthTo DATE= NULL --'20101012'

SELECT  *
FROM    dbo.bbmf
WHERE   birth BETWEEN ( CASE @birthFrom
                      WHEN NULL THEN birth
                      ELSE @birthFrom
                    END )
          AND     ( CASE @birthTo
                      WHEN NULL THEN birth
                      ELSE @birthTo
                    END )

My problem is: when I execute the above code there is no record selected

Any suggestion?

Upvotes: 0

Views: 3314

Answers (2)

Andomar
Andomar

Reputation: 238086

The reason your case doesn't work is that null is not equal to null. The expression null = null evaluates to unknown. For example:

select case null when null then 1 else 2 end
-->
2

You could make it work like case when x is null. Note the use of is as opposed to =:

declare @x int = null
select case when @x is null then 1 else 2 end
-->
1

For more details, see the Wikipedia article on three valued logic.

A simpler way is to omit the case altogether:

where   (@birthFrom is null or @birthFrom <= birth)
        and (@birthTo is null or birth <= @birthTo)

Upvotes: 2

Himanshu
Himanshu

Reputation: 32602

You have one mistake in CASE statement, you have added @birthFrom instead of @birthTo

WHERE   birth BETWEEN ( CASE @birthFrom
                      WHEN NULL THEN birth
                      ELSE @birthFrom
                    END )
          AND     ( CASE @birthFrom <----it should be @birthTo
-------------------------^^^^^^^^^^
                      WHEN NULL THEN birth
                      ELSE @birthTo
                    END )

Upvotes: 0

Related Questions