SQL Server 2008 : Managing Query Performance - Forcing a Specific Execution Plan
Example 1. Syntax Used to Specify an Execution Plan by Supplying the USE PLAN Query Hint
In order to supply the execution plan, you must first capture it in XML format. There are a few ways you can capture the XML execution plan to supply the query.
You can use the SHOWPLAN_XML SET statement to return the XML execution plan instead of running the query, as shown in the following code:
SET SHOWPLAN_XML ON
GO
SELECT * FROM Table
SET SHOWPLAN_XML OFF
GO
You can use the STATISTICS XML SET statement to return the XML execution plan following the query result set, as shown in the following code:
SET STATISTICS XML ON
GO
SELECT * FROM Table
SET STATISTICS XML OFF
GO
You can use the query_plan column in the sys.dm_exec_query_plan Dynamic Management Function, as shown in the following query:
SELECT est.text, eqp.query_plan
FROM sys.dm_exec_cached_plans ecp
CROSS APPLY sys.dm_exec_query_plan(ecp.plan_handle) eqp
CROSS APPLY sys.dm_exec_sql_text(ecp.plan_handle) est
You can use the Showplan XML, Showplan XML Statistics Profile, and Showplan XML For Query Compile event classes in SQL Server Profiler.
You can use the Display Estimated Execution Plan and Include Actual Execution Plan options in SQL Server Management Studio; right-click the execution plan, and select Show Execution Plan XML from the context menu.
If the XML execution plan is invalid in any way, the query will fail. Certain underlying database schema changes may cause the execution plan to become invalid. Therefore, it is extremely important to test any queries that have the USE PLAN query hint after making database changes. Just as with any option you use to override the query optimizer, you should apply the USE PLAN query hint with extreme caution, and then only after you have exhausted your other options, such as creating proper indexes and updating statistics. Since the USE PLAN query hint forces a query to utilize a specified execution plan, the query optimizer will no longer be able to dynamically adjust to changes within the database.