Skip to content

Clarify the separate compilation when SET options change - #10499

Open
Rudi Bruchez (rudi-bruchez) wants to merge 1 commit into
MicrosoftDocs:livefrom
rudi-bruchez:fix/ansi-defaults-separate-compilation
Open

Rudi Bruchez (rudi-bruchez) wants to merge 1 commit into
MicrosoftDocs:livefrom
rudi-bruchez:fix/ansi-defaults-separate-compilation

Conversation

@rudi-bruchez

Copy link
Copy Markdown
Contributor

What's wrong

In "Cache multiple plans for the same query", the SET ANSI_DEFAULTS example explains the second plan_handle as an execution-context reinitialization and says that both entries refer to the same plan.

The existing plan remains cached, and SQL Server compiles and caches a separate plan for the other SET options. Matching query_hash and query_plan_hash values describe the same query and plan shape across these separate cached plans. The absence of a statement-level recompilation event doesn't mean that no new compilation occurred.

The wording was already present before 9a6541d9de2 (February 2020); that edit expanded the explanation without changing this distinction.

Evidence

Fresh Linux containers, Developer editions. The reproduction follows the documented stored-procedure example: execute usp_SalesByCustomer twice with ANSI_DEFAULTS ON, then once with OFF. It uses a small Sales.Customers table in a fresh database instead of requiring the WideWorldImporters sample. AUTO_CLOSE OFF, Query Store off; compatibility levels 150, 160 and 170 respectively. Diagnostic queries restore ANSI options after the three procedure calls so XML methods can read the event target.

SQL Server Build Cached procedure plans post_compile / cache_insert / statement_recompile execution_count per plan
2019 15.0.4500.2 2 2 / 2 / 0 2 and 1
2022 16.0.4305.5 2 2 / 2 / 0 2 and 1
2025 17.0.5035.5 2 2 / 2 / 0 2 and 1

On each version, the plans have different plan_handle and memory_object_address values, set_options 251 and 266, and matching query_hash and query_plan_hash. Both sql_statement_post_compile events have is_recompile = false and recompile_cause = 19 (Not a recompile). Events are selected by the procedure's object ID or collected object name; recompilations of the diagnostic batches aren't counted.

Reproduction (run with sqlcmd, with permissions to create the test database and event session):

SET NOCOUNT ON;
CREATE DATABASE verif_doc_ansi_defaults;
ALTER DATABASE verif_doc_ansi_defaults SET AUTO_CLOSE OFF;
ALTER DATABASE verif_doc_ansi_defaults SET QUERY_STORE = OFF;
GO
USE verif_doc_ansi_defaults;
GO
CREATE SCHEMA Sales;
GO
CREATE TABLE Sales.Customers (CustomerID int PRIMARY KEY, CustomerName varchar(40));
INSERT Sales.Customers VALUES (8, 'Eight'), (10, 'Ten');
GO
CREATE PROCEDURE dbo.usp_SalesByCustomer @CID int
AS
SELECT * FROM Sales.Customers WHERE CustomerID = @CID;
GO
CREATE EVENT SESSION verif_ansi ON SERVER
ADD EVENT sqlserver.sql_statement_post_compile (SET collect_object_name = 1, collect_statement = 1),
ADD EVENT sqlserver.sql_statement_recompile (SET collect_object_name = 1, collect_statement = 1),
ADD EVENT sqlserver.sp_cache_insert
ADD TARGET package0.ring_buffer;
ALTER EVENT SESSION verif_ansi ON SERVER STATE = START;
GO
SET ANSI_DEFAULTS ON;
GO
EXECUTE dbo.usp_SalesByCustomer 10;
GO
EXECUTE dbo.usp_SalesByCustomer 8;
GO
IF @@TRANCOUNT > 0 COMMIT;
GO
SET ANSI_DEFAULTS OFF;
GO
EXECUTE dbo.usp_SalesByCustomer 8;
GO
-- Restore the options required by the XML methods used for diagnostics.
SET ANSI_DEFAULTS ON;
SET IMPLICIT_TRANSACTIONS OFF;
SELECT CAST(SERVERPROPERTY('ProductVersion') AS varchar(30)) AS build,
       CAST(SERVERPROPERTY('Edition') AS varchar(80)) AS edition;
SELECT compatibility_level, is_auto_close_on FROM sys.databases WHERE database_id = DB_ID();
SELECT cp.plan_handle, cp.memory_object_address, cp.usecounts,
       CAST(pa.value AS int) AS set_options, qs.query_hash, qs.query_plan_hash, qs.execution_count
INTO #plans
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st
CROSS APPLY sys.dm_exec_plan_attributes(cp.plan_handle) AS pa
JOIN sys.dm_exec_query_stats AS qs ON qs.plan_handle = cp.plan_handle
WHERE st.dbid = DB_ID() AND st.objectid = OBJECT_ID('dbo.usp_SalesByCustomer')
  AND pa.attribute = 'set_options';
SELECT * FROM #plans ORDER BY execution_count DESC;

SELECT CAST(t.target_data AS xml) AS data INTO #xe
FROM sys.dm_xe_session_targets AS t
JOIN sys.dm_xe_sessions AS s ON s.address = t.event_session_address
WHERE s.name = 'verif_ansi';
SELECT e.n.value('@name', 'sysname') AS event_name,
       e.n.value('(data[@name="object_name"]/value)[1]', 'sysname') AS object_name,
       e.n.value('(data[@name="object_id"]/value)[1]', 'int') AS object_id,
       e.n.value('(data[@name="database_id"]/value)[1]', 'int') AS database_id,
       e.n.value('(data[@name="statement"]/value)[1]', 'nvarchar(4000)') AS statement,
       e.n.query('.') AS event_xml
INTO #events
FROM #xe CROSS APPLY data.nodes('/RingBufferTarget/event') AS e(n);
SELECT event_name, object_id, statement
FROM #events
WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer');
SELECT event_name, COUNT(*) AS event_count
FROM #events WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer')
GROUP BY event_name;
-- The full event XML is useful if the event schema differs between versions.
SELECT CONVERT(nvarchar(max), event_xml) AS event_xml FROM #events WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer');
IF (SELECT COUNT(*) FROM #plans) <> 2
    THROW 50000, 'Expected two cached procedure plans', 1;
IF (SELECT COUNT(DISTINCT query_hash) FROM #plans) <> 1
 OR (SELECT COUNT(DISTINCT query_plan_hash) FROM #plans) <> 1
 OR (SELECT SUM(execution_count) FROM #plans) <> 3
    THROW 50000, 'Unexpected plan fingerprints or execution counts', 1;
IF (SELECT COUNT(*) FROM #events WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer') AND event_name = 'sql_statement_post_compile') <> 2
 OR (SELECT COUNT(*) FROM #events WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer') AND event_name = 'sp_cache_insert') <> 2
 OR EXISTS (SELECT 1 FROM #events WHERE (object_id = OBJECT_ID('dbo.usp_SalesByCustomer') OR object_name = 'usp_SalesByCustomer') AND event_name = 'sql_statement_recompile')
    THROW 50000, 'Unexpected compilation events', 1;
ALTER EVENT SESSION verif_ansi ON SERVER STATE = STOP;
DROP EVENT SESSION verif_ansi ON SERVER;
GO
USE master;
DROP DATABASE verif_doc_ansi_defaults;
GO

The assertions verify two cached entries, matching fingerprints, three executions in total, two compilation events, two cache insertions, and no statement-recompilation event for the procedure. The script drops the event session and database when the checks pass.

Change

Replaces only the nested bullet explaining the new plan handle: separate compilation, the original plan remaining cached, and the meaning of the matching fingerprints. No changes to the example or its output.

Not tested on Windows, Azure SQL Database, Azure SQL Managed Instance or Fabric.

@prmerger-automator

Copy link
Copy Markdown
Contributor

Rudi Bruchez (@rudi-bruchez) : Thanks for your contribution! The author(s) and reviewer(s) have been notified to review your proposed change.

@prmerger-automator

Copy link
Copy Markdown
Contributor

Rudi Bruchez (@rudi-bruchez) : Thanks for your contribution! The author(s) and reviewer(s) have been notified to review your proposed change.

@learn-build-service-prod

Copy link
Copy Markdown
Contributor

Learn Build status updates of commit a4b84d7:

✅ Validation status: passed

File Status Preview URL Details
docs/relational-databases/query-processing-architecture-guide.md ✅Succeeded

For more details, please refer to the build report.

@ttorble

Copy link
Copy Markdown
Contributor

Derek Wilson (@thesqlsith)

Can you review the proposed changes?

Due to the upcoming conference, all merging and publishing is on hold until the morning of November 17.

Important: When the changes are ready for publication, adding a #sign-off comment is the best way to signal that the PR is ready for the review team to merge.

#label:"aq-pr-triaged"
@MicrosoftDocs/public-repo-pr-review-team

@prmerger-automator prmerger-automator Bot added the aq-pr-triaged tracking label for the PR review team label Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants