CASE语句切换WHERE条件
我希望有一个如下所示的 t-sql 语句...
SELECT [field]
FROM [table]
WHERE CASE @flag
WHEN 1 THEN col1 = @value
ELSE col2 = @different_value
END
重点是我想在我的函数中放置一个标志以在同一查询中使用不同的 where 子句。我就是无法让它发挥作用。这可能吗?
I would love to have a t-sql statement like the following...
SELECT [field]
FROM [table]
WHERE CASE @flag
WHEN 1 THEN col1 = @value
ELSE col2 = @different_value
END
The point being I want to put a flag in my function to use different where clauses in the same query. I just can't get it to work. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这对你有用吗?
Will this work for you?
使用 mySQL,您的语句应该可以工作,因为 mySQL 支持二进制表达式。
所以你必须尝试这个,
这不是很好的可读性。请注意性能问题,因为优化器可能会在这里遇到困难。
With mySQL your statement should work, because mySQL supports binary expressions.
So you have to try this
That isn't pretty good readable. Please be aware of performance issues, because the optimizer may struggle here.
根据给定参数动态改变搜索是一个复杂的主题,并且以一种不同的方式进行,即使只有非常微小的差异,也会产生巨大的性能影响。关键是使用索引,忽略紧凑的代码,忽略担心重复代码,必须制定好的查询执行计划(使用索引)。
阅读本文并考虑所有方法。您的最佳方法将取决于您的参数、数据、模式和实际使用情况:
动态搜索《T-SQL 条件》,作者:Erland Sommarskog
动态 SQL 的诅咒与祝福,作者:Erland Sommarskog< /a>
这将产生最佳执行计划:
但是,如果您必须有一个查询,那么这是使用索引的最佳选择
Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).
Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:
Dynamic Search Conditions in T-SQL by by Erland Sommarskog
The Curse and Blessings of Dynamic SQL by Erland Sommarskog
this will produce the best execution plan:
However, if you have to have a single query, this is your best bet at using an index
您还可以使用布尔逻辑:
You could also use boolean logic:
简单点怎么样?
How about simply;