T-SQL :使用 OR 条件和空检查的 Where 子句

T-SQL : Where clause using OR Conditions and null checking

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

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

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

如果我像下面那样使用 AND,则不会 return 编辑任何行,因为它正在寻找匹配两个不同 post 代码

的记录
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,那么只要其中一个参数为空,它将 return table

中的任何 post 代码
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 条件?

您根本不需要 IS NULL 子句:

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

不过,事实上,似乎您最好使用 Table 类型参数。然后你可以为邮政编码传递 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))

使用 table 类型参数,您需要添加 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 子句,如果你还没有的话。