Poor Stored Procedure Performance Due to Parameter Sniffing
You're encountering performance issues with a stored procedure where an input parameter (@MyDate) can be NULL or a date. When the procedure is first compiled with @MyDate as NULL, subsequent executions exhibit poor performance regardless of the actual parameter value.
Parameter Sniffing Behavior
SQL Server performs "parameter sniffing" to optimize execution plans based on the parameter values during compilation. It captures these values in the procedure cache and uses them to estimate future executions.
In this case, parameter sniffing is causing the problem because it generates a suboptimal execution plan for all parameter values when @MyDate is NULL initially. Even when @MyDate is explicitly set to NULL at execution time, the cached plan remains.
Disabling Parameter Sniffing
You've encountered the classic symptom of "parameter sniffing gone bad," where the plan generated for the initial parameter values is used even when they are not representative of actual executions. To disable parameter sniffing, you spoofed the parameter with @MyDate_Copy.
Root Cause and Solution
The issue stems from a SQL Server 2005 bug where parameter sniffing can misbehave. In SQL Server 2008, you can mitigate this issue by using the OPTIMIZE FOR UNKNOWN option, which forces the optimizer to consider all possible values for the parameter during plan compilation.
Additional Insights
The above is the detailed content of How Can I Resolve Poor Stored Procedure Performance Caused by Parameter Sniffing in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!