1

I have following SQL,

DECLARE @EmployeeID Int

SELECT *
  FROM [Northwind].[dbo].[Orders]
  WHERE OrderID = 10248
  AND EmployeeID = @EmployeeID

I want to make sure IF @EmployeeID IS NULL Then do not include AND

Something like,

SELECT *
  FROM [Northwind].[dbo].[Orders]
  WHERE OrderID = 10248
  IF @EmployeeID IS NOT  NULL
  AND EmployeeID = @EmployeeID

I could think of creating a table variable and then filtering them based on parameter value , but is there a better way?

Simsons
  • 12,295
  • 42
  • 153
  • 269

2 Answers2

8

I think you want:

WHERE OrderID = 10248 AND
      (@EmployeeId IS NULL OR EmployeeID = @EmployeeID)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2
DECLARE @EmployeeID Int

SELECT *
  FROM [Northwind].[dbo].[Orders]
  WHERE OrderID = 10248
  AND EmployeeID = ISNULL(@EmployeeID, EmployeeID )
AB_87
  • 1,126
  • 8
  • 18