We are struggling with a strange problem: a stored procedure become extremely slow when raw SQL is executed fairly fast.
We have
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.