检查输入参数如果不是 Null 并在 SQL Server 的 where 中使用它 [英] Checking an input param if not Null and using it in where in SQL Server
问题描述
在 WHERE
子句中包含输入参数但如果它为空则排除它的最佳方法是什么?
What is the best way to include an input param in the WHERE
clause but exclude it if it is null?
我相信的方式有很多,但当时我似乎想不起来了.
There are a number of ways I believe, but I can't seem to remember then.
我也可以使用 COALESCE()
吗?但我认为这仅用于选择值?
Also could I use the COALESCE()
? But I think this is only for SELECTing values?
为了澄清,假设一个名为 @code ="1"
的变量,那么我的位置将是 Where type='B' AND code = @code
但如果 @code is null
那么我只想要 Where type='B'
- 注意缺少的 code = @code
.
To clarify, let's say a variable called @code ="1"
then my where would be Where type='B' AND code = @code
but if @code is null
then I only want Where type='B'
- notice the missing code = @code
.
推荐答案
您可以使用 IsNull
where some_column = IsNull(@yourvariable, 'valueifnull')
编辑:
您在评论中描述的内容可以这样做:
What you described in the comment can be done like:
where (@code is null or code = @code)
这篇关于检查输入参数如果不是 Null 并在 SQL Server 的 where 中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!