如何根据参数值设置条件where子句

时间:2017-10-04 00:40:30

标签: sql sql-server sql-server-2008

我有以下SQL,

DECLARE @EmployeeID Int

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

我想确保IF @EmployeeID IS NULL然后不要包含AND

类似的东西,

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

我可以考虑创建一个表变量,然后根据参数值对它们进行过滤,但是有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

我想你想要:

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

答案 1 :(得分:1)

DECLARE @EmployeeID Int

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