SQL Server: stored procedure become very slow, raw SQL query is still very fast

后端 未结 2 1366
刺人心
刺人心 2021-02-14 05:03

We are struggling with a strange problem: a stored procedure become extremely slow when raw SQL is executed fairly fast.

We have

  • SQL Server 2008 R2 Expre
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 06:03

    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.

提交回复
热议问题