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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 10:58:12

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'

SQL Server will do this for you - any execution plan is stored for as long as there is space available.

However, you can do a lot to increase the chances of execution plans being stored and reused - what you need to take care is to create identical SQL queries - anything down to an extra space can cause SQL Server to consider two queries to be different and not reuse an existing query plan.

So therefore:

  • be consistent in your queries - always spell out things in identical manner (watch out for capitalization / non-capitalization, whitespaces, dbo. prefixes etc.)

  • use parameters instead of literal values; if you use literal values your query plans will not be reused, and they unnecessarily fill up the plan cache.

  • try to avoid SELECT * - this means the query optimizer has less options - since you want all columns, it typically has to do a scan on the clustered index. If you specify the three, five, six columns you really need, there's a chance there might be an index that covers the query (contains all the columns you're interested in) and therefore, the query analyze could use that index and do an index scan / index seek on that (and reuse that plan).

So instead of your SQL now, use this instead:

SELECT (list of fields)
FROM dbo.MYTasks 
WHERE DATE < @EndDate and DATE > @StartDate

That should increase query plan reuse significantly.

Have you run the SQL Server Profiler? If so, are you sure the extra time is taken in compiling the statement and generating execution plans?

From your problem description, the additional 7 seconds could be time to setup the initial connection to the database. Maybe you've ruled this out already. I don't know.

An additional concern is the data cache. The first time you access data, SQL Server loads it into its cache. This can reduce the time of subsequent queries (assuming it can hold all the data).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!