sql server执行存储过程慢的问题

要实现一个根据时间查询数据生成报表的功能,写了如下存储过程:

CREATE   Procedure   [ dbo ] . [ Report_SearchEnginOnAccount ]
@FromDate   DATETIME ,
@ToDate   DATETIME

AS

SELECT   ''   as  ADGroup
      ,
''   as  Content
      ,
''   as  KeyWord
      ,
sum ( [ ViewAdPV ] as  ViewAdPV
      ,
sum ( [ Listing ] as  Listing
      ,
sum ( [ NB ] as  NB
      ,
sum ( [ NU ] as  NU
      ,
sum ( [ BouncedRate ] as  BouncedRate
      ,
sum ( [ BouncedUV ] as  BouncedUV
      ,
sum ( [ UV ] as  UV
      ,
sum ( [ PV ] as  PV
      ,
[ Date ]
      ,
sum ( [ ClickCount ] as  ClickCount 
      ,
sum ( [ ShowCount ] as  ShowCount
      ,
sum ( [ ClickRate ] as  ClickRate
      ,
sum ( [ TotalPrice ] as  TotalPrice
  
FROM   [ SmallChannelDB ] . [ dbo ] . [ SearchEnginDataReport_View ]
  
WHERE   [ Date ] <=   @ToDate   AND   [ DATE ] >= @FromDate  
  
Group   by   [ date ]
GO

      在使用过程中出现了超时的错误,经查发现是因为存储过程执行时间太长,20万左右的数据一分多钟都没有执行完……我以为是sql语句里面出现的问题,然后直接把@ToDate和@FromDate赋值执行,不到1s就出结果了,后来经公司sql server高手指导,把View换成直接的表连接,然后给两个表的Date列分别加上索引,问题解决,但不知道具体原因是什么。结果第二天又恢复原状了……

     后来在网上搜索资料,发现在sql server中有一个叫“Parameter sniffing”的特性(

http://blog.csdn.net/emili/article/details/2192081),有几个解决办法,一个就是declare一个变量,然后给这个变量赋上参数的值,在存储过程中使用此变量的值就可以了。

 

你可能感兴趣的:(SQL Server)