SQLWhere问题
我有一个关于 case 语句和 where 子句中的空值的问题。
我想做以下事情:
Declare @someVar int = null
select column1 as a from
TestTable t
where column1 = case when @someVar is not null then @someVar else column1 end
问题是:
假设@someVar 为空。我们还假设 TestTable t 中的 column1 具有 NULL 列值。然后,我的 case 语句中的条件 t = t 将始终评估为 false。
我基本上只是希望能够根据 @someVar 的值(如果提供)有条件地过滤列。有什么帮助吗?
I have a question about case statements and nulls in a where clause.
I want to do the following:
Declare @someVar int = null
select column1 as a from
TestTable t
where column1 = case when @someVar is not null then @someVar else column1 end
Here is the problem:
Let's say @someVar is null. Let's also say that column1 from TestTable t has NULL column values. Then, my condition t = t in the case statement will always evaluate to false.
I basically just want to be able to conditionally filter the column based on the value of @someVar if it's provided. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@someVar IS NULL
总是返回该行。@someVar IS NOT NULL
且column1 = @someVar
返回该行。因此,请尝试以下操作:
要测试此表达式是否有效,请尝试将一些测试值插入表中,然后获取
b
为 NULL 或a
等于的所有行b
:结果:
@someVar IS NULL
always return the row.@someVar IS NOT NULL
andcolumn1 = @someVar
return the row.So try this:
To test that this expression works try inserting some test values into a table and then fetch all the rows where
b
is NULL ora
is equal tob
:Result:
虽然条件过滤是主流模式,但我敦促您重新考虑您的意图。将多个查询压缩为单一形状的次数越多,对优化器确定查询功能的能力的干扰就越大,生成的查询执行计划就越有可能较差。
在这种情况下,优化器在不检查@somevar的情况下无法判断column1是否是过滤器。那么是否应该使用column1上的索引呢?
While conditional filtering is a mainstream pattern, I urge you to reconsider your intent. The more you compress multiple queries into a single shape, the more you interfere with the ability of the optimizer to figure out what your query does, and the more likely the resulting query execution plan will be poor.
In this case, the optimizer can't tell whether column1 is a filter or not without inspecting @somevar. So should an index on column1 be used or not?
也许研究 COALESCE 会对您有所帮助。
Maybe looking into COALESCE will help you.