Sql-server – SQL Server – force NO recompile stored procedure

sql serversql-server-2005stored-procedures

I would like to know if exists some command to force NO RECOMPILE of a stored procedure.
I have a procedure that take about 5 minutes to executed. But when I run directly in the Query windows it takes just few seconds. This sp have a temporary table.

My question is: Is there any way to force a stored procedure to avoid recompilation???

Note: I am using SQL Server 2005.

Best Answer

As was pointed out in the comments, this is almost certainly nothing to do with plan recompilation. If I had to hazard a guess, this is due a bad query plan being caused by parameter sniffing.

Assume that you have an ecommerce website where we can get different sales. We're going to have a lot more addresses in California than I will in Alaska, right? The physical operations that SQL Server is going to perform to read a lot of data (summarized sales in California) is going to be very different than they query to read a little bit of data (summarized sales in Alaska). Sometimes the cached plans are great for only one set of parameters and are horrible for all others. This is often referred to as parameter sniffing.

There's a fantastic article about Parameter Sniffing available on Simple Talk's website. So you can avoid reading that, you don't have too many options apart from specifying OPTION (RECOMPILE) at the statement level, specifying WITH RECOMPILE at the procedure level, or copying the procedure's parameters into local variables and using those to run your parameterized query.