【问题标题】:T-SQL : Where clause using OR Conditions and null checkingT-SQL:使用 OR 条件和空检查的 Where 子句
【发布时间】:2021-09-21 09:16:28
【问题描述】:

我有一个存储过程,我在其中传递了三个邮政编码(或邮政编码的 T-SQL 正则表达式)

@postCode nvarchar(50) null,
@postCode2 nvarchar(50) null,
@postCode3 nvarchar(50) null,

在我的 where 子句中,我需要搜索输入的任何邮政编码,但如果传递的是空值,则忽略该参数。

如果我使用如下所示的 AND,则不会返回任何行,因为它正在查找匹配两个不同邮政编码的记录

WHERE ((@postCode IS NULL OR CompPostCode.CompPostCode LIKE @postCode)
  AND (@postCode2 IS NULL OR CompPostCode.CompPostCode LIKE @postCode2) 
  AND (@postCode3 IS NULL OR CompPostCode.CompPostCode LIKE @postCode3))

如果我使用 OR,那么只要其中一个参数为 null,它将返回表中的任何邮政编码

WHERE ((@postCode IS NULL OR CompPostCode.CompPostCode LIKE  @postCode)
   OR (@postCode2 IS NULL OR CompPostCode.CompPostCode LIKE @postCode2) 
   OR (@postCode3 IS NULL OR CompPostCode.CompPostCode LIKE @postCode3))

我必须考虑所有三个参数都为空

如何在参数为空时忽略条件,但在提供值时仍使用 OR 条件?

【问题讨论】:

  • 添加一些示例数据。您接受匹配或空参数的方法对我来说是正确的。
  • 这些是英国的邮政编码吗?如果是这样varchar(10) 将涵盖所有有效代码

标签: sql-server tsql where-clause


【解决方案1】:

您根本不需要IS NULL 子句:

WHERE (CompPostCode.CompPostCode LIKE @postCode
   OR  CompPostCode.CompPostCode LIKE @postCode2
   OR  CompPostCode.CompPostCode LIKE @postCode3)

不过,事实上,使用表类型参数似乎会更好。然后你可以为邮政编码传递 0+ 个值(尽管传递 0 行会导致没有结果),并且可以做一个简单的EXISTS

WHERE EXISTS (SELECT 1
              FROM @YourTableParameter YTP
              WHERE CPC.CompPostCode LIKE YTP.PostCode)

移动球门柱的答案:

为了满足NULL 参数的所有值,您需要添加一个额外的OR

WHERE (CompPostCode.CompPostCode LIKE @postCode
   OR  CompPostCode.CompPostCode LIKE @postCode2
   OR  CompPostCode.CompPostCode LIKE @postCode3
   OR (@postCode IS NULL AND @postCode2 IS NULL AND @postCode3 IS NULL))

使用表类型参数,您需要添加NOT EXISTS 子句:

WHERE (EXISTS (SELECT 1
               FROM @YourTableParameter YTP
               WHERE CPC.CompPostCode LIKE YTP.PostCode)
   OR  NOT EXISTS (SELECT 1 FROM @YourTableParameter YTP))

既然这两个都是“包罗万象”/“厨房水槽”查询,我还强烈建议您将 RECOMPILE 添加到查询的 OPTION 子句中(如果您没有) '还没有。

【讨论】:

  • 谢谢拉努,但是帖子中没有提到的是所有参数都可能为空(我刚刚更新了问题)如果是这种情况,应该完全忽略邮政编码过滤.我认为以上任何一个都不是原因?
  • 我怎样才能满足帖子中没有的要求,@RichardWatts ..?
  • 我明白,我的错误。我已经更新了帖子
  • 我已经更新了新球门柱@RichardWatts 的答案,但是,将来请确保在发布问题时正确概述要求; 之后移动目标帖子,您收到的答案使所述答案无效,这是非常不受欢迎的;你真的应该发布一个新问题。
猜你喜欢
  • 2011-05-28
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多