How to Have Conditional Where Clause Based on Parameter Value

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?

1

2 Answers

I think you want:

WHERE OrderID = 10248 AND
      (@EmployeeId IS NULL OR EmployeeID = @EmployeeID)
DECLARE @EmployeeID Int

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest