创建 T-SQL where 子句以接受 NULL 值
现在我正在开发一个需要 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您正在检查空白/空字符串(意思是“跳过这个”)。如果变量也可以为 null,则可以使用 ISNULL(x,'') 强制将 null 参数转换为空字符串。
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.试试这个:
Try this:
您应该将查询更改为如下所示:
you should change the query to something like this: