创建 T-SQL where 子句以接受 NULL 值

发布于 2024-11-01 23:02:38 字数 259 浏览 1 评论 0原文

现在我正在开发一个需要 3 个输入参数的存储过程。但挑战在于客户不必输入任何这些参数;他们可能会将这 3 个作为空值。我怎样才能将其写入 WHERE 子句中?

伪代码类似于:

WHERE (@p1 = a.p1 or @p1 = '') 
and (@p2 = a.p2 or @p2 = '') 
and (@p2 = a.p2 or @p2 = '')

当选择所有 3 个参数时,上述逻辑有效,否则返回 0 条记录。

Now I am developing a stored proc which takes 3 input parameters. But the challenge is that the customer doesn't have to enter any of these parameters; they may instead have these 3 as nulls. How can I write this into the WHERE clause?

pseudocode is something like:

WHERE (@p1 = a.p1 or @p1 = '') 
and (@p2 = a.p2 or @p2 = '') 
and (@p2 = a.p2 or @p2 = '')

The above logic works when they choose all 3 parameters, but otherwise it returns 0 records.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吾家有女初长成 2024-11-08 23:02:38

看起来您正在检查空白/空字符串(意思是“跳过这个”)。如果变量也可以为 null,则可以使用 ISNULL(x,'') 强制将 null 参数转换为空字符串。

 WHERE (@p1 = a.p1 or ISNULL(@p1,'') = '')
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '') 
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '')

It looks like you're checking for blank/empty string (meaning 'skip this'). If the variable is also nullable, perhaps use an ISNULL(x,'') to force the null argument to be converted to an empty string.

 WHERE (@p1 = a.p1 or ISNULL(@p1,'') = '')
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '') 
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '')
小傻瓜 2024-11-08 23:02:38

试试这个:

  WHERE (@p1 = a.p1 or @p1 = '' OR @p1 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p2 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p3 IS NULL)

Try this:

  WHERE (@p1 = a.p1 or @p1 = '' OR @p1 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p2 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p3 IS NULL)
离旧人 2024-11-08 23:02:38

您应该将查询更改为如下所示:

WHERE (a.p1 = IsNull(NullIf(@p1, ''), a.p1))  
  and (a.p2 = IsNull(NullIf(@p2, ''), a.p2))
  and (a.p3 = IsNull(NullIf(@p3, ''), a.p3))

you should change the query to something like this:

WHERE (a.p1 = IsNull(NullIf(@p1, ''), a.p1))  
  and (a.p2 = IsNull(NullIf(@p2, ''), a.p2))
  and (a.p3 = IsNull(NullIf(@p3, ''), a.p3))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文