使用SQL Server 2008 R2查询性能问题

时间:2014-09-05 03:42:17

标签: sql sql-server performance tsql sql-server-2008-r2

我在视图中有以下记录:

 coldate                coltime           colseconds
------------------------------------------------------
 2014-08-02     1900-01-01 10:00:00.000      50
 2014-08-02     1900-01-01 11:08:08.000      120
 2014-08-02     1900-01-01 11:08:55.000      160
 2014-08-03     1900-01-01 09:00:15.000      180
 2014-08-04     1900-01-01 11:00:10.000      600
 2014-08-04     1900-01-01 11:05:50.000      320

预期结果是:

 coldate                coltime           colseconds
------------------------------------------------------
 2014-08-02     1900-01-01 11:08:08.000      120
 2014-08-02     1900-01-01 11:08:55.000      160
 2014-08-04     1900-01-01 11:00:10.000      600
 2014-08-04     1900-01-01 11:05:50.000      320

我正在使用以下脚本:

 declare @testtable table(dt date,st time,et time)

 insert into @testtable select coldate,coltime,DATEADD(ss,colseconds,coltime) from testt

 select distinct coldate,
            coltime,colseconds from (
 SELECT x.* FROM
 (
    select distinct coldate,
            coltime,colseconds from testt as x  /* testt is the view*/
            inner join  
            @testtable  as t on
            CAST(x.coltime as time) > t.st and CAST(x.coltime as time) < t.et 
  )x 
  UNION all

  SELECT  testt.coldate,
            testt.coltime,testt.colseconds FROM
  (
          select distinct coldate,
            coltime,colseconds,t.st  from testt as x 
            inner join  
            @testtable  as t on
            CAST(x.coltime as time) > t.st and CAST(x.coltime as time) < t.et 
  )y
 INNER JOIN  testt ON y.st = CAST(testt.coltime as time) 
 )z

是的,我尝试使用temp table索引,testt是视图名称,但仍然花费大量时间:

 create TABLE #testtable (dt date,st time,et time)

 create index index_st_et_dt on #testtable(dt,st,et)

注意:但是需要花费大量时间来处理大量数据。

任何建议都会有所帮助。

由于

0 个答案:

没有答案