使用SQL Server 2008 R2查询性能问题
我有以下记录:使用SQL Server 2008 R2查询性能问题,sql,sql-server,performance,tsql,sql-server-2008-r2,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.0
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
注意:但是对于一个庞大的数据来说,这是一个巨大的时间
任何建议都会有帮助
谢谢您应该编辑问题并描述您希望查询做什么。查询视图需要多少时间?我看不到您的查询中存在性能问题,因为只有6条记录,查询应该进行得很快。我能想到的唯一可能的原因就是眼前的表演…@zhongxiao37,是的,你说得对!但问题不在于这一小部分记录。但是对于大约50k的巨大记录来说,这将超过10分钟。@zhongxiao37,有没有其他方法来编写同样工作的脚本?Thanks@Meem:编写查询的最明显的替代方法是使用CTE而不是表值变量。
create TABLE #testtable (dt date,st time,et time)
create index index_st_et_dt on #testtable(dt,st,et)