We are struggling with a strange problem: a stored procedure become extremely slow when raw SQL is executed fairly fast.
We have
Try using using the hint OPTIMIZE FOR UNKNOWN
. If it works, this may be better than forcing a recompile every time. The problem is that, the most efficient query plan depends on the actual value of the date paramter being supplied. When compiling the SP, sql server has to make a guess on what actual values will be supplied, and it is likely making the wrong guess here. OPTIMIZE FOR UNKNOWN
is meant for this exact problem.
At the end of your query, add
OPTION (OPTIMIZE FOR (@now UNKNOWN))
http://blogs.msdn.com/b/sqlprogrammability/archive/2008/11/26/optimize-for-unknown-a-little-known-sql-server-2008-feature.aspx
Since you are using sp_executesql
recompiling the procedure, or clearing the cached plan for the procedure won't actually help, the query plan for the query executed via sp_executesql
is cached separately to the stored procedure.
You either need to add the query hint WITH (RECOMPILE)
to the sql executed, or clear the cache for that specific sql before executing it:
DECLARE @PlanHandle VARBINARY(64);
SELECT @PlanHandle = cp.Plan_Handle
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
WHERE st.text LIKE '%' + @SQLString;
DBCC FREEPROCCACHE (@PlanHandle); -- CLEAR THE CACHE FOR THIS QUERY
EXECUTE sp_executesql @SQLString,@ParmDefinition, @MediaID, @Rfa, @LicenseWindow, @OwnerID, @LicenseType, @PriceGroupID, @Format, @GenreID,
@Title, @Actor, @ProductionCountryID, @DontReturnMoviesWithNoLicense,@DontReturnNotReadyMovies, @take, @skip, @now;
This is of course irrelevant if when you executed DBCC FREEPROCCACHE
you didn't pass any parameters and cleared the whole cache.