如何使此语句更快:“paramDate Between startDate and NULL”?
当 endDate 为 null 时,此查询需要很长时间(我认为它是 about case 语句,在 case 语句之前它很快),
SELECT *
FROM HastaKurumlari
WHERE CONVERT(SMALLDATETIME,'21-05-2009',103)
BETWEEN startDate
AND (CASE WHEN endDate IS NULL THEN GETDATE() ELSE endDate END)
当 endDate 为 null 时,我应该使用什么来使其更快?
This query is taking long time when endDate is null (i think that its about case statement, before case statement it was fast)
SELECT *
FROM HastaKurumlari
WHERE CONVERT(SMALLDATETIME,'21-05-2009',103)
BETWEEN startDate
AND (CASE WHEN endDate IS NULL THEN GETDATE() ELSE endDate END)
What should i use, when endDate is null to make it faster ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是没有 CONVERT 或 CASE 的查询:
为了确保 Sql Server 不会对每一行计算 getdate() ,您可以缓存它,尽管我很确定 Sql Server 默认情况下足够智能:
发布查询计划可以帮助解释为什么查询慢:
Here's the query without CONVERT or CASE:
To make sure Sql Server doens't evaluate getdate() for every row, you could cache it, although I'm pretty sure Sql Server is smart enough by default:
Posting the query plan could help explain why the query is slow:
如果性能至关重要,那么也许不要使用
null
作为开放结束日期 - 使用支持的最大日期时间(可能有很多 9)。我也会单独进行转换:
上面的内容和你原来的内容仍然有些不同; 如果您可以解释
GETDATE()
检查的意图,我也许可以稍微整理(阅读:修复)它。If it is performance critical, then perhaps just don't use
null
for the open end-date - use the maximum supported datetime instead (probably lots of 9s).I'd also do the conversion separately:
There is still something a bit different in the above and your original; if you can explain the intent of the
GETDATE()
check I might be able to tidy (read:fix) it a bit.作为起点,分解 GETDATE() 以便仅调用一次,您应该会看到速度的提高。
按照您编写的方式,您要求每次 enddate 为空时评估 GETDATE() 。
由于 GETDATE() 是非确定性函数查询无法优化并且往往性能不佳。
As a starting point, factor out GETDATE() so that its called just once, and you should see an improvement in speed.
The way you've written it you are asking for GETDATE() to be evaluated every time enddate is null.
Since GETDATE() is a non-deterministic function the query cannot be optimised and will tend to under perform.
您可以尝试 coalesce 函数:
唯一确定的方法是尝试任何替代方案并查看为每个查询生成的执行计划。
You could try the coalesce function:
The only way to be certain is to try any alternatives and view the execution plan generated for each query.