I have following two queries. The first query is straight forward and is working as epecte when @MyParam is null. But the second query is not returning the same result. What is the mistake in the second query.
Note: I have been asked to use the second approach since the client asked to get rid of “@MyParam IS NULL” check (used in query 1)
QUERY
DECLARE @MyParam INT
DECLARE @MyTable TABLE (EmpID INT)
INSERT INTO @MyTable VALUES (1)
INSERT INTO @MyTable VALUES (2)
INSERT INTO @MyTable VALUES (3)
INSERT INTO @MyTable VALUES (4)
--Query 1
SELECT *
FROM @MyTable M
WHERE M.EmpID = @MyParam OR @MyParam IS NULL
-- Query 2 (Rewrite for performance)
SELECT *
FROM @MyTable M
WHERE M.EmpID = (CASE @MyParam WHEN NULL THEN M.EmpID ELSE @MyParam END)