kohera-logo-regular.svg

SQL Server Plan Guides: A Walkthrough, Part 2

Vector_BG.png

SQL Server Plan Guides: A Walkthrough, Part 2

Vector_BG.png

In the first part of this blog series, we looked into the basic plan guide setup, the fact that hints already on the queries will be overwritten by the plan guide and some other intricacies. In this part we will be taking a closer look at somethings you cannot do as well, as how to add a plan guide to procedures, and lastly how you could find queries that are using plan guides.

Test Data

CREATE TABLE DBO.TABLE1( ID INT IDENTITY(1,1), VALUE NVARCHAR(255));
CREATE TABLE DBO.TABLE2( ID INT IDENTITY(1,1), TABLE1ID INT, VALUE INT);

SET NOCOUNT ON;

DECLARE @I INT = 1
WHILE @I < 10000
BEGIN
INSERT INTO DBO.TABLE1(VALUE)
VALUES('PLAN GUIDE DEMO')

INSERT INTO DBO.TABLE2(TABLE1ID,VALUE)
VALUES(@I,@I)

INSERT INTO DBO.TABLE2(TABLE1ID,VALUE)
VALUES(5,5)

SET @I += 1
END

Create some indexes for the query’s

--CLUSTERED INDEXES
CREATE CLUSTERED INDEX CX_TABLE1_ID
on dbo.TABLE1(ID)
CREATE CLUSTERED INDEX CX_TABLE2_ID
on dbo.TABLE2(ID)
-- SEEK NC INDEX
CREATE INDEX IX_TABLE2_VALUE_TABLE1ID
on dbo.TABLE2(Value,TABLE1ID)

Query with a table variable

Consider the following query:

DECLARE @values table(id int, val varchar(255))
INSERT INTO @values(id,val)
values(1,'test');

SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2
ON T1.ID = T2.TABLE1ID
WHERE T2.VALUE IN (select id from @values);

We could try and create a plan guide for it:

EXEC sp_create_plan_guide
@name = 'RecompileForce',
@stmt = '',
@type = 'SQL',
@module_or_batch ='DECLARE @values table(id int, val varchar(255))
INSERT INTO @values(id,val)
values(1,''test'')

SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2
T2
ON T1.ID = T2.TABLE1ID
WHERE T2.VALUE IN (select id from @values)',
@hints = N'OPTION(RECOMPILE)';

An error occurs:

Msg 10509, Level 16, State 1, Line 11 Cannot create plan guide ‘RecompileForce’ because the statement specified by @stmt or @statement_start_offset either contains a syntax error or is ineligible for use in a plan guide. Provide a single valid Transact-SQL statement or a valid starting position of the statement within the batch. To obtain a valid starting position, query the ‘statement_start_offset’ column in the sys.dm_exec_query_stats dynamic management function.

Why?

In this case there are two reasons why I can’t create the plan guide. The obvious one being that you can’t do it on two statements, the second reason being that ‘USE PLAN’ can’t use DML. As a result, plan guides also cannot use DML.

An extra example of this:

EXEC sp_create_plan_guide
@name = 'RecompileForce',
@stmt = '',
@type = 'SQL',
@module_or_batch ='update dbo.table1 set VALUE = 1',
@hints = N'OPTION(RECOMPILE)';

Results in the same error.

Adding a plan guide for a procedure

No parameters

Create proc Dbo.ProcNoParams
as
SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2
ON T1.ID = T2.TABLE1ID

 

Simply execute it like so:

Exec Dbo.ProcNoParams;

Okay, so how do we add a plan guide for this?

We use the OBJECT @type. But note that the query statement needs to be added, aswell as the proc name.

EXEC sp_create_plan_guide @name = N'[ProcedureNoParamsPlanGuide]',
@stmt = N'SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2
ON T1.ID = T2.TABLE1ID ',
@type = N'OBJECT',
@module_or_batch = N'[Dbo].[ProcNoParams]',
@hints = N'OPTION (RECOMPILE)'

Ok, but how do we make sure that this worked? After all, plan guides are not going to ring any bells when they are being used?

Inside the query plan XML two new records are added, PlanGuideDB and PlanGuideName:

Which makes querying the plan XML possible:

The query we could use to find our ‘ProcedureNoParamsPlanGuide’ in action:

with xmlnamespaces (default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT TOP 10
databases.name,
dm_exec_sql_text.text AS TSQL_Text,
dm_exec_query_stats.creation_time, dm_exec_query_stats.execution_count,
dm_exec_query_stats.total_worker_time AS total_cpu_time,
dm_exec_query_stats.total_elapsed_time, dm_exec_query_stats.total_logical_reads,
dm_exec_query_stats.total_physical_reads,
dm_exec_query_plan.query_plan
FROM sys.dm_exec_query_stats 
CROSS APPLY sys.dm_exec_sql_text(dm_exec_query_stats.plan_handle) 
CROSS APPLY sys.dm_exec_query_plan(dm_exec_query_stats.plan_handle) 
INNER JOIN sys.databases 
ON dm_exec_sql_text.dbid = databases.database_id 
WHERE

query_plan.value('(/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/@PlanGuideNa 
me)[1]', 'varchar(max)') ='ProcedureNoParamsPlanGuide'


Houston we have lift-off

Querying for plan guides

Query to get all the plans in cache that use a plan guide

with xmlnamespaces (default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 
SELECT
 databases.name, 
dm_exec_sql_text.text AS TSQL_Text, 
dm_exec_query_stats.creation_time, dm_exec_query_stats.execution_count, 
dm_exec_query_stats.total_worker_time AS total_cpu_time, 
dm_exec_query_stats.total_elapsed_time, 
dm_exec_query_stats.total_logical_reads, 
dm_exec_query_stats.total_physical_reads, 
dm_exec_query_plan.query_plan 
FROM sys.dm_exec_query_stats 
CROSS APPLY sys.dm_exec_sql_text(dm_exec_query_stats.plan_handle) 
CROSS APPLY sys.dm_exec_query_plan(dm_exec_query_stats.plan_handle) 
INNER JOIN sys.databases 
ON dm_exec_sql_text.dbid = databases.database_id 
WHERE

query_plan.value('(/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/@PlanGuideNa me)[1]', 'varchar(max)') is not null

Depending on your hardware and the amount of plan’s in cache, this might take a while.

Stored Procedures with parameters

Consider the following procedure:

Create proc Dbo.ProcParams 
( 
@Value int = NULL 
) 
as 
SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
WHERE T2.VALUE = @Value;

Exec Dbo.ProcParams @Value = 1

 

Create the plan guide

EXEC sp_create_plan_guide @name = N'[ProcedureParamsPlanGuide]',
@stmt = N'SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID WHERE T2.VALUE = @Value;', 
@type = N'OBJECT', 
@module_or_batch = N'[Dbo].[ProcParams]', 
@hints = N'OPTION (RECOMPILE)' 

Note that you do not need to declare any variables in the @stmt, just add all the query text in the stored proc after the ‘as’. Change any single quote (‘) characters to double quotes (‘’).

 

Executing it once and checking the plan cache to see if the guide was used



Exec Dbo.ProcParams @Value = 1

Executing it again with a different parameter

Exec Dbo.ProcParams @Value = 2

Wait, the execution count remains 1?
– That is because we are using option(recompile), the creation_time did change due to recompilation of the plan.

Different kinds of procedures

Multiple queries

CREATE proc Dbo.ProcDoubleQuery

as 
SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
WHERE T1.ID = 1; 
SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
WHERE T1.ID = 2;

 

Not possible in its entirety:

Cannot create plan guide ‘ProcedureDoubleQueryPlanGuide’ because parameter @stmt has more than one statement.

 

Workaround, creating two plan guides:

EXEC sp_create_plan_guide @name = N'[PLanGuide_ProcDoubleQuery_1]', 
@stmt = N'SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
WHERE T1.ID = 1;', 
@type = N'OBJECT', 
@module_or_batch = N'[Dbo].[ProcDoubleQuery]', 
@hints = N'OPTION (RECOMPILE)'

EXEC sp_create_plan_guide @name = N'[PLanGuide_ProcDoubleQuery_2]', 
@stmt = N'SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
WHERE T1.ID = 2;', 
@type = N'OBJECT',
@module_or_batch = N'[Dbo].[ProcDoubleQuery]', 
@hints = N'OPTION (RECOMPILE)'

My script is not optimized for multiple plan guides, as in it will always show the first one found.

Looking at the XML however, we will find both plan guides:

A procedure that declares a parameter

CREATE proc Dbo.ProcDeclare

as 
declare @blabla int 
set @blabla = 5 
SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
where t2.value = @blabla

Not possible in its entirety:
Cannot create plan guide ‘ProcedureProcDeclare’ because parameter @stmt has more than one statement.

 

A Workaround

But, if we omit the declaration of @blabla:

EXEC sp_create_plan_guide @name = N'[PLanGuide_ProcDeclare]', 
@stmt = N'SELECT * FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
where t2.value = @blabla;', 
@type = N'OBJECT', 
@module_or_batch = N'[Dbo].[ProcDeclare]',
@hints = N'OPTION (RECOMPILE)'

The plan guide gets used:

A procedure that uses a CTE

CREATE proc Dbo.ProcCTE

as 
WITH CTE 
AS 
( 
SELECT T1.ID FROM DBO.TABLE1 T1 INNER JOIN DBO.TABLE2 T2 
ON T1.ID = T2.TABLE1ID 
where t2.value = 5 )

SELECT * FROM CTE;

Works from the get go:

Commands completed successfully.

Extra’s


						
2319-blog-database-specific-security-featured-image
Database specific security in SQL Server
There are many different ways to secure your database. In this blog post we will give most of them a...
kohera-2312-blog-sql-server-level-security-featured-image
SQL Server security on server level
In this blog, we’re going to look at the options we have for server level security. In SQL Server we...
blog-security_1
Microsoft SQL Server history
Since its inception in 1989, Microsoft SQL Server is a critical component of many organizations' data infrastructure. As data has...
DSC_1388
Aggregaties
Power BI Desktop is een prachtige tool om snel data-analyses te kunnen uitvoeren. Je connecteert op een databron, importeert en...
dba image
DBA is not that scary
Often when talking to people who are looking for a career path in the data world I feel like there...
blog-2303
How do you link an SCD Type 2 table in Power Query?
This article uses a simple example to demonstrate how to link an SCD Type 2 table in Power Query to...