Slow Performance when using variable in date comparison.

  • I am getting a big performance hit when I say

    DECLARE @FinalDay DATETIME

    SET @FinalDay= DATEADD(dd,-1*200,GETDATE())

    WHEREOrderDate > @FinalDay (takes 2 secs)

    but this performs much faster without using the variable.

    WHERE OrderDate > DATEADD(dd,-1*200,GETDATE()) (takes less than a second)

    is there anyway I can utilize the first query with better performance since @FinalDate is a varable that will need to change.

    Thank You

  • This looks like a case of parameter sniffing..

    have a look at this article on how this may affect the query performance and how to fix it

    http://blogs.msdn.com/khen1234/archive/2005/06/02/424228.aspx

  • Thank You.

    I was able to fix it by adding OPTION(RECOMPILE);

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply