Why you should be using stored procedures with recompile option

Stored Procedures (SPs) with RECOMPILE option

What is the RECOMPILE option?

The compilation is the process when a query execution plan of a stored procedure is optimized based on the current database objects state. This query execution plan is often stored in the cache to be quickly accessed.
By the way, this check is a part of our SQL Server Health Check service.
Recompilation is the same process as a compilation, just executed again.

Why should you care about it?

When you use the WITH RECOMPILE option, the store procedure gets a new execution plan every time it runs. That means SQL Server will execute the same action multiple times, degrading performance (high CPU usage).

How can you list all stored procedures with recompile option?

You can use the following script to list them from all databases:
EXECUTE master.sys.sp_MSforeachdb
'USE [?];
SELECT DISTINCT Database_Name = DB_Name(),
SP_Name = SO.name,
ISR.SPECIFIC_SCHEMA As Schema_Name
FROM sys.sql_modules AS SM
LEFT OUTER JOIN master.sys.databases AS sDB ON SM.object_id = DB_id()
LEFT OUTER JOIN dbo.sysobjects AS SO ON SM.object_id = SO.id and type = ''P''
LEFT OUTER JOIN INFORMATION_SCHEMA.ROUTINES AS ISR 
on ISR.Routine_Name = SO.name AND ISR.SPECIFIC_CATALOG = DB_Name()
WHERE SM.is_recompiled=1 OPTION (RECOMPILE);';
Figure 1 – Query output.

How to fix them?

1. When the store procedure does not run often, this can probably be ignored. 2. If SP often runs, investigate further, recompilation is not necessarily the best solution.

More information

Microsoft – Recompile a Stored Procedure. Frequent query recompilations – a SQL query performance killer – introduction, Milena Petrovic – SQLShack.
Picture of Mark Varnas

Mark Varnas

Hey I'm Mark, one of the guys behind Red9. I make a living performance tuning SQL Servers and making them more stable. I channel my SQL into our SQL Managed Services, SQL Consulting and our internal database products.

Leave a Reply

Your email address will not be published. Required fields are marked *