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....
Use RECOMPILE
query hint:
OPTION(RECOMPILE)
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:
EXEC sp_my_procedure WITH RECOMPILE
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.