Recently, I've been working on a database stored procedure which was having too many SQL statements and that performed some data operation on multiple tables. With the filter values were hardcoded everything was working fine but once I supplied those hardcoded values as parameters instead, the performance of the SP went down drastically. Then I researched why this was happening and did some analysis and found the issue. The following is some information which will help you understanding the issue with a feature of SQL Server Optimizer called Parameter Sniffing and a possible workaround for that. First let me tell you what parameter sniffing is, "SQL Server uses the histogram of statistics objects to estimate the cardinality of a query, and then use this information to try to produce an optimal execution plan. The query optimizer accomplishes this by first inspecting the values of the query parameters. This is called parameter sniffing."
This helps to get an execution plan tailored to the current parameters of the query which naturally improves the performance. These execution plans get cached in the plan cache so that they can be reused the next time the same query needs to be executed. This saves optimization cost (CPU resources) and time as the query doesn't get optimized again.
But sometimes a performance problem can be seen occasionally. Syntactically identical queries can generated different execution plans by Optimizer, depending on the parameters supplied and one of them can cause the performance issue. This is a known problem using explicit parameterization for e.g. StoredProcedures.
As we discussed there can be different execution plans generated for different values of the parameter so if you are aware of the values and want to optimize your query for that specific value you can use the following method known as "Optimizing for a typical parameter":
There is an OPTIMIZE FOR option hint available in SQL Server 2005 which can do this for you.
ALTER PROCEDURE demoSP ( @pid int)
AS
SELECT * FROM Sales.SalesOrderDetail
WHERE ProductID = @pid
OPTION ( OPTIMIZE FOR ( @pid = 192) )
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Gowtham RajamanickamPosted Apr 26, 2016, 3:06 AM
good article
Lajapathy ArunPosted May 9, 2012, 5:29 AM
Thanks Amit :)
Amit ChoudharyPosted May 9, 2012, 4:08 AM
By Enabling forced parameterization you can reduce the frequency of query optimizations, but you may also introduce suboptimal plans for some instances of those queries. I should update the article as well.. I missed this point to mention in article.
Lajapathy ArunPosted May 7, 2012, 11:39 PM
What is the use of "PARAMETERIZATION FORCED"?