0

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)
LCJ
  • 22,196
  • 67
  • 260
  • 418

5 Answers5

5

You could write

SELECT * 
FROM @MyTable M
WHERE M.EmpID = IsNULL(@MyParam,M.EmpID)

Or if you need to use casefor some other reason

WHERE M.EmpID = (CASE WHEN @MyParam IS NULL THEN M.EmpID ELSE @MyParam END)

Case is working properly. Select is not broken. http://pragmatictips.com/26

podiluska
  • 50,950
  • 7
  • 98
  • 104
  • Thanks. Marked as answer. I have a relaetd question http://stackoverflow.com/questions/18229937/rewriting-query-using-case-statement – LCJ Aug 14 '13 at 11:01
0

You should use IS NOT NULL. NEVER compare NULL with anything

NULL=NULL - > false
NULL <> NULL -> false
valex
  • 23,966
  • 7
  • 43
  • 60
0

Why not just use

SELECT * 
FROM @MyTable M
WHERE M.EmpID = ISNULL(@MyParam, M.EmpID)

or if it's performance you seek, checking for @MyParam with an IF statement

IF @MyParam IS NULL THEN
  SELECT * FROM @MyTable
ELSE
  SELECT * FROM @MyTable WHERE EmpID = @MyParam
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
0

I would use coalesce() for this purpose. It is the shorted, ANSI standard method:

SELECT m.* 
FROM @MyTable m
WHERE m.EmpID = coalesce(@MyParam, m.EmpID);

Note that this logic is subtly different from the first method, in the case the m.EmpId is NULL. The equivalent logic would be:

SELECT m.* 
FROM @MyTable m
WHERE m.EmpID = coalesce(@MyParam, m.EmpID) or (m.EmpId is NULL and @MyParam is NULL);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

The syntax is CASE WHEN @MyParam IS NULL THEN M.EmpID ELSE @MyParam END

please see similar answer here:

https://stackoverflow.com/a/3237670/11436

Community
  • 1
  • 1
Philippe Grondier
  • 10,900
  • 3
  • 33
  • 72