Parameter sniffing in SQL server 2005


I had an issue in one of our SQL server stored procedures recently with query execution plan caching. I had a datetime input parameter which caused a serious slowness to stored procedure. Initially we could not find out what was going on but after digging deep in the code base we found it is happening in stored procedural level. Query execution plan caching is a good thing as this helps the DB to deliver the data quite quickly but some cases caching can cause real night mares as what we faced in our stored proc.

We sorted the parameter sniffing issue with local variable declaration in the stored procedure. When declare the local variable and assign the input parameter into the local variable, SQL server doesn�t cache the parameter. This way we can disable to parameter sniffing in SQL server 2005.

Following is an example how the stored procedure was before the change made in receiving input parameter.


Code:
CREATE PROCEDURE usp_getdate(@IDate datetime=Null)
AS
  BEGIN
  SELECT CUSID,CUSTNAME FROM TB_Customer where DateAdded<@IDate AND ...;
  END
GO


After adding the local variable

Code:
CREATE PROCEDURE usp_getdate(@IDate datetime=Null)
AS
  BEGIN
   Decalre @lclDate datetime
   SET  @lclDate=@IDate;
  SELECT CUSID,CUSTNAME FROM TB_Customer where DateAdded<@IDate AND ...;
  END
GO


Above stored proc will remove the cache.

Also there is another way to disable the parameter sniffing is use OPTION hint in the query to recompile the execution plan.

So above query could have been something like

Code:
SELECT CUSID,CUSTNAME FROM TB_Customer where DateAdded<@IDate OPTION(OPTIMIZE FOR (@IDate = Null))


I hope this article will help someone out there.

Thanks for reading this.

Commentaires

Posts les plus consultés de ce blog

XAJAX with PHP – The future of web development

XAJAX with PHP – The future of web development

Database connection pooling in ADO.Net