Alternative to using local variables in a where clause

后端 未结 4 1715
清歌不尽
清歌不尽 2021-01-24 07:24

I have a query that has a where clause built using a number of local variables, This however is painfully slow. Below is a rough example as I don\'t have access to the query cur

4条回答
  •  情书的邮戳
    2021-01-24 07:56

    Optimise for unknown given by gbn may work in some cases, but in other cases, OPTION RECOMPILE may be a better choice.

    For simple queries on a dataset that varies between extremes, OPTION RECOMPILE gives you the best plan for each case, because it in effect plans out each query using static values (plan cost for each execution), but OPTIMISE FOR UNKNOWN causes a generic plan that may not be the best in any case, being average for all cases (cached plan).

    Sample usage

    select top 10 * from master..spt_values
    OPTION (RECOMPILE)
    

    There were some edge case bugs with OPTION RECOMPILE in SQL Server 2005, but it works fine in 2008.

提交回复
热议问题