SQL Server Stored Procedure Performance Degradation due to Parameter Sniffing
Parameter sniffing is an optimization technique used by SQL Server to improve query performance by selecting an execution plan based on the parameter values at the time the stored procedure is first compiled. However, in certain instances, parameter sniffing can lead to performance issues.
Consider the following stored procedure:
CREATE PROCEDURE MyProc @MyDate DATETIME = NULL AS IF @MyDate IS NULL SET @MyDate = CURRENT_TIMESTAMP -- Do Something using @MyDate
When this stored procedure is first executed with @MyDate as NULL, the query optimizer generates an execution plan that is optimized for that particular parameter value. However, if the stored procedure is subsequently executed with a different value for @MyDate, the query optimizer may not compile an optimal execution plan, leading to performance degradation.
This issue is known as "parameter sniffing gone bad". In the above example, even if @MyDate is actually NULL when used in the stored procedure, the poor execution plan that was generated based on the initial compilation remains in effect.
To resolve this issue, one can disable parameter sniffing by spoofing the parameter:
CREATE PROCEDURE MyProc @MyDate DATETIME = NULL AS DECLARE @MyDate_Copy DATETIME SET @MyDate_Copy = @MyDate IF @MyDate_Copy IS NULL SET @MyDate_Copy = CURRENT_TIMESTAMP -- Do Something using @MyDate_Copy
This approach creates a copy of the input parameter and uses that copy for the query optimization process, preventing biased parameter sniffing.
In SQL Server 2008 and later, parameter sniffing can be optimized using the OPTIMIZE FOR UNKNOWN hint:
CREATE PROCEDURE MyProc @MyDate DATETIME = NULL WITH RECOMPILE, OPTIMIZE FOR UNKNOWN AS -- Do Something using @MyDate
This hint instructs the query optimizer to generate an execution plan based on unknown parameter values, eliminating the risk of parameter sniffing-related performance issues.
The above is the detailed content of How Can I Resolve SQL Server Stored Procedure Performance Degradation Caused by Parameter Sniffing?. For more information, please follow other related articles on the PHP Chinese website!