Search code examples
sql-serversql-execution-plansqlperformance

How to store query execution plan so that they can be used later


My applications runs queries against a sql server database.

In many cases I can see the benefit of an execution plan: for example I click for the first time on a button to

SELECT * from Tasks
WHERE IdUser = 24 AND
  DATE < '12/12/2010' and DATE > '01/01/2010'

it takes 15 seconds the first time, 8 seconds the following times.

EDIT: I USE PARAMETRIZED QUERIES.

So I have a 7 seconds improvement the second time.

Now as I run the application again (so I do a new database connection) the first time it will take 15 seconds, the second time 7...

How is it possible to tell SQL Server to store the execution plans, at least to remember them for same days? Or however how can I get benefit of already calculated execution plans? If different users run the same query is it a way to tell sql server to be smart enough to use the same execution plan, even if in that case probably the IdUser will be different.

In software I have some parameters, so may be the next execution of the query will have different MinDate and MaxDate, but will this affect the query plan?


Solution

  • Use parametrised queries to maximise the chances that the plan will be cached

    SELECT * from MYTasks 
    WHERE IdUser = @UserId AND DATE < @enddate and DATE > @startdate
    

    SQL Server does do auto parametrisation but can be quite conservative about this.

    You can get some insight into plan reuse from the following

    SELECT usecounts, cacheobjtype, objtype, text, query_plan, value as set_options
    FROM sys.dm_exec_cached_plans 
    CROSS APPLY sys.dm_exec_sql_text(plan_handle) 
    CROSS APPLY sys.dm_exec_query_plan(plan_handle) 
    cross APPLY sys.dm_exec_plan_attributes(plan_handle) AS epa
    where text like '%MYTasks%' and attribute='set_options'