Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

tsql - SQL Server: Effects of using 'WITH RECOMPILE' in proc definition?

My understanding of the WITH RECOMPILE option with stored procedures is generally limited to using the clause with a single stored proc call as a trailing parameter:

exec sp_mystoredproc 'Parameter1', 2, '1/28/2011' with recompile

What are the effects of including WITH RECOMPILE in the actual proc definition? Does this recompile the proc every time it's executed? Or just the next time the proc is altered?

Example:

CREATE PROCEDURE [dbo].[sp_mystoredproc]
    (@string1           varchar(8000)
    ,@int2              int = 2
    ,@dt_begin          DATETIME
    with recompile
AS
... proc code ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This makes the proc rebuild the plans of all queries every time it's run.

Useful it the values of the proc parameters affect the filter selectivity.

Say, the optimal plan for this query:

SELECT  *
FROM    orders
WHERE   order_date BETWEEN @begin_report AND @from_report

will be a full scan if the date range is large or an index scan if it's small.

Created using WITH RECOMPILE, the proc will build the plan on each execution; without one, it will stick to a single plan (but will save time on recompilation itself).

This hint is usually used in procs processing large volumes of data and doing complex reports, when the overall query time is large and time for rebuilding the plan is negligible compared with the time saved by a better plan.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...