Troubleshooting Guide: SQL Server Error 6717 – XQuery Document Tree Too Deep
Why This Error Happens
This error occurs when SQL Server’s XQuery engine attempts to parse or process an XML document whose hierarchical nesting exceeds the maximum supported depth of 128 levels. This typically happens with deeply recursive XML schemas, auto-generated XML from poorly optimized export routines, or XML data imported from external systems that do not enforce depth limits. SQL Server enforces this cap to prevent stack overflow conditions and excessive memory consumption during XML parsing operations.
Step-by-Step Resolution Guide
Step 1: Identify the Offending XML Data
- Locate the specific query, stored procedure, or import job that triggered Error 6717.
- Run
SELECT @@VERSION;to confirm you are on SQL Server 2025 and check for any pending XML-related Cumulative Updates. - Use SQL Server Profiler or Extended Events to trace the exact T-SQL statement and XML column/variable causing the failure.
- Export a sample of the problematic XML using
SELECT CAST(XmlColumn AS NVARCHAR(MAX))to inspect nesting visually.
Step 2: Simplify or Flatten the XML Hierarchy
- Work with the source system or application team to reduce unnecessary nested elements (e.g., collapse repeated wrapper nodes).
- If the XML is generated via
FOR XML PATHorFOR XML AUTO, refactor the query to use flatter structures orFOR XML EXPLICITwith controlled depth. - For incoming XML files, use a pre-processing step (PowerShell, XSLT transform, or an SSIS Script Task) to flatten deeply nested nodes before loading into SQL Server.
- Example PowerShell flattening snippet:
[xml]$doc = Get-Content "C:\Data\input.xml"
# Apply XSLT transform to reduce nesting
Step 3: Adjust Application-Level XML Processing
- If using
OPENXMLor.nodes()/.value()methods, break large XQuery expressions into smaller, staged queries against intermediate temp tables. - Store partial XML fragments in separate
XML-typed columns rather than one deeply nested document. - On Windows Server 2025, ensure the SQL Server service account has adequate memory allocation (check via
sys.dm_os_process_memory) since excessive depth attempts can also correlate with memory pressure errors.
Step 4: Validate Schema Constraints
- If an XML Schema Collection (XSD) is bound to the column, review it using:
SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
- Modify the schema to cap
maxOccursand nesting depth on recursive complex types to prevent future violations.
Alternative or Verification Steps
- After flattening, re-run the original query or import job and confirm Error 6717 no longer appears in the SQL Server Error Log (
EXEC xp_readerrorlog 0, 1, N'6717';). - As a workaround, consider processing deeply nested XML outside SQL Server entirely (e.g., via a C# or Python pre-processing service) and only inserting the pre-flattened result into SQL Server tables.