我有一个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
几分钟后,此查询的执行速度变得非常慢。问题出在哪儿?为什么当服务器没有缓存查询时快速?
答案 0 :(得分:0)
参数嗅探是否会导致重复使用次优的缓存执行计划?
要查看是否是这种情况,请在查询结尾处选择OPTION(RECOMPILE):
ORDER BY [t0].[distance]
OPTION (RECOMPILE)
如果查询保持高效(因此问题是参数嗅探),我们可以提出更好的建议