在列可能为空的存储过程中使用参数
我想要(松散地)有一个存储过程,例如
select * from table where col1 像 @var
@var 的默认值是 '%',所以如果我没有 @var 的值,它应该返回每一行。但是,问题是它不返回 col1 为空的行。
如果 @var = '%' 则如何返回所有行,如果 @var 确实有值,如何返回类似 @var 的行?
[实际的 sp 明显更复杂,所以我不想将其包装在 if..then 中并有两个选择]
I want to (loosely) have a stored procedure like
select * from table where col1 like @var
the default value of @var is '%', so if I don't have a value for @var it should return every row. However, the problem is it doesn't return rows where col1 is null.
How do I return all rows if @var = '%' and rows that are like @var if it does have a value?
[the actual sp is significantly more complex so I don't want to just wrap it in a if..then and have two selects]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该做到这一点。
Should do the trick.
只是一个提醒比什么都重要。如果要频繁使用此 SP 并且您选择的数据很大,请确保对查询进行性能测试(使用上述任一解决方案)。根据过去的经验,同时使用 LIKE 和 ISNULL 或 IS NULL 会对性能产生很大影响
Just a heads up more than anything. If this SP is to be used frequently and the data you are selecting from is large make sure you performance test your query (using either of the solutions above). From past experience using LIKE and ISNULL or IS NULL together can have a big performance hit
当
@var
为 '%' 时,您可以使用特殊情况来包含所有空值,如下所示:You could special case when
@var
is '%' to include all the null values like this: