0

我有一个带有数千行表的数据库的 sql server 2008R2。当我启动服务器时,快速执行此查询:

exec sp_executesql N'SELECT *, [t0].[distance] AS [Meters], @p4 AS [ToWhat]
FROM [dbo].[getEventsByRange](@p0, @p1, @p2, @p3) AS [t0]
LEFT JOIN [dbo].[Event] AS [t1] ON [t0].[idEvent] = [t1].[id]
ORDER BY [t0].[distance]',N'@p0 var

其中 getEventsByRange 是这个函数:

SELECT idEvent, geography::STGeomFromText('POINT(' + @userLongitude + ' ' +       @userLatitude + ')', 4326).STDistance([Coordinates]) as distance
FROM EventCoords
INNER JOIN Event ON EventCoords.idEvent = Event.id
WHERE DAY(start_time)=DAY(@timeMax) AND MONTH(start_time)=MONTH(@timeMax)AND
YEAR(start_time)=YEAR(@timeMax) and 
geography::STGeomFromText('POINT(' + @userLongitude + ' ' + @userLatitude + ')', 4326).STDistance([Coordinates]) < @maxDistance

几分钟后,此查询的执行速度变得非常慢。问题出在哪里?为什么当服务器没有查询缓存时会快速运行?

4

1 回答 1

0

难道是参数嗅探导致了次优缓存执行计划的重用?

要查看是否是这种情况并将 OPTION (RECOMPILE) 放在查询的末尾:

ORDER BY [t0].[distance]
OPTION (RECOMPILE)

如果查询保持高性能(因此问题是参数嗅探),我们可以提出一些更好的建议

于 2012-05-22T23:18:46.237 回答