【发布时间】: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