我目前遇到了一个问题。我从一张大桌子中提取4列。这4个表被保存到表变量中。查询工作正常,但运行时间有问题。当我硬编码第一个日期条件时,它运行完美(大约1-2秒)。当我使用变量而不是硬编码日期时,查询大约需要3.5分钟才能运行。
我正在使用此查询运行MS SQL Server 2003.
有人知道造成运行时间差异的原因吗?
INSERT INTO @TableVariable
SELECT Coulmn1, Column2, Column3, Column4
FROM DatabaseTable
/*This line works almost instantaneously)*/
WHERE (DateTime > CONVERT(DATETIME, '2014-06-23 00:00:00', 102)) AND (DateTime <= @WeekEndTime)
/*If I use this one, it executes in around 3.5 min and I get the same results*/
WHERE (DateTime > @WeekStartTime) AND (DateTime < @WeekEndTime)
/*The same slow run time is seen with these lines*/
Declare @testTime varchar(20)
Set @testTime = '2014-06-23 00:00:00'
WHERE (DateTime > CONVERT(DATETIME, @testTime , 102)) AND (DateTime <= @WeekEndTime)
/*This line is always used*/
GROUP BY column 1
答案 0 :(得分:0)
使用变量与硬编码值时,SQL Server可以创建不同的执行计划。如果你在运行每个查询后查看实际的执行计划,你会看到差异。
答案 1 :(得分:0)
您的变量@WeekStartTime是数据类型DATETIME还是String?我有类似的情况,当我将变量更改为DATETIME的数据类型时,事情变得更好了。我注意到你也在尝试varchar。 。 。给DATETIME一个机会。