为什么 SQL 日期范围较短的查询运行缓慢,而日期范围较长的查询运行速度很快?

Why SQL query with short date range runs slow, while a long range runs quickly?

平台:SQL服务器 2008 R2

我有一个相当复杂的 SQL 查询,它查询 (2) 个不同的数据库并根据记录的日期范围收集报告。在超过 3,000,000 行中搜索日期范围(例如 2 个月)几乎是即时的。但是,搜索较短的日期范围(例如 7 天)需要将近两分钟。对于我的生活,我无法理解为什么会这样。下面是查询:

;with cte_assets as ( 
 select a.f_locationid, a.f_locationparent, 0 as [lev], convert(varchar(30), '0_' + convert(varchar(10), f_locationid)) lineage 
 from [db_assets].[dbo].[tb_locations] a where f_locationID = '366' UNION ALL 
 select a.f_locationid 
           ,a.f_locationparent 
           ,c.[lev] + 1 
           ,convert(varchar(30), lineage + '_' + convert(varchar(10), a.f_locationid)) 
    from   cte_assets c 
    join   [db_assets].[dbo].[tb_locations] a 
           on a.f_locationparent = c.f_locationID 
 ),
 cte_a AS 
 ( 
    select f_assetnetbiosname as 'Computer Name' 
    from cte_assets c 
    JOIN [db_assets].[dbo].[tb_assets] ass on ass.f_assetlocation = c.f_locationID 
 ) 
      select apps.f_applicationname, apps.f_applicationID, sum(f_runtime/60) [RunTime] 
 from cte_a c 
 JOIN [db_reports].[dbo].[tb_applicationusage] ss on ss.f_computername = c.[Computer Name] 
 JOIN [db_reports].[dbo].[tb_applications] apps 
 ON ss.f_application = apps.f_applicationID 
 WHERE ss.f_runtime IS NOT NULL AND f_starttime BETWEEN '1/26/2015 10:55:03 AM' AND '2/12/2015 10:55:03 AM'
 group by apps.f_applicationname, ss.f_application, apps.f_applicationID 
 ORDER BY RunTime DESC

最后的 WHERE 子句(倒数第三行)是指定日期范围的地方。 BETWEEN '1/26/2015 10:55:03 AM' AND '2/12/2015 10:55:03 AM' 查询中显示的日期范围可以快速无问题地运行。例如,如果我们将查询更改为 BETWEEN '1/27/2015 10:55:03 AM' AND '2/12/2015 10:55:03 AM'(仅一天后),则需要两分钟多才能变为 运行。我完全不知道为什么短范围会导致查询 运行 变慢。感谢任何帮助。

谢谢, 蜜蜂

抱歉,我应该先用谷歌更彻底地搜索这个问题。我在另一个 Whosebug post 上找到了关于需要更新统计信息的答案:

SQL query takes longer time when date range is smaller?

使用该文章中未链接的 MSDN 文章,但 this one here

Updates query optimization statistics on a table or indexed view. By default, the query optimizer already updates statistics as necessary to improve the query plan; in some cases you can improve query performance by using UPDATE STATISTICS or the stored procedure sp_updatestats to update statistics more frequently than the default updates.

Updating statistics ensures that queries compile with up-to-date statistics. However, updating statistics causes queries to recompile. We recommend not updating statistics too frequently because there is a performance tradeoff between improving query plans and the time it takes to recompile queries. The specific tradeoffs depend on your application. UPDATE STATISTICS can use tempdb to sort the sample of rows for building statistics.

我运行以下:

USE db_reports;
GO
UPDATE STATISTICS tb_applicationusage;
GO

2 秒后更新完成,我的短期近期查询现在 运行 很快。

谢谢, 蜜蜂