低效的查询计划SQL Server 2008 R2



大家好,

我们的数据库遇到了持续的问题,我们的内部DBA无法解释。

使用以下查询示例:

Select Distinct
   Date,
   AccountNumber,
   Region,
   Discount,
   ActiveBalance
Into 
   #sometemptable
From 
   anothertable With (Index(ondate)) --use this or the query takes much longer
Where 
   Date >='7/1/2013'
   And ActiveBalance > 0
   And Discount <> '0' and discount is not null

这个查询通常会运行一个多小时,最后我需要杀死它。

但是,如果我像下面这样运行查询:

Select Distinct
   Date,
   AccountNumber,
   Region,
   Discount,
   ActiveBalance
Into 
   #sometemptable
From 
   anothertable With (Index(ondate)) --use this or the query takes much longer
Where 
   Date Between '7/1/2013' and '12/1/2013'  --all of the dates are the first of the month
   And ActiveBalance > 0
   And Discount <> '0' and discount is not null

后接

Insert into #sometemptable
   Select Distinct
      Date,
      AccountNumber,
      Region,
      Discount,
      ActiveBalance
   From 
      anothertable With (Index(ondate)) --use this or the query takes much longer
   Where 
      Date Between '1/1/2014' and '6/1/2014'  --all of the dates are the first of the month
      And ActiveBalance > 0
      And Discount <> '0' and discount is not null

我可以在不到10分钟的时间内运行查询。我正在访问的特定表格每月更新一次。每月和每周都会对这些表进行统计更新。正如前面提到的,我们的DBA不理解为什么最重要的查询比较小查询的组合花费的时间要长得多。

任何想法?任何建议将非常感激!

谢谢,罗恩

这只是一个猜测,但是当你执行Date >= '7/1/2013'时,sql将分析它将大约返回多少行,如果行数大于某个内部阈值,它将执行扫描而不是查找,认为有足够的数据需要返回,扫描将更快。

当你执行between子句时,sql server将执行查找,因为它知道它不需要返回该表所包含的大多数行。

我假设当您执行>=搜索时,它正在进行表扫描。一旦你发布了执行计划,我们就会看到了。

最新更新