Stored Procedure runs fast after recompile

妖精的绣舞 提交于 2019-12-02 23:01:46
sion_corn

When you first compile a stored procedure, its execution plan gets cached.

If the sproc has parameters whose definitions can significantly change the contained query's execution plan (e.g. index scans vs seeks), the stored procedure's cached plan may not work best for all parameter definitions.

One way to avoid this is to include a RECOMPILE clause with the CREATE PROCEDURE statement.

Example:

CREATE PROCEDURE dbo.mySpro
@myParam
WITH RECOMPILE
AS
BEGIN
 -- INSERT WORKLOAD HERE
END
GO

By doing this, a new plan will be generated each time the procedure is called. If recompile time < time lost by its using the wrong cached plan, this is worth using WITH RECOMPILE. In your case, it will also save you the time/planning required to manually recompile this procedure every time you notice it is executing slowly.

For a stored procedure with that many parameters, it would be wise to add OPTION(OPTIMIZE FOR UNKNOWN) at the end of the query to tell the compiler not to optimize the execution plan for specific parameters.

What SQL Server does the first time it runs a stored procedure is optimize the execution plan(s) for the parameters that were passed to it. This is done in a process that is called Parameter Sniffing.

In general, execution plans are cached by SQL Server so that SQL Server doesn't have to recompile each time for the same query. The next time the procedure is run, SQL Server will re-use the execution plan(s) for the queries in it... However, the execution plan(s) might be totally inefficient if you call the stored procedure with different parameters.

Adding the option I mentioned will tell to the SQL compiler that the execution plan should not be optimized for specific parameters, but rather for any parameter that is passed to the stored procedure. From the documentation:

OPTIMIZE FOR UNKNOWN

Instructs the query optimizer to use statistical data instead of the initial values for all local variables when the query is compiled and optimized, including parameters created with forced parameterization.

The answer by @sion_corn recommends adding WITH RECOMPILE to the stored procedure definition, however this forces a recompile of the whole statement each time the stored procedure is executed. This might incur an unacceptable overhead if the procedure is called very often.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!