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?
The reason your
casedoesn’t work is thatnullis not equal tonull. The expressionnull = nullevaluates tounknown. For example:You could make it work like
case when x is null. Note the use ofisas opposed to=:For more details, see the Wikipedia article on three valued logic.
A simpler way is to omit the case altogether: