I have a sql server 2008R2 with a database that have table with thousands of rows. When i start the server execute fast this query:
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
where getEventsByRange is this function:
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
After some minutes this query become very slow to execute. Where is the problem? Why when the server haven’t query cached go fast?
Could it be that Parameter Sniffing is causing the reuse of a suboptimal cached execution plan ?
To see if this is the case and OPTION (RECOMPILE) to the end of your query:
If the queries stay performant (and thus the problem is parameter sniffing) we can make some better recommendations