[英]SQL Using Case in Where clause for null values
I have a SQL query that I am trying to incorporate the possibility of null responses in my selections. 我有一个SQL查询,试图将空响应的可能性纳入选择中。
Ultimately, this will end up in a SSRS report. 最终,这将最终成为SSRS报告。
This query works fine, but any null values in p.ReferralReason will always be returned. 该查询工作正常,但始终会返回p.ReferralReason中的任何空值。 I would like the nulls to not be returned if the value of @Reason is anything but '%': 如果@Reason的值不是'%',我希望不返回null:
DECLARE @Reason varchar(100)
SET @Reason = 'Lost To Care'
SELECT p.Person_ID, P.Person_Name, p.ReferralReason
FROM VIEW_Patient p
WHERE
p.ReferralReason like '%' + @Reason + '%'
I would like to incorporate all reasons with the @Reason = '%'
If @Reason is set to '%', I would like to include the null values, but I do not want to include the null values if @Reason is set to anything else. 我想将所有原因都与@Reason = '%'
合并如果将@Reason设置为'%',我想包含空值,但是如果@Reason设置为,我不想包含空值还要别的吗。
This is what I have tried, but it does not work: 这是我尝试过的方法,但是不起作用:
DECLARE @Reason varchar(100)
SET @Reason = '%'
SELECT p.Person_ID, P.Person_Name, p.ReferralReason
FROM VIEW_Patient p
WHERE
case
when @Reason = '%' then (p.ReferralReason like '%' + @Reason + '%' or p.ReferralReason is null)
else p.ReferralReason like '%' + @Reason + '%'
end
MS SQL Server 2008 R2. MS SQL Server 2008 R2。
If the NULL
values are replaced with empty strings they will match patterns consisting entirely of %
but not other strings surrounded with %
如果NULL
值与空字符串代替他们将匹配完全由图案%
与包围而不是其他字符串%
SELECT p.Person_ID,
P.Person_Name,
p.ReferralReason
FROM VIEW_Patient p
WHERE ISNULL(p.ReferralReason, '') LIKE '%' + @Reason + '%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.