30.06.2013 Views

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 1: <strong>Execution</strong> Plan Basics<br />

see how the optimizer and storage engine created your plan. With DMVs and dynamic<br />

management functions, we can easily put together a query to get a very complete set of<br />

information about the execution plans on our system:<br />

SELECT [cp].[refcounts] ,<br />

[cp].[usecounts] ,<br />

[cp].[objtype] ,<br />

[st].[dbid] ,<br />

[st].[objectid] ,<br />

[st].[text] ,<br />

[qp].[query_plan]<br />

FROM sys.dm_exec_cached_plans cp<br />

CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st<br />

CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp;<br />

Listing 1.18<br />

With this query, we can see the <strong>SQL</strong> and the XML plan generated by the execution of<br />

that <strong>SQL</strong>. There are a number of different DMOs available. I used one, sys.dm_exec_<br />

cached_plans, which shows properties about the object in the plan cache, but not the<br />

plan, as the basis for this query. I then used the CROSS APPLY statement to access the two<br />

dynamic management functions to retrieve the query from sys.dm_exec_sql_text<br />

and the plan from sys.dm_exec_query_plan. The CROSS APPLY applies a function<br />

once for every row in the result set. This query returns all queries from the cache as XML.<br />

These plans that are stored in cache do not contain runtime information such as the<br />

actual number of rows or actual number of executions. They are the estimated plans.<br />

This makes them slightly less useful than the real plans (obtained from tools such as<br />

Profiler) when you're doing detailed performance tuning because you can't see those<br />

runtime values. However, the ability to immediately pull the plan straight out of cache is<br />

incredibly useful, so this method is going to serve you well.<br />

We can use the XML directly or open it as a graphical execution plan. Furthermore, information<br />

available in the cache allows us to take more direct control over our execution<br />

plans. For example, as was mentioned earlier, we can retrieve the plan_handle from the<br />

52

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!