We are struggling with a strange problem: a stored procedure become extremely slow when raw SQL is executed fairly fast.
We have
Try using using the hint OPTIMIZE FOR UNKNOWN
. If it works, this may be better than forcing a recompile every time. The problem is that, the most efficient query plan depends on the actual value of the date paramter being supplied. When compiling the SP, sql server has to make a guess on what actual values will be supplied, and it is likely making the wrong guess here. OPTIMIZE FOR UNKNOWN
is meant for this exact problem.
At the end of your query, add
OPTION (OPTIMIZE FOR (@now UNKNOWN))
http://blogs.msdn.com/b/sqlprogrammability/archive/2008/11/26/optimize-for-unknown-a-little-known-sql-server-2008-feature.aspx