2

假设我有一个定义如下的视图:

CREATE VIEW [dbo].[vData_Values] AS
   SELECT ParentId, TimeStamp, Value From Table1
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table2
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table3
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table4

假设我针对我的观点编写了一个查询,如下所示:

   SELECT ParentId, TimeStamp, Value
   FROM vData_Values
   WHERE ParentId IN (...) and TimeStamp BETWEEN '1/1/2013' AND '3/31/2013 23:59'

任何人都会期望针对视图的查询与使用与视图相同的内部查询但在每一步使用相同WHERE子句的存储过程执行的方式不同。例如:

CREATE PROCEDURE [dbo].[GetValues]
(
...
)
AS
BEGIN

   SELECT ParentId, TimeStamp, Value From Table1
   WHERE ParentId IN (...) and TimeStamp BETWEEN '1/1/2013' AND '3/31/2013 23:59'
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table2
   WHERE ParentId IN (...) and TimeStamp BETWEEN '1/1/2013' AND '3/31/2013 23:59'
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table3
   WHERE ParentId IN (...) and TimeStamp BETWEEN '1/1/2013' AND '3/31/2013 23:59'
   UNION ALL
   SELECT ParentId, TimeStamp, Value FROM Table4
   WHERE ParentId IN (...) and TimeStamp BETWEEN '1/1/2013' AND '3/31/2013 23:59'

END

我试图概念化这两者是否/如何以不同的方式处理/优化。通过“分块”单个查询并将谓词单独应用于每个查询是否有任何性能提升?

谢谢。

4

2 回答 2

0

我自己也有这个问题,发现存储过程版本要快得多。我相信(而且我没有做太多调查),但我相信它会首先合并所有记录然后过滤。存储过程过滤每个部分,然后将它们联合起来,因此假设记录较少。

现在我没有尝试的是一个包含重复项的联合(并且可能不检查值。)

所以不幸的是,如果你要处理大量的记录,在你展示的两个样本之间——存储过程会更快。(我说很遗憾,因为您必须预先构建 where 子句。)

尝试查看执行计划,看看它说了什么(我也很好奇。)

于 2013-05-09T12:43:34.080 回答
0

比较执行计划

下面有相同的执行计划

  CREATE VIEW [dbo].[docSVsysInt] AS
  select sID 
  from docSVsys 
  union 
  select sID 
  from docSVint

  select sID 
  from [docSVsysInt] 
  where sID > 100000 and sID <  100010

  select sID 
  from docSVsys 
  where sID > 100000 and sID <  100010
  union 
  select sID 
  from docSVint
  where sID > 100000 and sID <  100010

  select sID 
  from
  (
  select sID 
  from docSVsys 
  union 
  select sID 
  from docSVint
  )  comb
  where sID > 100000 and sID <  100010
于 2013-05-09T14:02:39.637 回答