SQL Server: stored procedure become very slow, raw SQL query is still very fast

后端 未结 2 1376
刺人心
刺人心 2021-02-14 05:03

We are struggling with a strange problem: a stored procedure become extremely slow when raw SQL is executed fairly fast.

We have

  • SQL Server 2008 R2 Expre
2条回答
  •  滥情空心
    2021-02-14 06:02

    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

提交回复
热议问题