我有以下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
我可以考虑创建一个表变量,然后根据参数值对它们进行过滤,但是有更好的方法吗?
答案 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 )