Sp_Recompile – does it work the way you expect?

Last week I was working on an assignment where I need to recompile all stored procedure where ever it is refereeing to a certain table. There are many options to recompile stored procedure. I opted to go with SP_Recompile where I will pass table name as parameter and this is meeting my requirement.

MSDN documentation says SP_Recompile “Causes stored procedures and triggers to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.”

SP:CacheInsert is logged when a sp plan get inserted to plan cache.

SP:Recompile is logged when a sp get recompiled.

Also when you pass table or view name as an argument to sp_recompile, MSDN documenation says “all the stored procedures or triggers that reference the table or view will be recompiled the next time that they are run.”

Now let’s see what it logs when you pass table name as parameter to sp_recompile.

Select event SP:CacheInsert ,SP:Recompile and Start profiler. Then run the below code.

CREATE    Procedure usp_getProductDetails
Select ProductName, ProductLabel
From [dbo].[DimProduct] WHERE ProductName like '%MP3%'

Select ProductCategoryName, ProductCategoryLabel
From [dbo].[DimProductCategory] WHERE ProductCategoryName = '02'

-- Call sp
EXEC usp_getProductDetails -- Running first time so it will log a SP:CacheInsert 

-- mark sp to recompile where ever the table DimProductCategory is referred 
Sp_recompile 'DimProductCategory'

--Will get a message as “Object 'DimProductCategory' was successfully marked for recompilation.”

EXEC usp_getProductDetails


When we call the sp again just after

Sp_recompile 'DimProductCategory'

It is recompiling the stored procedure but if you watch closely it is not recompiling the whole sp rather it only recompiles the statement where the table  is referred in the stored proecdure.


About Sandip Pani

Sandip Pani is a Database/BI developer and speaker and is located in Bangalore, India. He has been working with SQL Server over 11 years. He is MCITP for SQL Server 2008 and specializes in SQL Server for application developers and performance and query tuning. His specialization is into Query Tuning and performance troubleshooting. He is working as Senior Technical Specilist for NextGen Healthcare. He is active in SQL community world. He share and enhance his knowledge of SQL Server by spending time at newsgroups and forums, reading and writing blogs, and attending and speaking at conferences.

View all posts by Sandip Pani →

Leave a Reply

Your email address will not be published.