简体   繁体   中英

How can I make sure partition prunning works at run time

Say I have a very large table, partitioned by date using a range on month.

I noticed that a query that specifies a hard value will do proper partition pruning in the execution plan. ( WHERE DATE_KEY = '1/1/2011' ). This will scan only that month's partition.

But I noticed that when I use a variable (WHERE DATE_KEY = @DATE_KEY) , say in a stored procedure, SQL Server will scan all partition.

So it's like SQL Server does partition pruning when caching the execution plan, as opposed to as runtime. Which is not ideal.

The workaround I have found is to use dynamic SQL instead EXEC('...WHERE DATE_KEY=''' + @DATE_KEY+ '''') . Which works, but is not very elegant.

So I was wondering if there is a switch or some parameter somewhere I can use to make this work properly without going through dynamic SQL. Say some hypothetical "SET COMPILE_PLAN_AT_RUNTIME ON" or something....

  1. Use RECOMPILE query hint:
    OPTION(RECOMPILE)

  2. Make sure that the parameter and the column being compared are of the same data type:
    (WHERE DATE_KEY = @DATE_KEY)

To recompile query use RECOMPILE query hint .

Check recompiling stored procedures for recompiling stored procedures. You can:

  • mark as WITH RECOMPILE in stored procedure definition - SQL Server will recompile procedure before each execution; watch out for performance hits if stored procedure is called often; check CREATE PROCEDURE
  • add WITH RECOMPILE at the end of each EXEC statement: EXEC sp_my_procedure WITH RECOMPILE
  • use sp_recompile to force recompilation on first next execution

Also, You can try using RECOMPILE query hint inside your stored procedure on specific query.

Don't forget to test for performance because recompilation is expensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM