I came across parameter sniffing when one of my queries took a much longer time to execute than expected. When I delved a little deeper into this problem I came to know that:
When first time query gets executed it (SQL Server) creates execution plan for that query and for other n number of times same query executed and if it has large variance in result set with first time execution then parameter sniffing problem occurs".
This was in my scenario.
Now my question is, is there any way or workaround to overcome parameter sniffing in SQL Server in these scenarios?
I know by running
sp_updatestats
I can verify whether it is happening or not.And also I know to catch the problem, I need to monitor the procedure cache, by
query_hash
andquery_plan_hash
fields ofsys.dm_exec_query_stats
I can do this.I don't want to use
RECOMPILE
inSET
variable section as this will create new execution plans each time query is executed.
But instead of verifying the problem I want to overcome it by doing something in query itself, I mean for example "Detect the problem at run time and create new execution plan only as and when required(Not every time)".
I face parameter sniffing problem quite frequently, so every helpful suggestion and help will be greatly appreciated. Thanks in advance!
You can apply the option
OPTION(OPTIMIZE FOR UNKNOWN)
to queries using parameters to have the query optimized to use statistics, rather than being optimized for specific parameters. This bypasses parameter sniffing.This is explained (summarily) in Query Hints for T-SQL:
You can assign the parameters to local variables.
As explained on this post. Assigning parameters to local variables tells SQL Server to use static densities instead of static histograms, hence avoiding the parameter sniffing problem.