-- Clear procedure cache
DBCC FREEPROCCACHE;
GO
-- First query run to get plan for freezing
SET STATISTICS XML ON;
EXEC sp_executesql
N'SELECT orderid, customerid, orderdate, shippeddate
FROM Orders
WHERE customerid = N''CACYK''';
SET STATISTICS XML OFF;
GO
-- Create plan quide based on plan
DECLARE @plan_handle VARBINARY(64);
SELECT @plan_handle = plan_handle
FROM sys.dm_exec_query_stats AS S
CROSS APPLY sys.dm_exec_sql_text(S.sql_handle) AS T
WHERE text LIKE '%Order%';
EXEC sp_create_plan_guide_from_handle 'PlanGuide2008', @plan_handle = @plan_handle;
GO
-- Check that plan guide was created
SELECT * FROM sys.plan_guides;
GO
-- Execute and verify UsePlan="1" and PlanGuideName="PlanGuide2008"
-- in the XML plan output
SET STATISTICS XML ON;
EXEC sp_executesql
N'SELECT orderid, customerid, orderdate, shippeddate
FROM Orders
WHERE customerid = N''CACYK''';
SET STATISTICS XML OFF;
GO
EXEC sp_control_plan_guide N'DROP', N'PlanGuide2008';
Labels: performance tuning, t-sql programming