There are 2 questions on SO, but they are different and do not solve this problem. Feel free to test it before marking this as duplicate.
There is a SQLFiddle for this question.
In this example, the cell phone number may be NULL
ID | Name | Cell |
---|---|---|
1 | John | 123 |
2 | Sally | NULL |
The query works when the cell number is not null:
DECLARE @Cell NVARCHAR(100) = '123'
SELECT *
FROM Temp
WHERE Cell = CASE WHEN @Cell IS NULL THEN NULL ELSE @Cell END
The same query fails when the cell number is null.
DECLARE @Cell NVARCHAR(100) = NULL
SELECT *
FROM Temp
WHERE Cell = CASE WHEN @Cell IS NULL THEN NULL ELSE @Cell END
The question is how to get the CASE WHEN
working for both NULL and when it is comparing an actual value. Note that this is a simplified example of the real problem (which has a lot more conditions and additional complexity) and the focus is to get the example working by modifying the CASE WHEN
in order to solve the real problem.