如果@reasonID = 1,我只需要选择原因ID为211的策略
如果@reasonID = 2,我只需要选择具有reasonID <> 211的策略
如果@reasonID = NULL,我需要选择所有策略,包括NULL
在下面的示例中,它适用于@reasonID = 1和@reasonID = 2。
但是当@reasonID = NULL
时,如何调整WHERE子句以选择所有行?
declare @TempTable table (PolicyNumber varchar(50), reasonID int)
insert into @TempTable values ('Pol1', 5),
('Pol2', NULL),
('Pol3', 211),
('Pol4', 8),
('Pol5', 211),
('Pol6', NULL)
--input @reasonID parameter
declare @reasonID int = 2
select PolicyNumber,reasonID
from @TempTable
where
(case when reasonID = 211 then 1 else 2 end = @reasonID) --works fine
OR (@reasonID = NULL) --does not work
答案 0 :(得分:6)
您使用IS NULL
而不是= NULL
。
您的最后一行应该是:
OR (@reasonID IS NULL)
而且,如果您想进行相反操作,则语法为IS NOT NULL
。