【发布时间】:2018-04-20 00:56:49
【问题描述】:
我正在使用 SQL Server 2016 Dev,并且我有一个带有 3 个选项的 WHERE 子句。
我解决了 2,我需要帮助解决第三个问题。请看代码。
我不能使用 CTE 或任何其他代码,因为它是遗留代码的一部分,除了 where 子句中的情况外,不能修改。
要求
When DepartmentID = 99 then all records
When DepartmentID = 97 then only PriorityID 10 records
All other Departments = all records except PriorityID 10
样本数据
Create table Department
(
DepartmentID int null,
PriorityID int null
)
GO
Insert into Department (DepartmentID, PriorityID)
values (1, 2), (2, 2), (3, 10), (4, 3), (5, 4),
(97, 10), (99, 10), (4, 5), (5, 3), (2, 10),
(99, 2), (97, 1), (3, 2), (3, 3), (2, 5)
GO
Select * from Department
到目前为止我的查询
--Declare @intDepartmentID int = 99 OK
--Declare @intDepartmentID int = 97 OK
Declare @intDepartmentID int = 2 -- Need to exclude Record with PriorityID = 10
Declare @intPriorityID int = null
IF @intDepartmentID = 99
Begin
Set @intDepartmentID = null
Set @intPriorityID = null
End
If @intDepartmentID = 97
Begin
Set @intDepartmentID = null
Set @intPriorityID = 10
End
Select DepartmentID,
PriorityID
From Department
Where (DepartmentID = @intDepartmentID or @intDepartmentID is null)
-- I think I need case statement here?
And (PriorityID = @intPriorityID or @intPriorityID is null)
【问题讨论】:
-
您的预期结果是什么?
-
有人给你投了反对票,因为你在代码的注释部分留下了要求。我想我的回答会做你喜欢的,但你还是可以考虑编辑这个问题。
标签: sql sql-server case sql-server-2016