加快包含转换的查询

时间:2014-09-01 14:01:56

标签: sql sql-server

有人知道如何加快以下查询:

select count (*)

from table

where column1 between DATEADD(day, -90,  convert(date, getdate())) AND getdate() 

and column2 is not null

此查询需要20秒。为8.000行

我认为/知道瓶颈是转换,但这是必要的......

3 个答案:

答案 0 :(得分:2)

您的查询没问题。转换是在常量上,而不是在列上。相反,你需要一个索引。这可能会有所帮助:

create index idx_table_column1_column2 on table(column1, column2);

这是覆盖索引,因此只使用索引来满足查询。

答案 1 :(得分:1)

这不太可能成为指数问题。

sqlserver-2008中有bug。它应该在较新版本的sqlserver

中修复

请改为尝试:

declare @from datetime = DATEADD(day, -90,  convert(date, getdate()))
declare @to datetime = getdate() 

select count (*)
from table
where column1 between @from and @to 
and column2 is not null

您可以阅读类似的问题here

答案 2 :(得分:0)

确保column1和WHERE子句条件数据类型是否兼容。 还可以在必要时尝试在列上创建索引,但始终有维护 索引。

感谢。

相关问题