How to fix Error 6933 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6933 – “XML Validation: Invalid Simple Type Operation”

Why This Error Happens

This error occurs when SQL Server’s XML parser attempts to validate an XML instance against an XML Schema Collection (XSD) and encounters a simple type (such as an attribute or element value) that does not conform to the facets, restrictions, or data type defined in the schema. This is commonly triggered by corrupted XML data, a mismatched or outdated XML Schema Collection bound to the column, or an application sending malformed data (e.g., incorrect date formats, out-of-range numeric values, or invalid enumeration values) that violates xs:simpleType restrictions. In some cases, this also surfaces after an in-place upgrade to SQL Server 2025 on Windows Server 2025, where stricter XSD compliance checks expose previously unvalidated legacy data.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data and Schema Collection

  • Run SELECT name, xml_collection_id FROM sys.xml_schema_collections; to list schema collections bound to your database.
  • Use SELECT * FROM sys.dm_exec_describe_first_result_set or query the affected table directly to locate the specific row/column causing the validation failure.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact XPath or element name referenced in the 6933 error.

Step 2: Validate and Correct the XML Instance

  • Extract the problematic XML value using SELECT CAST(xml_column AS NVARCHAR(MAX)) FROM YourTable WHERE PrimaryKey = X;.
  • Open the extracted XML in a validation tool (Visual Studio 2022/2025 XML Editor or xmllint.exe) against the associated .xsd file.
  • Correct data type mismatches manually — for example, ensure xs:date fields use YYYY-MM-DD format and xs:integer fields do not contain decimal or alphanumeric values.
  • Re-insert or update the corrected XML using UPDATE YourTable SET xml_column = @FixedXml WHERE PrimaryKey = X;.

Step 3: Rebuild or Refresh the XML Schema Collection

  • If the schema itself is outdated, drop and recreate it: DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;.
  • Re-register the corrected XSD using CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollection AS N'<xsd content>';.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear any cached schema metadata.

Step 4: Check for Application-Layer Data Submission Issues

  • Review the application or ETL pipeline (SSIS package, .NET DataSet, or API payload) generating the XML to ensure it enforces the same type constraints as the SQL Server schema collection.
  • Add client-side validation using System.Xml.Schema.XmlSchemaSet in .NET before submitting data to SQL Server, preventing malformed XML from reaching the database layer.

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT/UPDATE statement or application transaction that triggered Error 6933 — it should now complete without validation errors.
  • Alternative approach: If schema strictness is not business-critical, temporarily store the data as untyped XML (without a schema collection) to unblock operations, then re-apply validation once the root data issue is resolved.

How to fix Error 6929 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6929 – Invalid QName for xsi:type Attribute

Why This Error Happens

This error occurs when SQL Server’s XML parser encounters an xsi:type attribute value that does not conform to a valid QName (Qualified Name) format, typically because the namespace prefix used has not been properly declared within the scope of the XML instance document. It commonly arises from malformed XML being inserted into an XML-typed column, corrupted data during a bulk import, or client applications generating XML with incorrect namespace bindings. Additionally, this can surface after upgrading to SQL Server 2025 if legacy XML schema collections contain prefix mappings that are no longer resolved correctly by the updated XML validation engine.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XML Data

  • Identify the specific INSERT, UPDATE, or import operation that triggered Error 6929 by checking SQL Server Error Logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Extract the exact XML payload using SQL Server Profiler or Extended Events (xml_validation_error event) to capture the raw string causing the failure.
  • Look specifically for the xsi:type attribute value flagged in the error message (e.g., ns1:CustomType).

Step 2: Validate Namespace Prefix Declarations

  • Open the XML source and confirm that every prefix used in an xsi:type attribute (e.g., ns1) has a corresponding xmlns:ns1="http://your-namespace-uri" declaration in an ancestor element.
  • Check for case-sensitivity mismatches between the prefix declared and the prefix used in the xsi:type value.
  • If using Windows PowerShell to test XML validity, run:
  [xml]$doc = Get-Content "C:\Temp\test_payload.xml"
  $doc.OuterXml

Step 3: Repair or Rebuild the XML Schema Collection

  • If the issue stems from a registered XML Schema Collection (XSC), query the current definition:
  SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Drop and recreate the schema collection with updated namespace mappings if the collection pre-dates a SQL Server 2025 compatibility level change:
  ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName ADD N'<xsd:schema>...</xsd:schema>';
  • Ensure the application connection string or middleware (e.g., .NET XmlSerializer) is updated to emit fully qualified namespace prefixes matching the server-side schema.

Step 4: Patch and Restart the SQL Service

  • Verify you are running the latest Cumulative Update (CU) for SQL Server 2025, as early XML parser builds had known QName resolution bugs.
  • Apply the update, then restart the service via PowerShell:
  Restart-Service -Name "MSSQLSERVER" -Force

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT/UPDATE statement or re-importing the file; confirm no Error 6929 appears in the Application Event Viewer under Windows Logs > Application, filtered by Event ID 6929.
  • Alternative workaround: If immediate resolution isn’t possible, temporarily cast the column as nvarchar(max) instead of xml to bypass strict validation, then migrate back to the xml type once the namespace prefixes are corrected at the source.

How to fix Error 6930 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6930 – XML ID Constraint Validation Failure

Why This Error Happens

Error 6930 occurs when SQL Server 2025 validates an XML instance against a schema collection (XSD) that defines an attribute or element with the ID data type, and the XML document contains two or more elements sharing the same ID value. Per the W3C XML Schema specification, xs:ID values must be unique within the document, so the SQL Server XML parser rejects the data during INSERT, CAST, or CONVERT operations against an xml typed column bound to a schema collection. This is typically caused by malformed source data, a faulty ETL/export process that duplicates keys, or an XSD schema that incorrectly reuses an ID attribute name across unrelated element types that should instead use IDREF or a scoped key constraint.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Document and Attribute

  • Capture the full error message text, which includes the specific attribute name and duplicate ID value (e.g., Found attribute named 'ItemID' with duplicate ID value 'A1023').
  • Run the failing INSERT/UPDATE statement in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF and capture the exact XML payload being passed.
  • Use SELECT CAST(@xmlVariable AS xml) in isolation to reproduce the failure outside of the larger batch or application call.

Step 2: Inspect and Correct the XML Source Data

  • Export the problematic XML to a flat file and open it in VS Code or an XML editor that supports XPath querying.
  • Run an XPath query such as //*[@ItemID] to list all nodes using the flagged attribute, then manually diff values to locate the duplicate.
  • Correct the source system or generation script (SSIS package, application serializer, or stored procedure) so that each ID-typed attribute is guaranteed unique, typically by using a GUID or a sequential key generator instead of a business key that can repeat.

Step 3: Review and Adjust the XML Schema Collection

  • Open the schema collection definition with: SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Check whether the attribute was incorrectly typed as xs:ID when it should be xs:string or xs:IDREF (IDREF attributes point to an ID elsewhere and do not require document-wide uniqueness themselves).
  • If the schema is wrong, drop and recreate the collection: DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName; followed by CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'<corrected XSD content>';
  • Re-bind the corrected schema collection to the target column if it was temporarily detached during troubleshooting.

Step 4: Validate Data Integrity Upstream

  • If the XML originates from an external feed or API, add a pre-validation step in your application or SSIS data flow using an XmlReaderSettings object with ValidationType.Schema in .NET to catch duplicates before they reach SQL Server.
  • Log and quarantine any documents failing pre-validation into a staging table (xml_staging_errors) for manual review rather than allowing them to hit the production insert path.

Alternative or Verification Steps

  • Verify the fix: Re-run the original INSERT/CAST statement against the corrected XML document; a successful execution with no Error 6930 confirms resolution. Also run SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName'; to confirm the schema updated correctly.
  • Alternative workaround: If immediate correction of upstream data isn’t feasible, temporarily load the XML into an untyped xml column (without a schema collection bound) to unblock ingestion, then run a scheduled cleanup/validation job before promoting the data to schema-validated tables.

How to fix Error 6931 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6931 – XML Validation IDREF Constraint Check Failed

Why This Error Happens

Error 6931 occurs when SQL Server’s XML schema validation engine encounters an attribute of type IDREF or IDREFS that points to an ID value which does not exist anywhere in the XML instance document. This typically happens due to malformed XML data being inserted into a column typed with an XML schema collection, incomplete data migrations, or application-layer logic that generates XML fragments referencing nodes outside the current document scope. It can also surface after upgrading to SQL Server 2025 if legacy XML schema collections were registered with looser validation rules than the new engine enforces.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Document and Schema Collection

  • Run SELECT name, xml_collection_id FROM sys.columns WHERE xml_collection_id IS NOT NULL; to locate the affected column.
  • Extract the specific XML value causing the failure using a targeted SELECT on the primary key range reported in the SQL Server error log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025).
  • Cross-reference the attribute name and ID value from the error message (%.*ls placeholders) against the raw XML content.

Step 2: Validate and Repair the XML Instance

  • Export the problematic XML using SQL Server Management Studio (SSMS) 21 by right-clicking the result grid cell and selecting “Save Result As.”
  • Open the file and search for the IDREF attribute named in the error; confirm whether the corresponding ID-typed element/attribute is missing, misspelled, or was truncated during a prior ETL/import job.
  • Manually correct the XML fragment, or regenerate it from the source application, ensuring every IDREF has a matching ID in the same document instance.

Step 3: Re-register or Update the XML Schema Collection

  • If the schema itself is outdated, drop and recreate it using:
  ALTER XML SCHEMA COLLECTION [SchemaName] ADD 'updated_xsd_content_here';
  • Verify the .xsd file used for the collection correctly defines the xs:ID and xs:IDREF relationships and hasn’t been corrupted during transfer.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear any cached schema validation plans.

Step 4: Re-insert or Update the Corrected Data

  • Execute the UPDATE or INSERT statement again with the corrected XML payload.
  • Monitor the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for Event ID 6931 to confirm it no longer triggers.

Alternative or Verification Steps

  • Verify the fix by running SELECT XmlColumn.exist('//*[@id]') FROM YourTable; to confirm all referenced IDs resolve correctly within the document.
  • If the error persists across multiple records, consider temporarily unbinding the XML schema collection from the column (ALTER TABLE ... ALTER COLUMN XmlColumn XML; without the schema reference), cleaning the dataset in bulk, then re-binding the schema once all historical data is validated.

How to fix Error 6927 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6927 – XML Validation: Invalid Simple Type Value

Why This Error Happens

Error 6927 occurs when SQL Server 2025 attempts to validate an XML instance against an XML Schema Collection (XSD), but a node’s value does not conform to the simple type defined in the schema (e.g., a string value placed where an xs:integer, xs:date, or xs:boolean is expected). This typically happens due to malformed data being inserted into a typed XML column, locale/culture mismatches in date or numeric formatting, or a corrupted/outdated XML Schema Collection that no longer matches the application’s data contract. It can also surface after an in-place upgrade to SQL Server 2025 if stricter XSD compliance checks were introduced for existing schema collections.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data and Schema

  • Run the failing INSERT/UPDATE statement in isolation using SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance to capture the exact %ls value reported in the error message.
  • Query the schema collection in use with: SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Cross-reference the failing value against the <xs:simpleType> or <xs:restriction> definitions (base type, pattern, enumeration) in the retrieved XSD output.

Step 2: Correct the Data Format or Type Mismatch

  • Adjust the source application or ETL process to format values according to the XSD-defined type (e.g., ensure dates are YYYY-MM-DD for xs:date, booleans are lowercase true/false, not 1/0 or True).
  • For numeric types, verify no thousands separators or currency symbols are present in the XML payload.
  • Re-test the insert using a minimal XML sample in SSMS: DECLARE @x XML(YourSchemaCollection) = '<Root><Value>123</Value></Root>';

Step 3: Repair or Update the XML Schema Collection

  • If the schema itself is outdated or too strict, drop and recreate it using DROP XML SCHEMA COLLECTION YourSchemaCollectionName; followed by CREATE XML SCHEMA COLLECTION with the corrected XSD definition.
  • Store the updated XSD file in a version-controlled location (e.g., C:\SQLSchemas\YourApp\schema_v2.xsd on the Windows Server 2025 host) for change tracking.
  • Ensure the SQL Server service account has read access to any referenced external XSD import paths if schemas use xs:import or xs:include.

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Open Windows Update or check the SQL Server Installation Center on Windows Server 2025 / Windows 11 for pending Cumulative Updates (CUs), as XML validation engine fixes are periodically released.
  • Verify current build version with: SELECT @@VERSION; and compare against Microsoft’s latest CU release notes for SQL Server 2025.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after applying any update.

Alternative or Verification Steps

  • Verify the fix by re-running the original failing transaction and confirming no Error 6927 appears in the SQL Server Error Log (Get-Content "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG" -Tail 50 in PowerShell).
  • As an alternative, if strict validation is not business-critical, temporarily store the data as untyped XML (without a schema collection binding) and apply validation at the application layer instead.

How to fix Error 6928 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6928 – XML Content Model Ambiguity

Why This Error Happens

This error occurs because the XML Schema Collection (XSC) registered in SQL Server contains a content model or group that is ambiguous under the W3C XML Schema specification, meaning the parser cannot deterministically validate instances against it (a violation of the Unique Particle Attribution rule). This typically happens when an XSD file imported into SQL Server 2025 uses overlapping <xs:choice> or <xs:sequence> elements with optional/wildcard elements that overlap in namespace or name. It can also surface after an in-place upgrade to SQL Server 2025, as the updated XML parser engine enforces stricter W3C compliance checks than legacy versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate the problematic schema collection referenced in the error log:
  SELECT name, xml_schema_namespace, schema_collection_id 
  FROM sys.xml_schema_collections 
  WHERE name = '%ls';
  • Check the SQL Server Error Log (via C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) to confirm the exact Schema Collection ID triggering Error 6928.

Step 2: Export and Analyze the XSD Definition

  • Extract the raw XML Schema definition using:
  SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Look for <xs:choice> blocks containing a wildcard (<xs:any>) alongside named elements, or two <xs:sequence> groups with identical starting elements—this is the most common cause of the “multiple ways” validation conflict.
  • Use an external validator (like Visual Studio 2025‘s XML Schema Explorer or xmllint --schema) to pinpoint the specific line causing the ambiguity.

Step 3: Correct the Content Model and Re-import

  • Modify the XSD to remove ambiguity. Replace ambiguous <xs:choice> groups with a strict <xs:sequence> or add a minOccurs="0" constraint with a distinct discriminator element.
  • Drop the old, corrupted collection and create a new one with the fixed schema:
  DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  GO
  CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS 
  N'<Insert Corrected XSD Content Here>';
  GO

Step 4: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 and restart the SQL Server (MSSQLSERVER) service to clear the cached execution plans associated with the old, invalid schema.
  • Alternatively, run DBCC FREEPROCCACHE; to ensure no stale query plans attempt to reference the dropped schema ID.

Alternative or Verification Steps

  • Verification: Re-run the INSERT or UPDATE statement that originally triggered Error 6928 against the xml typed column; it should now process without throwing a validation exception.
  • Alternative Fix: If modifying the vendor-provided XSD is not possible, consider converting the target column from a Typed XML (bound to the schema collection) to Untyped XML via ALTER TABLE YourTable ALTER COLUMN YourXMLColumn XML; to bypass strict validation entirely (note: this sacrifices schema enforcement).

How to fix Error 6925 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6925 – Invalid Definition for Element in XML Schema Collection

Why This Error Happens

This error occurs because SQL Server 2025 enforces strict XSD validation rules that prohibit modifying existing substitution groups through an ALTER XML SCHEMA COLLECTION statement. When a schema update attempts to add a new element to a substitution group head that was already registered in the original CREATE XML SCHEMA COLLECTION, the SQL Server XML engine rejects the operation to preserve schema integrity and prevent validation conflicts with existing XML-typed columns. This is a design limitation rather than a bug, meaning the fix requires a structural workaround rather than a configuration patch.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Substitution Group

  • Query sys.xml_schema_collections and sys.xml_schema_components to locate the schema collection referenced in the error message.
  • Run SELECT xml_schema_namespace(N'dbo', N'YourCollectionName') to extract the current schema definition as text.
  • Note the specific %ls element name reported in the error and cross-reference it against the <xs:element substitutionGroup="..."> attribute in the extracted XSD.

Step 2: Drop and Recreate the Schema Collection (Instead of Altering)

  • Since ALTER XML SCHEMA COLLECTION cannot add members to a substitution group, you must use CREATE XML SCHEMA COLLECTION with a temporary name instead.
  • Export all dependent objects (tables, stored procedures, functions) that reference the existing collection using SQL Server Management Studio’s “Script Table As” feature.
  • Execute: CREATE XML SCHEMA COLLECTION dbo.TempSchemaCollection AS N'<full XSD including new substitution group member>'.
  • Verify the new collection compiles successfully before proceeding.

Step 3: Migrate Columns to the New Schema Collection

  • For every table column typed with the old collection, run: ALTER TABLE YourTable ALTER COLUMN YourXmlColumn XML (dbo.TempSchemaCollection).
  • This operation implicitly re-validates existing XML data against the new schema, so monitor for Error 6926 (invalid instance data) during migration.
  • Once all columns, parameters, and variables reference the new collection, drop the old one: DROP XML SCHEMA COLLECTION dbo.OldSchemaCollection.

Step 4: Rename the Collection to Match Original References

  • Use sp_rename cautiously or re-create any stored procedures/functions that explicitly call out dbo.OldSchemaCollection by name, updating them to dbo.TempSchemaCollection.
  • Rebuild any CLR assemblies or application-layer DAL code that hard-codes the schema collection name in connection strings or XML serialization attributes.

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM sys.xml_schema_collections WHERE name = 'TempSchemaCollection' and confirming the substitution group members via xml_schema_namespace() include the newly added element.
  • Alternative approach: If migration is too risky on a production system, maintain the new element in a separate, independent XML Schema Collection and use application-layer logic (or a UNION-based XML wrapper) to validate against both collections rather than merging substitution groups at the database engine level.

How to fix Error 6926 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6926 – XML Validation: Invalid Simple Type Value

Why This Error Happens

Error 6926 occurs when SQL Server’s XML schema collection (XSD) validator encounters a value in an XML instance that does not conform to the simple type definition (such as xs:int, xs:date, or a custom restriction pattern) specified in the associated XML Schema Collection. This typically happens due to a mismatch between the data format being inserted and the strict type constraints (like minInclusive, pattern, or enumeration) defined in the schema, often caused by application-layer data corruption, locale/culture mismatches (e.g., date formats), or an outdated schema collection that doesn’t match the incoming data structure. Additionally, corrupted XSD files imported into the collection can cause the internal parser to reject otherwise valid-looking data.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection and Column

  • Run the following query to locate which column is bound to a strict XML Schema Collection: SELECT name, XML_COLLECTION_PROPERTY(xml_collection_id, 'Name') FROM sys.columns WHERE xml_collection_id <> 0;
  • Check the specific error message string (%s) logged in the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to identify the exact invalid value.

Step 2: Validate the XML Data Format Manually

  • Export the XSD schema using SELECT xml_schema_namespace('dbo', 'YourSchemaCollectionName'); and open it in Visual Studio 2025 or VS Code with an XML extension.
  • Compare the data type restrictions (e.g., xs:date requiring YYYY-MM-DD) against the actual value causing the failure; look specifically for regional date/time discrepancies (e.g., MM/DD/YYYY vs. DD-MM-YYYY).
  • Use SET LANGUAGE us_english; in your session temporarily to rule out locale-based parsing conflicts on Windows Server 2025 culture settings.

Step 3: Re-Register or Patch the XML Schema Collection

  • If the schema itself is outdated or corrupted, drop and recreate it using: ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName ADD 'C:\SchemaFixes\UpdatedSchema.xsd';
  • Ensure the SQL Server service account (running under Windows Server 2025) has Read/Execute NTFS permissions on the folder where the .xsd files are staged for import.

Step 4: Apply Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and verify your instance is running the latest Cumulative Update for SQL Server 2025, as early builds have known XML parser bugs regarding simple type coercion.
  • Check current build version via: SELECT @@VERSION; and compare against the latest build number on the official SQL Server release notes page.

Alternative or Verification Steps

  • Verification: Re-run the original INSERT or UPDATE statement that triggered the error; if successful, query sys.dm_exec_query_stats to confirm the execution plan no longer references a validation failure.
  • Alternative: If the strict schema is not business-critical, temporarily relax the constraint by altering the column to XML(CONTENT dbo.YourSchemaCollectionName) instead of XML(DOCUMENT ...), which allows for more flexible root-node validation while you resolve the underlying data type conflict.

How to fix Error 6923 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6923 occurs when SQL Server’s XML Schema Collection (XSD) validates an XML instance against a defined schema, and the parser encounters an element in the XML data that is not declared or expected at that position in the schema sequence. This typically happens due to a mismatch between the application’s XML output format and the schema registered in the database (often after a schema update) or because of incorrect element ordering, namespace mismatches, or an extra/optional field that wasn’t accounted for in the XSD definition. It can also surface after migrating databases to SQL Server 2025 if legacy XML Schema Collections weren’t updated to match new application payloads.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML and Schema Collection

  • Run the failing query/insert statement in SQL Server Management Studio (SSMS) to capture the full error message, noting the exact %s (unexpected element name) and %S_MSG (schema detail).
  • Query sys.xml_schema_collections to locate the specific schema collection bound to the column:
    SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Export the current schema definition using xml_schema_namespace function to compare it against the incoming XML payload.

Step 2: Compare XML Payload Against XSD Definition

  • Open the incoming XML data (from the application log or Profiler/Extended Events trace) and check the element causing the conflict.
  • Verify the sequence order inside the <xs:sequence> tags in the XSD; SQL Server XML validation is strict about ordinal placement unless <xs:all> is used.
  • Check for namespace prefix mismatches (e.g., xmlns:ns1 vs xmlns:ns2) that might cause the parser to flag a valid element as “unexpected.”

Step 3: Update or Alter the XML Schema Collection

  • If the application is sending new, valid data fields, update the schema rather than hardcoding a bypass:
    ALTER XML SCHEMA COLLECTION YourSchemaName ADD 'N<xs:schema>...</xs:schema>';
  • If the element is truly invalid (e.g., a bug in the sending application), roll back the application’s API version or XML serializer settings to match the expected contract.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 to clear any cached schema validation states if the ALTER command does not take effect immediately.

Step 4: Check for SQL Server 2025 Compatibility Changes

  • Verify the database compatibility level using SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';.
  • If recently upgraded from an older engine, ensure compatibility level is set to 170 (or the current 2025 level) to ensure the XML parser uses the correct validation engine: ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verification: Re-run the original INSERT/UPDATE transaction that triggered Error 6923; if successful, check sys.dm_exec_requests to confirm no blocking or parsing errors remain in the active session.
  • Alternative: If modifying the production schema collection is too risky, create a pre-processing stored procedure that strips or validates optional unexpected nodes using nodes() and value() XQuery methods before the data is inserted into the strictly-typed XML column.

How to fix Error 6924 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6924 – XML Validation Failure

Why This Error Happens

Error 6924 occurs when SQL Server’s XML parser validates a document against an XML Schema Collection and encounters text content inside an element or attribute that is defined as “attribute-only” (meaning the schema expects only attributes, with no mixed text content). This typically results from malformed XML being inserted into a column with an associated XML Schema Collection, an outdated or incorrect schema definition, or application code that incorrectly serializes XML data before sending it to SQL Server. It can also surface after upgrading to SQL Server 2025 if legacy XML data violates stricter schema validation rules introduced in the new engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data and Schema Collection

  • Run the failing query/procedure in SQL Server Management Studio (SSMS) to capture the full error text, including the %.*ls substituted value — this reveals the exact text string causing the violation.
  • Query sys.xml_schema_collections to locate the schema bound to the target column:
  SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;
  • Identify the specific complex type in the schema marked as attribute-only (no mixed="true" and no child text nodes allowed).

Step 2: Validate and Correct the XML Payload

  • Extract the problematic XML using a script or SELECT CAST(column AS NVARCHAR(MAX)) to view the raw content.
  • Check for stray text, whitespace, or CDATA sections inserted between XML tags that are declared as attribute-only in the XSD.
  • Strip or escape the invalid text nodes in the source application (e.g., C#, PowerShell, or ETL tool) before re-submitting the data.
  • If using SSIS or a data pipeline, verify the XML serializer isn’t injecting default text values into empty elements.

Step 3: Update or Re-Validate the XML Schema Collection

  • If the schema itself is outdated and should legitimately allow mixed content, modify it:
  ALTER XML SCHEMA COLLECTION SchemaCollectionName
  ADD 'XSD definition with mixed="true" where appropriate';
  • Alternatively, drop and recreate the schema collection with the corrected XSD file using CREATE XML SCHEMA COLLECTION.
  • Ensure the XSD file path is accessible from the SQL Server 2025 instance (local disk or UNC share with proper NTFS permissions for the SQL Service account).

Step 4: Re-Test the Insert/Update Operation

  • Re-run the original INSERT or UPDATE statement against the XML typed column.
  • Confirm SQL Server Error 6924 no longer appears in SSMS or the Windows Server 2025 Application Event Log (Event Viewer > Windows Logs > Application).

Alternative or Verification Steps

  • Verify the fix: Run SELECT * FROM sys.messages WHERE message_id = 6924 to confirm error text, then execute a test insert with a known-valid XML sample to confirm successful schema validation.
  • Alternative workaround: If immediate correction of the schema isn’t feasible, temporarily cast the column to untyped XML (XML without schema collection binding) to unblock data ingestion while the schema or source data is corrected offline.

How to fix Error 6921 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6921 – XML Validation Fixed Attribute Conflict

Why This Error Happens

Error 6921 occurs when SQL Server’s XML Schema Collection validator encounters an element or attribute that the XSD schema explicitly marked with a fixed constraint, but the XML instance data being inserted or validated contains a different value than the one specified as fixed. This typically happens after an application update introduces new XML payloads, a schema collection is altered incorrectly, or legacy data was inserted before the schema’s fixed constraint was applied. In SQL Server 2025 running on Windows Server 2025, this is frequently triggered by stricter XML parsing compliance introduced in the updated SQLOS engine, which now enforces fixed-value constraints more rigorously than in previous builds.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run SELECT name, definition FROM sys.xml_schema_collections to locate the schema tied to the affected table or column.
  • Cross-reference the %s placeholder in the error message with your XSD to find which element/attribute has the fixed attribute declared.
  • Use SELECT xml_schema_namespace(N'schema_name', N'collection_name') to extract the full schema definition for inspection.

Step 2: Correct the XML Instance Data or Schema Definition

  • Open the XML payload causing the failure and compare the conflicting value against the fixed="value" declaration in the XSD.
  • If the data is wrong, correct the source application or ETL process generating the XML to match the fixed value exactly (case-sensitive, including whitespace).
  • If the schema is overly restrictive, modify the XSD to use default instead of fixed, then redeploy using:
  ALTER XML SCHEMA COLLECTION [dbo].[YourCollection] ADD N'<xsd:schema>...</xsd:schema>'

Step 3: Validate and Reload the Schema Collection

  • Drop and recreate the schema collection if ALTER fails due to type conflicts:
  DROP XML SCHEMA COLLECTION [dbo].[YourCollection];
  CREATE XML SCHEMA COLLECTION [dbo].[YourCollection] AS N'<xsd:schema>...</xsd:schema>';
  • Re-run the original INSERT or UPDATE statement that triggered Error 6921 to confirm the schema now accepts the payload.

Step 4: Clear Cached Execution Plans (If Error Persists)

  • Execute DBCC FREEPROCCACHE to eliminate stale query plans referencing the old schema definition.
  • Restart the SQL Server service via services.msc on Windows Server 2025 only if the issue persists after cache clearing, ensuring minimal downtime by scheduling during a maintenance window.

Alternative or Verification Steps

  • Verify the fix by inserting a test XML document with the corrected fixed value using SELECT CAST('<YourXML/>' AS XML) against the schema-bound column — it should succeed without raising Error 6921.
  • If the error persists across multiple schema collections, consider exporting all affected XSDs, auditing them in a tool like Visual Studio’s XML Schema Designer, and re-importing a consolidated, validated version.

How to fix Error 6922 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6922 – XML Namespace Resolution Failure

Why This Error Happens

Error 6922 occurs when SQL Server’s XML parser encounters a namespace prefix in an XML document or schema that has not been properly declared or is out of scope at the point of reference. This typically happens due to malformed XML data being inserted into an XML-typed column, a missing or incorrectly registered XML Schema Collection (XSCHEMA), or a prefix typo that doesn’t match any xmlns: declaration in the document. In some cases, this is also triggered when an application constructs XML dynamically and fails to carry forward namespace context across concatenated fragments.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Document

  • Extract the exact XML payload being inserted or queried using SQL Server Profiler or Extended Events (filter on Error Number = 6922).
  • Check for the specific prefix named in the error message (e.g., ns1, soap, xsi) and confirm it has a corresponding xmlns:prefix="URI" declaration somewhere in the document hierarchy.
  • Use an external validator (e.g., xmllint --noout file.xml on Windows Server 2025 via WSL, or Visual Studio’s XML Editor) to catch malformed namespace scoping before it reaches SQL Server.

Step 2: Inspect and Repair the XML Schema Collection

  • Run the following query to list registered schema collections and their namespaces:
SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;
  • If the collection is missing the namespace referenced by the prefix, re-import the correct .xsd file using:
CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'<xsd content here>';
  • If the schema collection already exists but is outdated, drop and recreate it (ensure no columns are actively bound to it first, or use ALTER XML SCHEMA COLLECTION to add components instead).

Step 3: Correct the Application-Side XML Generation Logic

  • Review the application or ETL code (SSIS package, .NET XmlWriter, or ORM layer) generating the XML string before it is sent to SQL Server.
  • Ensure namespace declarations are placed on the root element or the specific node where the prefix is first used, not only on a child fragment that gets concatenated separately.
  • If using FOR XML PATH or FOR XML EXPLICIT in T-SQL, explicitly declare the WITH XMLNAMESPACES clause at the top of the query:
WITH XMLNAMESPACES ('http://example.com/ns' AS ns1)
SELECT ... FOR XML PATH('root');

Step 4: Clear Cached Execution Plans (If Applicable)

  • If the XML schema was recently updated but the error persists, stale cached plans referencing the old schema definition may be the cause.
  • Run DBCC FREEPROCCACHE (in a controlled maintenance window) or use sp_recompile on the specific stored procedure/table handling the XML data.

Alternative or Verification Steps

  • Verify the fix by re-running the original insert/query that triggered Error 6922 and confirming it completes without exception; additionally, query sys.dm_exec_query_stats to confirm no residual bad plans are being reused.
  • As an alternative, if the XML source is untrusted or third-party, consider relaxing validation by storing the data in an untyped XML column (without a schema collection binding) temporarily, then validate/transform it via a staging process before promoting it to a schema-validated column.

How to fix Error 6919 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6919 – XML Validation Abstract Type Error

Why This Error Happens

This error occurs when SQL Server attempts to validate an XML instance against an XML Schema Collection (XSD) where the target element is defined as abstract="true". Abstract types in XML Schema cannot be instantiated directly—they exist only to be extended or restricted by other derived types. When client applications, ETL packages, or stored procedures insert XML data into a column typed with an XML(SCHEMA COLLECTION) without explicitly declaring the xsi:type attribute, SQL Server’s XML parser rejects the data because it cannot determine which concrete derived type to use for validation.

Step-by-Step Resolution Guide

Step 1: Identify the Abstract Element in the Schema Collection

  • Run the following query to locate the schema collection bound to your XML column:
SELECT xsc.name, xsc.xml_schema_namespace, c.name AS column_name
FROM sys.xml_schema_collections xsc
JOIN sys.columns c ON c.xml_collection_id = xsc.xml_collection_id
WHERE xsc.name = 'YourSchemaCollectionName';
  • Export the schema using SELECT xml_schema_namespace('dbo', 'YourSchemaCollectionName'); and inspect it for abstract="true" attributes on <xs:complexType> or <xs:element> definitions.
  • Note the exact element name referenced in the error message (%s), as this is the abstract type causing the failure.

Step 2: Modify the XML Instance to Include xsi:type

  • Update the source XML payload (from your application, SSIS package, or API) to explicitly declare the derived non-abstract type using the xsi:type attribute.
  • Example correction:
<Payment xsi:type="CreditCardPayment" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <CardNumber>XXXX-XXXX-XXXX-1234</CardNumber>
</Payment>
  • Ensure the xmlns:xsi namespace declaration is present in the XML instance; missing namespace declarations will cause a separate parsing error.
  • If using SSIS, update the Data Flow XML Source task or Script Component to inject this attribute dynamically before the insert.

Step 3: Validate and Rebuild the XML Schema Collection (If Schema is Faulty)

  • If the abstract type was unintentionally set during schema design, alter the schema collection to remove the abstract="true" flag:
ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
ADD '<xs:schema>...corrected schema without abstract flag...</xs:schema>';
  • Alternatively, drop and recreate the collection entirely if ALTER fails due to type conflicts:
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS '...';
  • Restart the SQL Server service via services.msc on Windows Server 2025 only if schema cache corruption is suspected (rare, but clears stale metadata).

Step 4: Re-Test the Insert Operation

  • Re-run the original INSERT or UPDATE statement that triggered Error 6919.
  • Check SQL Server Error Logs via EXEC sp_readerrorlog 0, 1, 'xsi:type'; to confirm no recurrence of Error 6919.

Alternative or Verification Steps

  • Verify the fix: Execute a test insert with a known-good XML payload containing the correct xsi:type attribute and confirm it succeeds without throwing Error 6919.
  • Alternative workaround: If modifying every client payload is impractical, consider changing the column to untyped XML (without schema collection binding) if strict validation isn’t a business requirement, though this sacrifices data integrity checks at the database layer.

How to fix Error 6920 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6920 — Invalid XML Schema Collection Definition

Why This Error Happens

Error 6920 occurs when SQL Server 2025 attempts to register or alter an XML Schema Collection that contains a malformed xs:restriction definition. Specifically, an attribute is declared with use="prohibited" in a derived complex type, but that same attribute does not exist in the base type it is supposedly restricting. This is almost always caused by a hand-edited or improperly generated XSD file being imported into SQL Server, rather than a SQL Server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Locate and Isolate the Offending XSD File

  • Identify which CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement triggered the error by checking the SQL Server error log or the query that failed.
  • Export the raw XSD content to a local file for inspection:
  SELECT xml_schema_namespace('YourSchemaName', 'YourSchemaCollectionName');
  • Save the output to a .xsd file (e.g., C:\Temp\schema_review.xsd) using SQL Server Management Studio (SSMS).

Step 2: Validate the XSD Against W3C Schema Rules

  • Open the .xsd file in Visual Studio 2022/2025 or an XML editor with schema validation support.
  • Search for any <xs:attribute name="..." use="prohibited" /> entries inside <xs:restriction base="..."> blocks.
  • Confirm whether the attribute referenced actually exists in the parent/base complex type definition — if it does not exist there, use="prohibited" is invalid and must be removed or corrected.
  • Cross-check the base type hierarchy by tracing base="..." attributes up through all parent complexType definitions in the file.

Step 3: Correct the Schema and Re-import

  • Edit the XSD so the prohibited attribute either matches an attribute that genuinely exists in the base type, or remove the use="prohibited" declaration entirely if it is not needed.
  • Drop and recreate the schema collection with the corrected file:
  DROP XML SCHEMA COLLECTION YourSchemaName.YourSchemaCollectionName;
  GO
  CREATE XML SCHEMA COLLECTION YourSchemaName.YourSchemaCollectionName
  AS N'<paste corrected XSD content here>';
  GO
  • If the schema is deployed via a .dacpac or deployment script, update the source file in your project (e.g., SSDT/Visual Studio) to prevent the issue from recurring on future deployments.

Step 4: Check for Third-Party or Auto-Generated Schema Sources

  • If the XSD was auto-generated (e.g., exported from an external ERP system, SOAP WSDL, or XML tool), check for a newer version of that tool or export utility, as this is a common source of malformed restriction blocks.
  • Re-export or regenerate the schema from the source system rather than manually patching it, when possible.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE/ALTER XML SCHEMA COLLECTION statement and confirming it completes without Error 6920, then test any stored procedures or columns typed against that schema collection with sample XML data.
  • As an alternative, use an independent XSD validator (such as xmllint --schema on Windows via WSL, or the .NET XmlSchemaSet class in a PowerShell script) to pre-validate the XSD file before importing it into SQL Server, catching structural errors earlier in the pipeline.

How to fix Error 6917 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6917 — XML Validation xsi:nil Constraint Violation

Why This Error Happens

This error occurs when an XML document being validated against an XML Schema Collection (XSD) in SQL Server 2025 contains an element with xsi:nil="true", but that element’s schema definition does not explicitly include nillable="true". SQL Server’s native XML validation engine strictly enforces XSD rules, so any attempt to insert a null-marked element without the corresponding schema permission will be rejected. This is commonly caused by mismatched schema versions, a manually edited XSD, or client applications generating XML using a different schema template than the one registered in the database.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Element and Schema Collection

  • Run the failing query/insert again and capture the full error message, noting the %ls element name returned in the error text.
  • Query sys.xml_schema_collections to locate the schema collection bound to the target XML column:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Use SELECT XML_SCHEMA_NAMESPACE('dbo','YourSchemaName') to extract the current raw XSD definition for inspection.

Step 2: Update the XSD to Allow Nillable Elements

  • Open the extracted XSD in a text editor or Visual Studio XML editor.
  • Locate the <xs:element> tag matching the name identified in Step 1.
  • Add the nillable="true" attribute explicitly:
  <xs:element name="YourElementName" type="xs:string" nillable="true" />
  • If the element carries a fixed constraint (e.g., fixed="SomeValue"), remove or relax the fixed attribute, since fixed-value elements can never legally accept xsi:nil="true".

Step 3: Drop and Recreate the XML Schema Collection

  • Since ALTER XML SCHEMA COLLECTION only supports additive changes, you must drop and recreate the collection if the element already exists:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaName;
  GO
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaName AS N'<Paste Updated XSD Here>';
  • Re-bind the schema collection to the relevant table column if it was temporarily unbound during recreation.

Step 4: Validate the Source XML Payload

  • Inspect the XML document generated by the client application (e.g., via SSIS, .NET XmlSerializer, or a REST API payload) to confirm it isn’t incorrectly inserting xsi:nil="true" on required or fixed-value fields.
  • Update the client-side serialization logic or XML generation template to only emit xsi:nil="true" for fields that are genuinely optional in the business logic.

Step 5: Restart Dependent Services (If Using SSIS/SSRS Integration)

  • If the XML validation is invoked via SQL Server Integration Services (SSIS) or Reporting Services on Windows Server 2025, restart the respective service to clear any cached schema metadata:
  Restart-Service -Name "MsDtsServer160"
  Restart-Service -Name "SQLServerReportingServices"

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement containing the XML payload — a successful commit with no Error 6917 confirms the schema update resolved the nillable constraint.
  • As a quick alternative verification, use dbo.YourTable.XMLColumn.exist('/Element[@xsi:nil="true"]') in a SELECT statement to confirm the server now accepts nil-marked nodes without throwing a validation exception.

How to fix Error 6918 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6918 – XML Validation Error

Why This Error Happens

Error 6918 occurs when SQL Server’s XML parser validates data against an XML Schema Collection (XSD) and finds that an element defined as “empty” or “complex-only” contains unexpected text or nested child elements. This typically results from malformed XML being inserted into a typed xml column, a mismatch between the application’s XML output and the registered schema collection, or a schema collection that was altered/upgraded incorrectly during a migration to SQL Server 2025. In rare cases, corruption in the sys.xml_schema_collections metadata on Windows Server 2025 instances after an in-place OS upgrade can also trigger this validation failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Document and Schema Collection

  • Run SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; to confirm the schema is correctly registered.
  • Capture the exact XML payload causing the failure by enabling XEvents on error_reported filtered to error number 6918.
  • Note the specific %s element name returned in the error message — this tells you which XSD element is being violated.

Step 2: Validate the XML Against the XSD Manually

  • Export the XSD definition using SELECT xml_schema_namespace('dbo','YourSchemaName');.
  • Use an external validator (e.g., Visual Studio XML Editor or xmllint --schema schema.xsd data.xml) to pinpoint whether the element is incorrectly defined as nillable or complexType with mixed="false".
  • Correct the source application code (e.g., .NET XmlSerializer or SSIS package) so it does not inject whitespace, comments, or text nodes into elements declared as child-only or empty.

Step 3: Re-register or Patch the Schema Collection

  • If the schema itself is outdated, update it using:
  ALTER XML SCHEMA COLLECTION dbo.YourSchemaName ADD '<xsd:schema>...corrected definition...</xsd:schema>';
  • Ensure the SQL Server 2025 instance has the latest Cumulative Update applied (SELECT @@VERSION;), as early 2025 builds had a known XML parser regression (tracked internally, fixed in CU2).
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator on Windows Server 2025) after applying the update.

Step 4: Re-test the Insert/Update Operation

  • Re-run the original INSERT/UPDATE statement that triggered the 6918 error.
  • Check sys.dm_exec_requests and the SQL Server error log (EXEC xp_readerrorlog 0, 1, N'6918';) to confirm no further validation failures occur.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(YourXmlColumn AS xml).value('(/Root/Element)[1]','varchar(100)') FROM YourTable; — it should return without throwing error 6918.
  • If the error persists, temporarily drop the xml typed constraint (ALTER TABLE YourTable ALTER COLUMN YourXmlColumn XML; without schema binding) to isolate whether the issue is schema-related or data-related, then re-bind once the source XML is corrected.

How to fix Error 6915 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6915 – “Element or Attribute Name Too Long”

Why This Error Happens

Error 6915 occurs when SQL Server’s XML parser encounters an element or attribute name that exceeds the maximum allowed length (typically 128 characters) during XML data type operations, such as parsing, shredding, or querying with XQuery/XPath expressions. This is commonly triggered by malformed or dynamically generated XML—often from external data feeds, corrupted export files, or application code that concatenates excessively long tag names. It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schema collections or stored procedures contain non-standard or auto-generated node names that were never validated against current parser limits.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Offending XML

  • Check SQL Server Error Logs via SQL Server Management Studio (SSMS) > Management > SQL Server Logs for the exact query or procedure that triggered Error 6915.
  • Run SELECT * FROM sys.dm_exec_query_stats cross-referenced with sys.dm_exec_sql_text to pinpoint the exact batch or stored procedure handling the XML.
  • If the XML originates from an external file, inspect it using a text editor or Get-Content in PowerShell to manually scan for unusually long tags.

Step 2: Validate and Sanitize the XML Input

  • Use an XML validation tool or a PowerShell script with [xml]$doc = Get-Content "C:\Data\input.xml" to load and inspect the document structure programmatically.
  • Write a pre-processing script (PowerShell or SSIS) to truncate or rename any element/attribute names exceeding 128 characters before ingestion into SQL Server.
  • If the data comes from a third-party API or application, contact the vendor to confirm compliance with standard XML naming conventions (NCName limits).

Step 3: Update XML Schema Collections and Stored Procedures

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Types > XML Schema Collections in SSMS and review any custom schemas for legacy long-name definitions.
  • Run ALTER XML SCHEMA COLLECTION to update constraints if the schema itself defines overly long element names.
  • Refactor any stored procedures using OPENXML or .nodes()/.value() XQuery methods to include input length validation using LEN() checks prior to XML parsing.

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Configuration Manager to confirm your current build version.
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as early 2025 builds have known XML parser edge-case bugs that were patched in subsequent releases.
  • Reboot the Windows Server 2025 / Windows 11 instance after installation to ensure the SQL Server service binaries are fully refreshed.

Alternative or Verification Steps

  • After applying fixes, re-run the original query or import job in a test environment using SET STATISTICS XML ON to confirm the XML parses without throwing Error 6915.
  • If the issue persists, as a workaround, cast the XML column to NVARCHAR(MAX) first, perform string-based truncation on the long tag names using REPLACE() or PATINDEX(), and then re-cast it back to the XML data type before final processing.

How to fix Error 6916 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6916 – XML Content Model Ambiguity

Why This Error Happens

Error 6916 occurs when SQL Server attempts to parse or validate an XML Schema Collection (XSD) that contains a content model or model group violating the W3C XML Schema “Unique Particle Attribution” (UPA) constraint. This typically happens when a schema defines overlapping element declarations within a choice, sequence, or all group, making it impossible for the parser to deterministically distinguish which particle an incoming XML element should match. It is almost always caused by a malformed or hand-edited XSD being registered via CREATE XML SCHEMA COLLECTION, rather than a SQL Server engine fault itself.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run SELECT name, xml_schema_namespace, definition FROM sys.xml_schema_collections; to locate the schema collection referenced in the error.
  • Export the full XSD definition to a .xsd file using SSMS or SELECT xc.definition FROM sys.xml_schema_collections xc WHERE name = 'YourSchemaName';.
  • Note the exact type or model group name reported in the %s placeholder of the error message.

Step 2: Validate the XSD Using an External Parser

  • Open the exported .xsd file in Visual Studio 2022+ or use the xmllint --schema command-line tool on Windows Server 2025.
  • Look specifically for <xs:choice> or <xs:sequence> blocks where two or more elements share the same name but different types, or where optional elements with minOccurs="0" overlap with wildcard (<xs:any>) declarations.
  • Correct the ambiguity by renaming conflicting elements, merging duplicate type definitions, or restructuring the choice/sequence group so each particle is uniquely distinguishable on the first token.

Step 3: Drop and Recreate the Schema Collection

  • Since XML Schema Collections are immutable in SQL Server 2025, you cannot patch them in place; you must drop and recreate.
  • Run DROP XML SCHEMA COLLECTION [SchemaName]; (ensure no dependent XML columns or variables are actively bound first).
  • Recreate it with the corrected XSD: CREATE XML SCHEMA COLLECTION [SchemaName] AS N'<corrected XSD content here>';

Step 4: Rebind Dependent Objects

  • If any table columns, stored procedures, or CLR types referenced the old schema collection, re-validate them by running ALTER TABLE to re-point the XML column typing if needed.
  • Recompile affected stored procedures using EXEC sp_recompile 'YourProcedureName'; to clear cached execution plans tied to the old schema.

Alternative or Verification Steps

  • Verify the fix by inserting a sample XML document that previously failed: DECLARE @x XML(SchemaName); SET @x = '<test XML>'; — if no error is thrown, the UPA conflict is resolved.
  • If the schema originates from a third-party vendor (e.g., an ERP or B2B integration), as an alternative, use WITH (DOCUMENT) instead of strict typed XML to bypass validation until the vendor supplies a corrected XSD.

How to fix Error 6913 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6913 occurs when SQL Server’s XML parser attempts to validate an XML instance against an XML Schema Collection (XSC) but cannot locate a matching element or type declaration within that schema. This typically happens due to a mismatched or incomplete XML Schema Collection, a missing namespace binding in the XML document, or schema drift caused by an application update that introduced new XML elements without a corresponding schema migration. Corrupted or partially imported schema collections in the sys.xml_schema_collections catalog can also trigger this validation failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate schema collections tied to the affected column or variable:
SELECT name, schema_id, xml_schema_namespace 
FROM sys.xml_schema_collections;
  • Cross-reference the element name from the %s placeholder in the error message against the collection’s declared elements.
  • Use SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName') to dump the raw schema and inspect declarations.

Step 2: Validate and Repair the XML Document Source

  • Check whether the application layer is sending an XML document with a namespace prefix that doesn’t match any targetNamespace in the registered schema collection.
  • Open the source XML in a validator (e.g., Visual Studio XML Editor or xmllint on Windows Subsystem for Linux) and confirm every element has a corresponding <xs:element> declaration.
  • If the application was recently updated, compare the new XML payload structure against the schema version currently loaded in SQL Server.

Step 3: Update or Re-Import the XML Schema Collection

  • If the schema is outdated, alter it to include the missing element declaration:
ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
ADD N'<xs:schema>...updated declaration...</xs:schema>';
  • For severely corrupted collections, drop and recreate it entirely (ensure no dependent columns/tables are using it first):
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'...full schema...';

Step 4: Restart the Affected SQL Service (If Caching Is Suspected)

  • On Windows Server 2025 / Windows 11, open Services.msc and restart SQL Server (MSSQLSERVER) to clear any cached schema metadata.
  • Alternatively, run DBCC FREEPROCCACHE to flush compiled plans referencing the old schema.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement or application transaction that triggered Error 6913; if it completes without the XML Validation error, the schema fix is confirmed.
  • If the error persists, enable XML schema validation debugging via SQL Server Profiler (filter on Error/Warning events) to capture the exact failing element and namespace for deeper comparison against the XSD source file.

How to fix Error 6914 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6914 – XML Validation Type Definition Not Found

Why This Error Happens

This error occurs when SQL Server attempts to validate an XML instance against a schema collection (XML Schema Collection), but the specific type definition referenced is missing, unregistered, or was never properly imported into the target XML Schema Collection. This commonly happens when a schema component is dropped, partially migrated, or when the XML data references a namespace/type that doesn’t exist in the currently bound collection. It can also surface after a database restore or migration where schema collections were not fully transferred along with dependent objects.

Step-by-Step Resolution Guide

Step 1: Verify the XML Schema Collection Exists

  • Run the following query to confirm the schema collection is present in the target database:
  • SELECT name, xml_schema_namespace FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • If no rows return, the collection was never created or was dropped during a migration/restore.

Step 2: Inspect the Schema Collection Contents

  • Extract and review the actual XSD content to confirm the missing type is defined:
  • SELECT xml_schema_namespace.* FROM sys.xml_schema_collections CROSS APPLY (SELECT CAST(xml_schema_namespace AS XML) AS content) xml_schema_namespace WHERE name = 'YourSchemaCollectionName';
  • Confirm the <xs:complexType> or <xs:simpleType> matching the error’s reported type name is actually present in the XSD definition.

Step 3: Re-Import or Repair the Schema Collection

  • If the type is missing, drop and recreate the collection with the corrected XSD file:
  • DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  • CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS N'<path or inline XSD content>';
  • Ensure the XSD file used for import is the complete, unmodified version matching the original application schema (check with the vendor or source control for Windows Server 2025 deployment packages).

Step 4: Check for Namespace Mismatches

  • Open the XML instance causing the error and confirm the xmlns declaration matches exactly (case-sensitive) the namespace registered in the schema collection.
  • Correct any mismatched namespace URIs in the application code or XML payload before re-submitting the insert/update operation.

Step 5: Rebuild Dependent Objects

  • If the schema collection is used by typed XML columns, drop and recreate those column bindings after the schema fix:
  • ALTER TABLE YourTable ALTER COLUMN XmlColumn XML (YourSchemaCollectionName);
  • Restart the SQL Server 2025 service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear cached schema validation plans.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement that triggered Error 6914 and confirm it completes without validation errors.
  • If the issue persists, temporarily remove the XML schema binding (ALTER TABLE ... ALTER COLUMN XmlColumn XML;) to isolate whether the problem is schema-related or data-related, then re-apply the typed binding once the correct XSD is confirmed.

How to fix Error 6911 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6911 – XML Validation Duplicate Element in All Content Model

Why This Error Happens

Error 6911 occurs when SQL Server 2025 attempts to validate an XML instance against a registered XML Schema Collection (XSC) that contains an <xs:all> content model definition with a duplicate child element reference. The W3C XML Schema specification strictly prohibits repeating the same element declaration within an all group, so when a schema is imported with this structural flaw—often due to a malformed or hand-edited .xsd file—SQL Server’s internal validator rejects it. This typically surfaces after a schema collection migration, an application update that pushed a new XSD version, or manual corruption of the schema metadata during an in-place upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE schema_id = SCHEMA_ID('dbo'); to list all registered collections in the affected database.
  • Cross-reference the collection name mentioned in the error message output (%s placeholder) with your application’s schema deployment scripts.
  • Use SELECT xml_schema_namespace(N'dbo', N'YourCollectionName'); to extract the raw XSD content for inspection.

Step 2: Inspect and Correct the XSD Definition

  • Open the extracted schema in a text editor or Visual Studio XML editor and locate the <xs:all> block.
  • Search for duplicate <xs:element name="..."> entries within the same all group — remove or merge the redundant declaration.
  • If the design genuinely requires repeating/multiple occurrences of that element, replace <xs:all> with <xs:sequence> or <xs:choice>, since only sequence/choice support maxOccurs greater than 1.

Step 3: Drop and Recreate the Schema Collection

  • Run DROP XML SCHEMA COLLECTION dbo.YourCollectionName; (ensure no dependent XML columns or variables are actively bound first).
  • Re-register the corrected schema using CREATE XML SCHEMA COLLECTION dbo.YourCollectionName AS N'<corrected XSD content>';
  • Re-link any typed XML columns or stored procedure parameters that referenced the old collection.

Step 4: Clear Cached Query Plans Referencing the Schema

  • Execute DBCC FREEPROCCACHE; or target a specific plan with DBCC FREEPROCCACHE (plan_handle); to purge stale execution plans tied to the old schema.
  • Restart the SQL Server service via services.msc on Windows Server 2025 only if the error persists after cache clearing.

Alternative or Verification Steps

  • Validate the fix by inserting a test XML document that previously triggered the error using INSERT INTO YourTable (XmlColumn) VALUES (CAST(N'<test XML>' AS XML)); — it should succeed without Error 6911.
  • If the error reappears, use an external XSD validator (e.g., xmllint --schema schema.xsd instance.xml) on Windows 11 to catch structural issues before re-importing the schema into SQL Server.

How to fix Error 6912 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6912 – XML Validation Error

Why This Error Happens

Error 6912 occurs when SQL Server’s XML parser encounters an element in a location where only text content is expected according to the schema collection (XSD) bound to the XML data type column. This typically happens due to a mismatch between the XML schema definition and the actual XML data being inserted or validated, often caused by an outdated or corrupted XML Schema Collection, improper nesting of elements, or application code sending malformed XML that violates the simpleContent/complexType restrictions defined in the schema. In SQL Server 2025, this can also surface after an in-place upgrade if legacy schema collections were not re-validated against the updated XML parser engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate schema collections bound to the table/column throwing the error:
  SELECT name, xml_collection_id 
  FROM sys.xml_schema_collections 
  WHERE schema_id = SCHEMA_ID('dbo');
  • Note the %s and %S_MSG placeholders from the actual error output in SQL Server Management Studio (SSMS) — these identify the exact element name and message context causing the violation.
  • Cross-reference the element name against the XSD definition to confirm whether it expects simpleType (text-only) content.

Step 2: Validate the XML Input Against the Schema

  • Extract the exact XML payload being inserted (use SQL Server Profiler or Extended Events on Errors and Warnings > User Error Message).
  • Open the XML in a validator (e.g., Visual Studio 2022+ XML Editor or xmllint on Windows via WSL) against the registered .xsd file.
  • Look specifically for child elements nested inside tags that are defined as <xs:simpleContent> — this is the most common trigger for Error 6912.

Step 3: Repair or Re-register the XML Schema Collection

  • If the schema collection is outdated, drop and recreate it:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  GO
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'<updated XSD content here>';
  • Ensure the updated .xsd file is stored in a version-controlled location (e.g., C:\SQLSchemas\Production\) to prevent future drift.
  • Restart the SQL Server 2025 service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025 to clear any cached schema validation plans.

Step 4: Correct the Source Application Code

  • Review the application or ETL pipeline (SSIS, Azure Data Factory, or custom .NET code) generating the XML payload.
  • Ensure any serialization logic (e.g., System.Xml.Serialization) is not injecting unexpected child nodes into elements marked as text-only in the XSD.
  • Redeploy the corrected application build and re-run the failing transaction.

Alternative or Verification Steps

  • To verify the fix, re-run the original INSERT/UPDATE statement or ETL job that triggered Error 6912 and confirm it completes without validation errors in SSMS or the SQL Server Error Log (Event Viewer > Windows Logs > Application, Event ID 6912 should no longer appear).
  • If the error persists after schema correction, as a temporary workaround, remove the XML Schema Collection binding from the column (ALTER TABLE ... ALTER COLUMN YourXmlColumn XML) to allow untyped XML storage while you finalize schema corrections offline.

How to fix Error 6908 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6908 – XML Validation Failure

Why This Error Happens

Error 6908 occurs when SQL Server 2025’s XML parser validates a typed XML column or variable against its assigned XML Schema Collection and finds that the document structure does not match the expected schema definition. This typically happens because the XML instance is missing a required root element, contains an unexpected element ordering, or references a namespace that does not align with the registered schema collection. It can also surface after a schema collection is altered or partially corrupted, causing valid-looking XML to fail validation against stale or mismatched schema metadata.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE schema_id = SCHEMA_ID('dbo'); to locate the schema collection bound to the affected column.
  • Cross-reference the column definition using SELECT name, xml_collection_id FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName');
  • Note the exact collection name reported in the error message alongside the %s placeholders.

Step 2: Extract and Compare the Schema Definition

  • Execute SELECT xml_schema_namespace('dbo','YourSchemaCollectionName'); to pull the live schema definition from SQL Server.
  • Compare this output against the XML document you are trying to insert or update, paying close attention to element names, sequence order, and namespace URIs (xmlns attributes).
  • Use a diff tool (like VS Code’s compare feature) to spot mismatched or missing <xs:element> entries causing the “Expected element(s)” mismatch.

Step 3: Correct the XML Instance or Update the Schema Collection

  • If the XML document is wrong, correct the element order/names in your application code or T-SQL insert statement to match the schema’s <xs:sequence> requirements.
  • If the schema itself is outdated, run ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName ADD '<xs:schema>...</xs:schema>'; to add the missing element definitions.
  • Restart the SQL Server 2025 service via services.msc on Windows Server 2025 only if the schema cache appears stale after the alteration.

Step 4: Rebuild Corrupted Schema Metadata (If Applicable)

  • If Step 2 reveals the stored schema collection itself appears truncated or corrupted, drop and recreate it using DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName; followed by a fresh CREATE XML SCHEMA COLLECTION statement using a verified .xsd file.
  • Store a backup copy of the correct .xsd file in C:\SQLSchemas\Backup\ on the Windows Server 2025 host for future recovery.

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT or UPDATE statement that triggered Error 6908; a successful execution with no validation error confirms resolution.
  • As an alternative, temporarily cast the column to untyped XML (CAST(YourColumn AS XML)) to confirm the document is well-formed XML before re-applying schema validation, isolating whether the issue is structural or schema-specific.

How to fix Error 6909 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6909 occurs when SQL Server’s XML schema validation engine encounters a text node (character data) in a location where the XML Schema Definition (XSD) only permits child elements or empty content. This typically happens when XML data being inserted into a column bound to an XML Schema Collection contains stray whitespace, mixed content, or misplaced text between tags that the schema marks as “element-only.” It can also surface after a corrupted or incorrectly registered schema collection is applied following a Windows Server 2025 / SQL Server 2025 upgrade, where stricter XML parsing rules are now enforced by default.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Document

  • Run the failing INSERT or UPDATE statement in isolation using SQL Server Management Studio (SSMS) connected to your instance.
  • Capture the exact XML payload using SELECT CAST(@xmlVariable AS NVARCHAR(MAX)) to inspect raw content.
  • Look for stray text, line breaks, or extra whitespace between closing and opening tags (e.g., <Root> text <Child>...).

Step 2: Validate Against the XML Schema Collection

  • Open a query window and run: SELECT name, definition FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Check the <xs:complexType> definitions for mixed="false" (the default), which explicitly disallows text nodes alongside child elements.
  • If business logic requires mixed content, alter the schema using: ALTER XML SCHEMA COLLECTION YourSchemaCollectionName ADD '<xs:complexType mixed="true">...'

Step 3: Clean and Resubmit the XML Payload

  • Strip extraneous whitespace/text nodes programmatically before submission using .value() or .nodes() XQuery methods to reconstruct a clean document.
  • On the application side (C#/.NET on Windows Server 2025), ensure XmlWriterSettings.Indent = false or sanitize output using XDocument.Parse(input, LoadOptions.None) to avoid injecting formatting text nodes.
  • Re-run the insert statement against the target XML-typed column.

Step 4: Rebuild the Schema Collection if Corrupted

  • If the schema collection itself appears corrupted (common after in-place upgrades to SQL Server 2025), drop and recreate it:
  • DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  • CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS 'C:\Schemas\YourSchema.xsd';
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear cached schema validation plans.

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM sys.dm_exec_query_stats combined with a test insert to confirm no Error 6909 is thrown and the row commits successfully.
  • As a fallback, temporarily cast the column to untyped XML (XML without schema binding) to confirm the payload itself is valid, then re-bind the schema once the mixed-content issue is resolved at the source.

How to fix Error 6910 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6910 — Invalid XML Schema Collection Definition (Union Type Restriction)

Why This Error Happens

This error occurs when a developer attempts to register or modify an XML Schema Collection (XSD) in SQL Server 2025 that contains a <xs:restriction> applied to a <xs:union> simple type. SQL Server’s XML schema validation engine explicitly does not support deriving restrictions from union types, as this falls outside the subset of the W3C XML Schema specification implemented by the Database Engine. The root cause is almost always a structurally non-compliant XSD file being passed to a CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement, often one imported from an external system or generated by a third-party schema design tool that does not account for SQL Server’s limited schema support.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection and Type

  • Run the following query to locate the schema collection name and owning schema referenced in the error:
  • SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE name = '<CollectionName>';
  • Extract the full XSD definition using SELECT xml_schema_namespace(N'dbo', N'<CollectionName>'); to inspect the raw markup.
  • Search the extracted XML for the specific %ls type name reported in Error 6910 — this pinpoints the exact complexType or simpleType causing the failure.

Step 2: Locate and Remove the Union-Based Restriction

  • Open the XSD file in a text editor (VS Code, Notepad++) or XML IDE on your Windows Server 2025 / Windows 11 machine.
  • Search for the pattern <xs:union memberTypes= combined with a sibling or parent <xs:restriction base= referencing that same union type.
  • Refactor the schema: instead of restricting a union type, redefine the type as a direct <xs:simpleType> with explicit <xs:enumeration> or <xs:pattern> facets against a single base type (e.g., xs:string or xs:integer).
  • Save the corrected file to a known path, for example: C:\SQLSchemas\CorrectedSchema.xsd.

Step 3: Re-import the Corrected Schema Collection

  • Drop the invalid collection if it was partially created: DROP XML SCHEMA COLLECTION dbo.<CollectionName>;
  • Re-create it using the corrected file via sqlcmd or SSMS:
  • CREATE XML SCHEMA COLLECTION dbo.<CollectionName> AS N'<paste corrected XSD content here>';
  • Alternatively, load from disk using PowerShell/sqlcmd variable substitution: sqlcmd -S <ServerName> -d <DatabaseName> -Q "CREATE XML SCHEMA COLLECTION dbo.<CollectionName> AS N'$(Get-Content C:\SQLSchemas\CorrectedSchema.xsd -Raw)'"

Step 4: Validate Dependent Objects

  • Check any tables or stored procedures that reference the old schema collection using SELECT * FROM sys.columns WHERE xml_collection_id = <ID>;
  • Rebind affected xml typed columns if the collection was dropped and recreated with a new xml_collection_id, using ALTER TABLE <TableName> ALTER COLUMN <ColumnName> XML (dbo.<CollectionName>);

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE/ALTER XML SCHEMA COLLECTION statement in a non-production database — if Error 6910 no longer appears and sys.xml_schema_collections shows the new entry, the schema is valid.
  • If refactoring the union restriction is not feasible, bypass SQL Server’s native XSD validation entirely by storing and validating the XML at the application layer (e.g., using .NET’s XmlSchemaSet or a Java XSD validator) and persist the data as untyped xml in SQL Server instead of binding it to a schema collection.

How to fix Error 6906 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6906 – XML Validation Attribute Missing

Why This Error Happens

Error 6906 occurs when SQL Server’s XML schema collection validator parses an XML document or schema (XSD) and finds that a required attribute defined in the schema is absent from the instance document. This is typically caused by a malformed or incomplete XML payload being inserted into an xml typed column that has a CONTENT or DOCUMENT XML Schema Collection bound to it, an outdated or corrupted XSD registered in the schema collection, or an application/ETL process generating XML that no longer matches the schema contract after an update. In SQL Server 2025 running on Windows Server 2025 or Windows 11, this can also surface after in-place upgrades if cached schema collection metadata becomes stale relative to the actual XSD definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Document and Attribute

  • Capture the full error message text, noting the %s placeholders — these resolve to the specific attribute name and element context.
  • Run the failing INSERT/UPDATE statement manually in SQL Server Management Studio (SSMS) to isolate the exact XML payload.
  • Use SELECT xml_column.query('.') or export the XML to a file to inspect it with a text editor or XML validator.

Step 2: Validate the XML Against the Registered Schema Collection

  • Query the current schema definition using:
  SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Compare the required attributes in the <xs:attribute use="required"> tags against the actual XML instance.
  • Identify any attribute present in the XSD as mandatory but missing in the source XML (common causes: trailing whitespace stripping, application serialization bugs, or truncated payloads).

Step 3: Correct the XML Source or Update the Schema Collection

  • If the application is generating invalid XML, fix the serialization logic (e.g., a .NET XmlSerializer class missing a required property) and redeploy.
  • If the schema itself is outdated, alter the XML Schema Collection:
  ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
  ADD 'C:\SQLSchemas\UpdatedSchema.xsd';
  • Ensure the .xsd file used for the ADD/CREATE statement is not corrupted — re-copy it from source control rather than a local cached version, especially after a Windows Server 2025 OS upgrade that may have reset file permissions or paths.

Step 4: Clear Cached Execution Plans Referencing the Schema

  • Stale plans can sometimes reference old schema collection IDs after an ALTER.
  • Run:
  DBCC FREEPROCCACHE;

(Use cautiously in production — prefer DBCC FREEPROCCACHE (plan_handle) for a targeted single-plan clear.)

  • Re-execute the original failing statement to confirm the schema collection update is now active.

Alternative or Verification Steps

  • Verify the fix by re-running the exact INSERT/UPDATE statement that originally threw Error 6906 — it should now complete without validation errors.
  • As an alternative, temporarily relax validation by casting the column to xml without schema binding (CAST(@xmlvar AS XML)) in a test environment to confirm the payload itself is otherwise well-formed, then re-apply schema binding once the root cause (bad data vs. bad schema) is confirmed.

How to fix Error 6907 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6907 – “Namespace URI too long”

Why This Error Happens

Error 6907 occurs when SQL Server’s XML parser encounters a namespace URI that exceeds the internal length limit enforced by the XML data type engine. This is typically caused by malformed or auto-generated XML documents (often from third-party integrations or BI tools) that embed excessively long or dynamically concatenated namespace strings. In some cases, it also surfaces due to corrupted XML schema collections (XSC) registered in the database that contain bloated or duplicated namespace declarations.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source

  • Capture the exact query or stored procedure throwing Error 6907 using SQL Server Profiler or Extended Events on Windows Server 2025.
  • Check the application layer (SSIS packages, Power BI connectors, or REST API payloads) for XML inputs with concatenated or auto-generated namespace URIs.
  • Run the following to inspect recent XML-related errors:
SELECT * FROM sys.messages WHERE message_id = 6907;

Step 2: Validate and Trim the Namespace URI

  • Open the source XML document and manually inspect the xmlns attributes for unusually long strings (typically over 4,000 characters).
  • Shorten or standardize the namespace URI to a conventional format, such as http://schemas.yourcompany.com/v1.
  • If the XML is generated programmatically (e.g., via C# XmlWriter or Python lxml), audit the code for string concatenation loops that may be appending data unintentionally into the namespace field.

Step 3: Repair or Rebuild XML Schema Collections

  • If the error originates from a registered XML Schema Collection (XSC), drop and recreate it with corrected namespace definitions:
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;
GO
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollection AS N'<schema>...corrected XML...</schema>';
GO
  • Ensure the new schema file is UTF-8 encoded and validated using an external tool (like xmllint or Visual Studio’s XML Schema Explorer) before re-import.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Navigate to Microsoft Update Catalog and verify you are running the latest Cumulative Update (CU) for SQL Server 2025, as early builds had a known buffer-handling bug related to the %.*ls string formatter in XML parsing.
  • Apply the update via Setup.exe /Action=Patch /AcceptSQLServerLicenseTerms /Quiet on the Windows Server 2025 host.
  • Restart the SQL Server service (MSSQLSERVER) after patching.

Alternative or Verification Steps

  • Verification: Re-run the original query or XML import process; monitor the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm Error 6907 no longer appears.
  • Alternative Fix: If the namespace length cannot be reduced at the source, convert the field to NVARCHAR(MAX) instead of native XML type for storage, and handle parsing/validation at the application layer using a library with configurable buffer limits (e.g., .NET’s XmlReaderSettings).

How to fix Error 6904 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6904 occurs when SQL Server’s XML parser encounters malformed XML data containing the same attribute name declared twice within a single element tag. This typically happens due to corrupted data during an INSERT/UPDATE operation, application-level string concatenation errors when building XML payloads, or encoding mismatches when importing XML from external sources like SSIS packages or linked servers. The underlying XML schema validation engine in SQL Server 2025 strictly enforces the W3C XML specification, which prohibits duplicate attributes within the same node.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Run the failing query in SSMS and capture the full error message, which includes the duplicate attribute name in the %s placeholder.
  • Check the application layer (C#, Java, or Python connector) generating the XML string for improper concatenation logic, especially in loops that append attributes dynamically.
  • Review SSIS package data flows or ETL scripts if the XML originates from bcp or BULK INSERT operations.

Step 2: Validate and Sanitize the XML Payload

  • Extract the offending XML string using SELECT and copy it into a validator tool like XML Notepad or an online XML linter to pinpoint the exact duplicate node.
  • Use SELECT TRY_CAST(@xmlVariable AS XML) in a T-SQL script to isolate which row or batch is causing the parsing failure before the full transaction runs.
  • Modify the source application code to use parameterized XML builders (e.g., XmlWriter in .NET) instead of manual string concatenation, which prevents duplicate attribute injection entirely.

Step 3: Adjust Schema Validation and Retry the Operation

  • If using an XML Schema Collection (XSD), open SQL Server Management Studio and navigate to Databases > [YourDB] > Programmability > Types > XML Schema Collections to ensure the schema definition doesn’t inadvertently allow duplicate keys.
  • Re-run the INSERT INTO TableName (XmlColumn) VALUES (@CleanedXml) statement with the sanitized data.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 only if the error persists due to a cached execution plan holding invalid schema metadata.

Alternative or Verification Steps

  • Verify the Fix: Execute SELECT * FROM sys.dm_exec_requests WHERE status = 'suspended' to confirm no XML parsing threads are hanging, then re-run the original query to ensure Error 6904 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • Alternative Solution: If the error persists despite cleaning the XML, bypass strict validation temporarily by casting the data as NVARCHAR(MAX) first, then use REPLACE() functions in T-SQL to strip duplicate attribute patterns via regex before casting back to the XML data type.

How to fix Error 6905 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6905 – XML Validation Attribute Error

Why This Error Happens

Error 6905 occurs when SQL Server’s XML schema validation engine encounters an attribute in an XML instance document that is not defined or permitted by the associated XML Schema Collection (XSCHEMA). This typically happens due to a mismatch between the XML data being inserted/validated and the schema definition, often caused by an outdated or incorrectly versioned XSD schema bound to the column. It can also result from application-side XML generation changes that were not synchronized with the database schema collection, or from a corrupted schema collection object within the database.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Attribute and Schema Collection

  • Run the failing query/statement again and capture the full error message, noting the specific attribute name (%s) referenced in the error.
  • Query the schema collection associated with the target XML column using:
  SELECT xsc.name, xs.* 
  FROM sys.xml_schema_collections xsc
  CROSS APPLY sys.xml_schema_namespaces xs
  WHERE xsc.xml_collection_id = (SELECT xml_collection_id FROM sys.columns WHERE name = 'YourXMLColumn');
  • Compare the attribute causing the error against the registered schema to confirm the mismatch.

Step 2: Update or Re-register the XML Schema Collection

  • If the schema is outdated, alter it using ALTER XML SCHEMA COLLECTION to add the missing attribute definition, or drop and recreate it if structural changes are required.
  • Example for adding to an existing collection:
  ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollection
  ADD '<xs:schema>...updated definition...</xs:schema>';
  • Ensure the new XSD file path (if loading from disk on Windows Server 2025, e.g., C:\SQLSchemas\updated_schema.xsd) is accessible by the SQL Server service account.

Step 3: Validate Application XML Output

  • On the application server (Windows 11/Windows Server 2025), check the XML generation logic (e.g., in .NET, Java, or middleware) to ensure it is not injecting deprecated or extra attributes not covered by the current schema version.
  • Update the application’s XML serializer or mapping configuration to align with the current XSD.

Step 4: Rebuild Corrupted Schema Collections (If Applicable)

  • If the schema collection object itself is suspected to be corrupted, drop it and reload it cleanly:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;
  • Reload using CREATE XML SCHEMA COLLECTION with a verified, clean XSD file to eliminate any internal metadata corruption.

Alternative or Verification Steps

  • After applying the fix, re-run the original INSERT/UPDATE statement or application transaction that triggered Error 6905 to confirm the XML now validates successfully against the schema collection.
  • As an alternative, if frequent schema mismatches occur, consider relaxing validation by using an untyped XML column instead of a typed one bound to a schema collection, provided business logic allows for looser validation constraints.

How to fix Error 6902 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6902 – Invalid XML Schema Collection Definition

Why This Error Happens

This error occurs when a user attempts to register an XML Schema Collection in SQL Server 2025 that applies a pattern or enumeration facet to a simple type derived as a list of xs:QName. SQL Server’s XML schema validation engine does not support restricting a QName list type using these facets, as this falls outside the subset of W3C XML Schema (XSD) features implemented by the SQL Server XML engine. The root cause is almost always a non-compliant or overly complex XSD file being passed to CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION, rather than a server configuration, permissions, or networking issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Component

  • Locate the .xsd file or inline schema string referenced in the failing CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement.
  • Search the schema for any <xs:simpleType> definitions where the base type is <xs:list itemType="xs:QName">.
  • Check if that same simple type definition includes a child <xs:restriction> block containing <xs:pattern .../> or <xs:enumeration .../> facets.
  • Use a text editor or XML IDE (such as Visual Studio Code with an XML extension) to quickly search for the string QName across all imported/included schema files, since the issue may be in a nested or imported schema, not just the top-level one.

Step 2: Modify the XSD to Remove Unsupported Facets

  • Edit the .xsd source file and remove the pattern or enumeration facet from the QName list restriction.
  • If validation logic is required, move that validation into application-layer code (e.g., a C# or Java pre-processing step) or into a SQL Server trigger/stored procedure that validates the XML data before insertion.
  • If the enumeration is meant to restrict a finite set of QName values, consider redesigning the type as a plain xs:string list with a CHECK constraint on the resulting column instead.
  • Save the corrected schema file, for example at C:\SQLSchemas\CorrectedSchema.xsd on Windows Server 2025.

Step 3: Re-register the Corrected Schema Collection

  • Connect to the instance using SQL Server Management Studio (SSMS) 21 or sqlcmd.
  • Run the corrected definition:
  CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection
  AS N'<paste corrected XSD content here>';
  • If updating an existing collection, use:
  ALTER XML SCHEMA COLLECTION dbo.MySchemaCollection
  ADD N'<paste corrected XSD content here>';
  • Confirm no error 6902 (or related XML validation errors) is returned in the Messages pane.

Step 4: Clear Cached Query Plans and Metadata (If Partial Registration Occurred)

  • If a prior failed attempt left partial metadata, run DBCC FREEPROCCACHE to clear any stale cached plans referencing the schema collection.
  • Restart the SQL Server 2025 service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) if the schema collection appears “stuck” in a bad state.

Alternative or Verification Steps

  • Verify the fix by querying sys.xml_schema_collections and sys.xml_schema_types to confirm the schema collection registered successfully and the problematic type no longer exists.
  • As an alternative, run the XSD through an independent, strict W3C XSD 1.1 validator (such as xmllint or the Oxygen XML Editor) before importing it into SQL Server — this helps catch unsupported constructs like QName-list pattern/enumeration facets early, before they cause Error 6902 during deployment.

How to fix Error 6903 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6903 – XML Schema Collection ID Attribute Validation Failure

Why This Error Happens

This error occurs when registering an XML Schema Collection in SQL Server 2025 that contains an attribute or element defined with the xs:ID type, which SQL Server’s XML validation engine explicitly does not support. SQL Server’s internal XML schema processor restricts certain W3C XML Schema constructs—including ID, IDREF, and IDREFS—because it cannot guarantee uniqueness constraints across document instances the way a native XML parser would. This is almost always a schema design issue introduced during migration, import, or third-party schema generation rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Component

  • Capture the full error message, which includes the type name in %ls (e.g., Invalid definition for type 'EmployeeRecordType').
  • Open the .xsd file or extract the schema using:
  SELECT xml_schema_namespace('YourSchema', 'YourCollectionName');
  • Search the output for attributes or elements declared with type="xs:ID", type="xs:IDREF", or type="xs:IDREFS".

Step 2: Modify the XML Schema Definition

  • Replace any xs:ID typed attribute with xs:string or xs:token instead, since SQL Server cannot enforce ID uniqueness natively.
  • Example fix:
  <!-- Unsupported -->
  <xs:attribute name="RecordID" type="xs:ID"/>

  <!-- Supported -->
  <xs:attribute name="RecordID" type="xs:string"/>
  • If uniqueness enforcement is required, implement it at the application layer or via a CHECK constraint/trigger after shredding the XML into relational columns.

Step 3: Drop and Re-Create the XML Schema Collection

  • Remove the old collection (ensure no columns/tables reference it first):
  DROP XML SCHEMA COLLECTION YourSchema.YourCollectionName;
  • Re-register the corrected schema:
  CREATE XML SCHEMA COLLECTION YourSchema.YourCollectionName AS N'<your corrected XSD content here>';
  • If the collection is referenced by existing typed XML columns, you will need to temporarily convert those columns to untyped XML, drop the collection, recreate it, then reapply the typed binding.

Step 4: Validate Dependent Objects

  • Check for stored procedures, functions, or table definitions that reference the schema collection using:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourCollectionName';
  • Recompile any dependent objects with sp_refreshsqlmodule to ensure they pick up the corrected schema binding.

Alternative or Verification Steps

  • Verify the fix: Re-run the original CREATE XML SCHEMA COLLECTION or ALTER statement that triggered Error 6903 — it should now complete without error, and you can confirm registration via SELECT name FROM sys.xml_schema_collections;.
  • Alternative workaround: If modifying the source XSD isn’t feasible (e.g., third-party generated schema), strip the xs:ID constraint programmatically using an XSLT transformation before importing the schema into SQL Server, preserving the field as a plain string type.

How to fix Error 6879 on Windows Server 2025 / Windows 11

Why This Error Happens

This error occurs when a T-SQL query attempts to use the PI() (processing instruction) function within a FOR XML clause to generate a node with the target name xml. SQL Server reserves this specific target name because it is interpreted as an attempt to manually construct an <?xml version="1.0"?> declaration rather than a standard processing instruction. Since the XML standard prohibits processing instructions from using the reserved target name “xml” (case-insensitive), SQL Server’s XML parser rejects the query at runtime to prevent the creation of malformed or non-compliant XML output.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Review the SQL Server error log or the specific batch that triggered Error 6879 in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Search the T-SQL statement for the use of the PI('xml', ...) function call, specifically looking for FOR XML PATH or FOR XML EXPLICIT clauses.
  • Check Application and System logs in Windows Event Viewer (eventvwr.msc) under “Windows Logs” to correlate the timestamp of the event ID with the specific database session.

Step 2: Modify the T-SQL Query Syntax

  • Locate the specific line of code generating the error, which will look similar to: SELECT PI('xml', 'version="1.0"') FOR XML PATH('').
  • Remove the PI('xml', ...) function call entirely, as SQL Server does not support programmatically injecting a standard XML declaration header via this method.
  • If you require a specific encoding or standalone declaration, handle this concatenation in the application layer (e.g., C# or PowerShell) after retrieving the raw XML string from SQL Server, rather than within the T-SQL query itself.

Step 3: Utilize Native XML Declaration Alternatives

  • If the goal is simply to generate valid XML with standard formatting, remove the manual PI constructor and rely on the FOR XML directive’s native output, which handles root elements correctly without a declaration by default.
  • For scenarios requiring the declaration, use the CAST function to prepend a static string: SELECT CAST('<?xml version="1.0"?>' AS XML) as a separate variable, then concatenate it with your FOR XML result set in the client application.
  • Restart the SQL Server service via the “Services” console (services.msc) on Windows Server 2025 only if the error persists due to a cached execution plan, though this is rarely required for a syntax-level fix.

Step 4: Update Database Compatibility Level

  • Open SSMS and right-click on the specific database throwing the error, then select “Properties.”
  • Navigate to the “Options” page and verify the “Compatibility Level” is set to SQL Server 2025 (170) to ensure you are using the latest XML parsing engine rules.
  • Run ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170; in a new query window if the GUI setting is grayed out or inaccessible.

Alternative or Verification Steps

  • To verify the fix, re-run the modified query in SSMS; a successful execution will return a valid XML result set or NULL without throwing the “invalid XML processing instruction target” error (Event ID 6879).
  • If the error persists despite removing the PI('xml', ...) syntax, check for linked server queries or nested stored procedures that might be dynamically constructing the SQL string with the reserved keyword, as dynamic SQL injection is a common alternative cause of this specific error.

How to fix Error 6901 on Windows Server 2025 / Windows 11

Why This Error Happens

SQL Server Error 6901 occurs when the XML parser receives a fragment—such as a list of elements, a text node, or multiple root-level nodes—instead of a well-formed XML document containing a single root element. This is typically triggered by application code or SSIS packages that pass raw XML fragments to the TYPE or xml data type without wrapping them in a proper root node. It can also surface after upgrading to SQL Server 2025 if legacy stored procedures generate XML output using string concatenation rather than FOR XML with proper document formatting.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Capture the exact XML payload being passed into the query using SQL Server Profiler or Extended Events (sqlserver.error_reported filtered on Error 6901).
  • Check whether the XML string has more than one root-level element or is missing an opening/closing root tag entirely.
  • Run the offending XML snippet manually in SQL Server Management Studio (SSMS) using SELECT CAST('<yourxml>' AS XML) to reproduce the error in isolation.

Step 2: Wrap the XML Fragment in a Valid Root Element

  • Modify the source query, application code, or ETL package (SSIS/SSDT) to enclose the fragment in a single parent node, for example: <Root>...</Root>.
  • If using FOR XML PATH, ensure you are generating a document-style result by adding a root clause: FOR XML PATH('Item'), ROOT('Items').
  • For C#/.NET applications on Windows Server 2025, confirm XmlDocument.LoadXml() is being passed a single-rooted string before it is sent to SQL Server as a parameter.

Step 3: Update the Column or Variable Definition to Enforce Document Mode

  • If the target column is typed XML(DOCUMENT xml_schema_collection), verify the schema collection explicitly expects a document, not a content fragment.
  • If fragments are legitimately expected (multiple top-level nodes), change the typed XML definition from DOCUMENT to CONTENT using: ALTER TABLE YourTable ALTER COLUMN XmlColumn XML(CONTENT YourSchemaCollection);
  • Re-run the insert/update statement to confirm the type now accepts the fragment without forcing a single-root requirement.

Step 4: Clear Cached Execution Plans and Validate

  • Run DBCC FREEPROCCACHE (in a non-production environment first) to ensure no stale execution plan is reusing an old XML validation path.
  • Re-execute the stored procedure or application call that originally threw Error 6901 to confirm resolution.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(@XmlVariable AS XML).query('/') — if it returns results without error, the XML is now properly document-formatted.
  • If the error persists in a specific SSIS package, open the XML Source component in SSDT, re-validate the XSD schema binding, and re-import a sample XML file to confirm the root element matches the expected schema structure.

How to fix Error 6877 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6877 – Empty Namespace Prefix Not Allowed in WITH XMLNAMESPACES Clause

Why This Error Happens

This error occurs when a T-SQL query uses the WITH XMLNAMESPACES clause but attempts to define a namespace using an empty string ('') as the prefix, which SQL Server’s XML parser explicitly disallows. SQL Server 2025 requires that every namespace prefix be a valid, non-empty identifier unless you are setting a DEFAULT namespace, which uses different syntax. This is typically caused by a coding error, a malformed dynamic SQL string, or a migration script that incorrectly translated an XML schema definition into T-SQL syntax.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the exact stored procedure or script referenced in the Error 6877 stack trace.
  • Search the script specifically for the WITH XMLNAMESPACES keyword to isolate the problematic block.
  • Check if the syntax looks like WITH XMLNAMESPACES ('http://example.com' AS ''), which is invalid.

Step 2: Correct the Syntax Using the DEFAULT Keyword

  • If the intention was to set a namespace that applies to all unqualified elements, replace the empty string prefix with the DEFAULT keyword.
  • Update the code from AS '' to the correct syntax: WITH XMLNAMESPACES (DEFAULT 'http://example.com').
  • Ensure there are no trailing quotes or whitespace characters that might be misinterpreted as an empty prefix string by the parser.

Step 3: Validate Dynamic SQL and Variable Concatenation

  • If the namespace prefix is being generated dynamically (e.g., via a variable in an ETL package or application layer), check the source code for logic errors.
  • Add a NULL or empty-string check in your application logic (C#/Python/PowerShell) before concatenating the prefix into the SQL string to prevent an empty value from ever reaching the database engine.
  • Example check: IF (@Prefix IS NULL OR @Prefix = '') SET @Prefix = 'DefaultNS';

Step 4: Test the Query in Isolation

  • Copy the corrected WITH XMLNAMESPACES block into a new query window in SSMS.
  • Execute the query against a test database on your Windows Server 2025 instance to confirm the parser accepts the syntax before deploying the fix to production.

Alternative or Verification Steps

  • Verification: Re-run the original stored procedure or ETL job that triggered Error 6877; if the XML namespace resolves correctly and the result set populates without a syntax error, the fix is confirmed successful.
  • Alternative: If modifying the source query is not immediately possible, wrap the vulnerable dynamic SQL execution in a TRY...CATCH block to gracefully handle the XML parsing error and log the specific malformed string for a developer to review later.

How to fix Error 6878 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6878 – FOR XML XMLSCHEMA Cannot Be Used with a Typed XML Column Whose Schema Collection Is Empty

Why This Error Happens

This error occurs when a query uses FOR XML XMLSCHEMA against a typed XML column that references an XML Schema Collection containing no actual schema definitions (i.e., it was created but never populated, or had its schemas dropped). SQL Server 2025 requires a fully populated schema collection to generate the inline XSD schema output required by the XMLSCHEMA directive. This commonly happens after an incomplete migration script, a failed CREATE XML SCHEMA COLLECTION statement, or manual deletion of schema components without dropping the collection itself.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Schema Collection

  • Run the following query to locate the column and its associated collection:
  • SELECT c.name AS ColumnName, s.name AS SchemaName, xsc.name AS CollectionName FROM sys.columns c JOIN sys.xml_schema_collections xsc ON c.xml_collection_id = xsc.xml_collection_id JOIN sys.schemas s ON xsc.schema_id = s.schema_id WHERE c.xml_collection_id IS NOT NULL;
  • Confirm the CollectionName returned matches the one referenced in your failing FOR XML XMLSCHEMA query.

Step 2: Verify the Schema Collection Contents

  • Check if the collection actually contains schema components:
  • SELECT xml_schema_namespace(N'YourSchemaName', N'YourCollectionName');
  • If this returns NULL or an empty XML result, the collection is confirmed to be empty and is the root cause of Error 6878.

Step 3: Repopulate or Recreate the XML Schema Collection

  • If the collection is empty, you must add a valid schema definition using ALTER XML SCHEMA COLLECTION:
  • ALTER XML SCHEMA COLLECTION YourSchemaName.YourCollectionName ADD N'<xsd:schema>...your valid XSD definition...</xsd:schema>';
  • If no backup of the original XSD exists, drop and recreate the collection entirely using CREATE XML SCHEMA COLLECTION, ensuring the column is not currently enforcing a NOT NULL dependency that blocks the drop.

Step 4: Re-bind the Typed XML Column (If Necessary)

  • If the collection had to be dropped and recreated (rather than altered), rebind the column via SQL Server Management Studio (SSMS) 21 or T-SQL:
  • ALTER TABLE YourTable ALTER COLUMN YourXMLColumn XML(YourSchemaName.YourCollectionName);
  • Ensure the application connection string does not point to a cached execution plan referencing the old (now deleted) collection ID.

Alternative or Verification Steps

  • Verification: Re-run the original SELECT ... FOR XML AUTO, XMLSCHEMA query; a successful fix will return a result set containing the <xsd:schema> node alongside your data rows rather than throwing Error 6878.
  • Alternative: If repopulating the schema is not immediately feasible, modify the query to use FOR XML AUTO (without the XMLSCHEMA directive) as a temporary workaround to retrieve data without the inline schema definition.

How to fix Error 6875 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6875 – Invalid URI in WITH XMLNAMESPACES

Why This Error Happens

This error occurs when SQL Server’s XML parser encounters a character in the namespace URI string that does not conform to the RFC 2396 URI syntax standard. It is typically caused by unescaped special characters (such as spaces, backslashes, or non-ASCII symbols) being passed directly into the WITH XMLNAMESPACES clause, often due to improper string concatenation or copy-paste errors from source documents. Additionally, encoding mismatches between the client application (using Windows 11) and the SQL Server 2025 instance (on Windows Server 2025) can introduce invisible Unicode characters that corrupt the URI string.

Step-by-Step Resolution Guide

Step 1: Isolate and Inspect the Offending Character

  • Copy the exact error message text; the %c (0x%04X) value tells you the exact Unicode code point causing the failure.
  • Open the query in SQL Server Management Studio (SSMS) and enable “View Whitespace” or use a hex editor to check for hidden characters like non-breaking spaces (0x00A0) or smart quotes.
  • Run SELECT UNICODE(SUBSTRING(@YourURI, 1, 1)) to programmatically verify the character code if the URI is stored in a variable.

Step 2: Sanitize the URI String

  • Manually re-type the namespace URI directly into the T-SQL editor rather than pasting it from Word documents or web browsers, as these often inject smart quotes or non-standard dashes.
  • Ensure the URI strictly uses standard ASCII characters; reserved characters like spaces must be percent-encoded (e.g., replace a space with %20).
  • Verify there are no leading or trailing whitespace characters within the quotation marks of the XMLNAMESPACES declaration.

Step 3: Validate Database Collation and Encoding Settings

  • Check the database collation to ensure it supports the character set being used:
  SELECT DATABASEPROPERTYEX('YourDBName', 'Collation');
  • If connecting via a driver (ODBC/JDBC) from a Windows 11 client, verify the connection string explicitly defines Charset=UTF-8 to prevent transcoding errors during transmission to the Windows Server 2025 host.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell if you update server-level collation settings.

Step 4: Update SQL Server Cumulative Updates

  • Navigate to the Microsoft Update Catalog and check for the latest Cumulative Update (CU) for SQL Server 2025.
  • Apply the patch as corrupted XML parsing libraries in specific pre-GA or early builds of SQL Server 2025 have been known to misinterpret valid URI schemas.
  • Verify the build number post-installation using SELECT @@VERSION;.

Alternative or Verification Steps

  • Verification: Execute the query using a hard-coded, known-good standard namespace (e.g., http://www.w3.org/2001/XMLSchema-instance) to confirm the WITH XMLNAMESPACES clause itself is functioning correctly before re-testing your specific URI.
  • Alternative: If the URI must contain special characters that cannot be removed, wrap the variable assignment using N'...' (Unicode string literal) explicitly to force correct character interpretation rather than relying on the default varchar casting.

How to fix Error 6876 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6876 – URI Used in WITH XMLNAMESPACES Is Too Long

Why This Error Happens

This error occurs when a URI string declared in a WITH XMLNAMESPACES clause exceeds the maximum character limit enforced by SQL Server’s XML parser. SQL Server 2025 imposes a strict internal limit on namespace URI length to prevent memory overallocation during XML schema validation and query compilation. This is typically caused by auto-generated namespace URIs (often from third-party tools or ORM-generated queries) that concatenate long GUIDs, timestamps, or file paths into the namespace string.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and URI

  • Use SQL Server Profiler or Extended Events to capture the exact T-SQL batch raising Error 6876.
  • Inspect the WITH XMLNAMESPACES clause in the captured query text and count the characters in the URI string.
  • Check the error message detail for the %d value — this tells you the exact maximum character limit enforced in your current SQL Server 2025 build.

Step 2: Shorten or Refactor the Namespace URI

  • Edit the query source (stored procedure, application code, or SSIS package) to use a shorter, static namespace URI instead of a dynamically generated long string.
  • If the URI is auto-generated by an ORM (e.g., Entity Framework, Hibernate), check the mapping configuration file (commonly appsettings.json or web.config) for namespace generation logic and hardcode a shorter alias.
  • Where possible, use a namespace prefix mapping table in your application layer to translate long internal URIs to short, compliant ones before passing them to SQL Server.

Step 3: Update SQL Server 2025 to the Latest Cumulative Update

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11 and confirm your current build number via:
  SELECT @@VERSION;
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025, as some CUs have adjusted internal buffer limits for XML parsing.
  • Install the update using elevated PowerShell:
  Start-Process -FilePath "SQLServer2025-KB XXXXXXX-x64.exe" -ArgumentList "/quiet /IAcceptSQLServerLicenseTerms" -Verb RunAs
  • Restart the SQL Server service via services.msc or:
  Restart-Service -Name "MSSQLSERVER" -Force

Step 4: Adjust Application-Level XML Handling

  • If the long URI cannot be shortened (e.g., required by an external XSD schema), restructure the query to avoid WITH XMLNAMESPACES entirely and instead use OPENXML or .nodes() with inline namespace declarations embedded directly in the XML instance.
  • Validate the refactored query in a non-production environment (e.g., a test instance on Windows 11 with SQL Server 2025 Developer Edition) before deploying to production.

Alternative or Verification Steps

  • Re-run the original query after shortening the URI and confirm it executes without raising Error 6876; check the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for confirmation that no XML namespace errors remain.
  • As an alternative, if modifying the URI isn’t feasible, configure the query to reference an external XML schema collection (CREATE XML SCHEMA COLLECTION) instead of inline WITH XMLNAMESPACES, which bypasses the character limit entirely.

How to fix Error 6873 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6873 – XML Namespace Prefix Redefinition

Why This Error Happens

This error occurs when a FOR XML query uses the ELEMENTS XSINIL directive alongside a WITH XMLNAMESPACES clause that explicitly redefines the reserved xsi prefix (typically bound to http://www.w3.org/2001/XMLSchema-instance). SQL Server automatically generates and manages the xsi prefix internally to emit xsi:nil attributes for NULL elements, so an explicit, conflicting redefinition in the query creates an ambiguous namespace mapping. The SQL Server 2025 XML engine rejects this ambiguity at parse time rather than guessing which binding to honor, resulting in Error 6873.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Namespace Declaration

  • Open the query or stored procedure that throws Error 6873 in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Locate the WITH XMLNAMESPACES (...) clause preceding the SELECT ... FOR XML statement.
  • Check specifically for a line similar to: 'http://www.w3.org/2001/XMLSchema-instance' AS xsi

Step 2: Remove or Rename the Explicit ‘xsi’ Binding

  • If your query does not strictly require a custom URI for xsi, delete that specific namespace declaration from the WITH XMLNAMESPACES block entirely.
  • Allow SQL Server to handle the xsi prefix implicitly; it will be generated automatically because ELEMENTS XSINIL is present.
  • If you need a custom schema instance URI for other purposes, rename the prefix alias to avoid the reserved keyword, e.g., change AS xsi to AS xsi_custom.

Step 3: Validate T-SQL Syntax and Compatibility Level

  • Verify the database compatibility level is correctly set for SQL Server 2025 features by running:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the value is 170 or higher; if not, update it via:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-run the corrected FOR XML query to confirm the parser accepts the syntax without throwing Error 6873.

Step 4: Clear Cached Execution Plans

  • If the error persists due to a stale cached plan referencing the old namespace definition, clear the specific plan cache.
  • Run the following command to free the procedure cache for the specific query (use with caution in production):
  DBCC FREEPROCCACHE;
  • Re-execute the stored procedure or ad-hoc query to force a fresh compilation.

Alternative or Verification Steps

  • Verification: Execute the modified query and check the output XML; successful execution with properly formatted xsi:nil="true" attributes on NULL columns confirms the fix.
  • Alternative: If renaming the prefix is not feasible due to third-party application dependencies, switch the query logic to use ELEMENTS XSINIL without any WITH XMLNAMESPACES clause, letting SQL Server manage the entire namespace stack by default.

How to fix Error 6874 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6874 – Empty URI in WITH XMLNAMESPACES Clause

Why This Error Happens

This error occurs when a T-SQL query uses the WITH XMLNAMESPACES clause with an empty string ('') as the namespace URI, which SQL Server’s XML parser explicitly disallows. Unlike a default namespace declaration in standard XML (xmlns=""), SQL Server requires that if you declare a default namespace, it must resolve to a non-empty, valid URI value. This is typically caused by dynamically generated SQL, legacy code migrated from an older schema, or a copy-paste error where a namespace variable failed to populate correctly before the query executed.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Identify the exact stored procedure, view, or dynamic SQL script triggering Error 6874 using SQL Server Profiler or Extended Events on your SQL Server 2025 instance.
  • Search the query text for the syntax pattern WITH XMLNAMESPACES (DEFAULT '' AS ...) or similar empty-string declarations.
  • Check if the URI value is being passed via a variable (e.g., DECLARE @ns VARCHAR(100) = '') that is failing to initialize.

Step 2: Correct the Namespace Declaration

  • Replace the empty string with a valid, non-null URI. If you only need to strip prefixes for parsing, use a placeholder URI instead of an empty one, such as:
  WITH XMLNAMESPACES (DEFAULT 'http://www.example.com/default' AS ns)
  • If the intention was to remove the namespace from the XML entirely, modify the XML source data to remove the xmlns="" attribute via .modify() before shredding the XML, rather than relying on the query’s WITH clause to handle the empty value.

Step 3: Audit Dynamic SQL and ETL Scripts

  • If the query is generated dynamically (e.g., via SSIS packages or an external application on Windows Server 2025), check the source code logic that concatenates the namespace string.
  • Look for truncation issues or incorrect parsing of the source XML schema that might result in a null or empty variable being injected into the WITH XMLNAMESPACES clause.
  • Update the application logic to validate that the URI variable is not empty before constructing the final T-SQL string.

Step 4: Apply Cumulative Updates

  • Ensure your Microsoft SQL Server 2025 instance is patched with the latest Cumulative Update (CU) via SQL Server Setup, as XML parsing engine behaviors are occasionally refined in these updates.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER followed by net start MSSQLSERVER after applying any updates.

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific query in SQL Server Management Studio (SSMS) and confirm the XML shredding/querying operation completes without throwing Error 6874, ensuring the output XML or table result renders correctly.
  • Alternative Approach: If dropping the namespace is not feasible, utilize the nodes() and value() methods with wildcard namespace prefixes (*:) in your XQuery expressions to bypass the need for a strict WITH XMLNAMESPACES declaration altogether.

How to fix Error 6870 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6870 – Invalid XML Identifier in WITH XMLNAMESPACES Clause

Why This Error Happens

This error occurs when the prefix defined in a WITH XMLNAMESPACES clause contains a character that does not conform to valid XML naming rules, such as a leading digit, a space, or a reserved symbol like #, $, or %. SQL Server strictly validates namespace prefixes against the W3C XML Names specification, and any character outside the permitted Unicode ranges for NameStartChar or NameChar will trigger this failure. This is typically a query authoring issue rather than a server configuration problem, often introduced by copy-pasted code, dynamic SQL string concatenation, or localization/encoding mismatches that insert hidden or non-standard characters into the prefix string.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Character in the Query

  • Locate the exact WITH XMLNAMESPACES clause referenced in the error message.
  • Note the character and hex code provided in the error (e.g., '%c'(0x%04X)), as this tells you precisely which character is invalid.
  • Open the query in SQL Server Management Studio (SSMS) and visually inspect the prefix string for stray spaces, numbers at the start, or special symbols.

Step 2: Correct the Namespace Prefix Syntax

  • Ensure the prefix starts with a letter or underscore (_), not a digit or symbol.
  • Remove invalid characters such as #, @, %, $, or whitespace from the prefix definition.
  • Example of a corrected syntax:
WITH XMLNAMESPACES ('http://schemas.example.com/orders' AS ord)
SELECT * FROM Orders
FOR XML AUTO;
  • If the prefix was dynamically generated (e.g., via string concatenation in application code), audit the source variable for injected whitespace or encoding artifacts.

Step 3: Check for Encoding or Copy-Paste Corruption

  • If the query was copied from a Word document, PDF, or web page, retype the prefix manually instead of pasting it, as hidden Unicode characters (like non-breaking spaces 0x00A0) are a common cause.
  • In SSMS, enable View > Non-Printable Characters or use a hex editor to inspect the raw bytes of the query file if the issue persists.
  • Save the script using UTF-8 or ANSI encoding without BOM to avoid introducing stray byte-order-mark characters at the start of identifiers.

Step 4: Validate Against XML Naming Rules Programmatically

  • If prefixes are generated dynamically in application code (C#, PowerShell, etc.), add a validation regex before constructing the SQL string: ^[a-zA-Z_][a-zA-Z0-9_.-]*$.
  • Reject or sanitize any input that does not match this pattern before it reaches the T-SQL execution layer.
  • Re-run the query in a test environment (non-production instance) to confirm the corrected prefix executes without triggering Error 6870.

Alternative or Verification Steps

  • Verify the fix: Execute the corrected query in SSMS or Azure Data Studio and confirm it returns results successfully without the 6870 error in the Messages pane.
  • Alternative workaround: If the prefix is being generated by a third-party ORM or reporting tool, bypass dynamic namespace generation entirely by hardcoding a known-safe prefix (e.g., ns1, ns2) directly in the query template.

How to fix Error 6871 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6871 — Reserved Prefix in WITH XMLNAMESPACES

Why This Error Happens

Error 6871 occurs when a T-SQL query attempts to declare a user-defined namespace prefix in a WITH XMLNAMESPACES clause that collides with a system-reserved prefix, most commonly xml, xmlns, or sqlxml. SQL Server 2025 enforces strict XML namespace compliance per the W3C specification, which explicitly reserves certain prefixes for internal processing. This is not a server configuration or permissions issue — it is a syntax-level validation error thrown by the query parser before execution begins.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Prefix in Your Query

  • Open the failing script in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate the WITH XMLNAMESPACES (...) block and check for prefixes named xml, xmlns, sqlxml, or any variant with inconsistent casing (e.g., XML, Xml).
  • Cross-reference the exact string reported in the error message Prefix '%.*ls' used... — this placeholder resolves to the actual prefix name in your error log.

Step 2: Rename the Conflicting Prefix

  • Replace the reserved prefix with a custom, non-conflicting alias in your WITH XMLNAMESPACES clause.
  • Example fix:
  -- Incorrect (throws Error 6871)
  WITH XMLNAMESPACES ('http://example.com' AS xml)

  -- Corrected
  WITH XMLNAMESPACES ('http://example.com' AS myxml)
  • Update every subsequent reference to that prefix throughout the query (e.g., in FOR XML PATH, XQuery expressions, or nodes()/value() calls).

Step 3: Check Linked Stored Procedures and Views

  • Search your database objects for reused namespace declarations using sys.sql_modules:
  SELECT object_name(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%XMLNAMESPACES%'
  • Audit each result for the same reserved-prefix pattern, since error 6871 can surface in nested views, functions, or SSIS packages calling these objects.

Step 4: Clear Cached Execution Plans (If Error Persists After Fix)

  • Run DBCC FREEPROCCACHE in a test environment to eliminate stale plan references tied to the old (broken) query text.
  • Re-execute the corrected query to confirm SQL Server recompiles cleanly under the new namespace alias.

Alternative or Verification Steps

  • Verify the fix by executing the corrected query in isolation and confirming no Msg 6871 appears in the Messages tab of SSMS.
  • If the error persists across multiple objects, consider a global search-and-replace across your .sql deployment scripts using a tool like grep or PowerShell’s Select-String to catch any remaining reserved-prefix declarations before redeploying.

How to fix Error 6872 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6872 – XML Namespace Prefix Conflict

Why This Error Happens

This error occurs when an XML document or query passed to SQL Server 2025 explicitly redefines the reserved xml prefix to a URI other than http://www.w3.org/XML/1998/namespace. The SQL Server XML parser strictly enforces the W3C XML namespace specification, which reserves the xml prefix exclusively for this URI. This typically stems from malformed XML being generated by an application, a faulty ETL/import script, or a third-party tool that incorrectly constructs XML payloads before sending them to FOR XML, OPENXML, or an xml-typed column/parameter.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Capture the exact XML payload being sent to SQL Server using SQL Server Profiler or Extended Events on the Windows Server 2025 instance.
  • Check stored procedures, application code, or SSIS packages that construct XML strings manually using string concatenation.
  • Look specifically for any line that declares xmlns:xml="..." with a value different from the W3C standard URI.

Step 2: Correct the XML Namespace Declaration

  • Open the source file or code (e.g., .xml, .xsd, or C#/Java string builder logic) responsible for generating the payload.
  • Remove any explicit xmlns:xml attribute declarations — the xml prefix is implicitly bound by default and does not need to be declared manually.
  • If a custom prefix is required for your namespace, rename it to something other than xml (e.g., xm or custom), such as changing xmlns:xml="http://mycompany.com" to xmlns:myns="http://mycompany.com".

Step 3: Validate XML Before Insertion

  • On Windows 11 or Windows Server 2025, use the built-in PowerShell cmdlet to pre-validate the XML structure before sending it to SQL Server:
  • [xml]$test = Get-Content "C:\Temp\payload.xml"
  • If PowerShell throws a parsing error here, it confirms the file is invalid prior to reaching SQL Server, isolating the issue to the client-side generation process rather than the database engine.

Step 4: Test the Corrected Query in SSMS

  • Open SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Run the corrected XML insert or CAST/CONVERT statement in a new query window to ensure Error 6872 no longer appears.
  • Check the “Messages” tab for a successful completion status rather than a parsing exception.

Alternative or Verification Steps

  • Verification: Re-run the original failing transaction or SSIS package; if the XML parses successfully and data populates the target table without throwing Error 6872, the fix is confirmed.
  • Alternative: If you do not have access to modify the source application code, use a T-SQL REPLACE() function on the incoming string to strip out the invalid xmlns:xml attribute before casting the string to the xml data type.

How to fix Error 6867 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6867 — “xmlns’ is invalid in XML tag name in FOR XML PATH”

Why This Error Happens

This error occurs when a FOR XML PATH query attempts to use xmlns as a literal column alias or node name rather than as a reserved namespace declaration keyword. SQL Server reserves the xmlns prefix exclusively for namespace binding, so when it appears directly in a PATH mode column alias (e.g., AS xmlns), the XML tag name parser rejects it as malformed syntax. This is typically caused by a query author mistakenly using xmlns as a shorthand without properly wrapping it in a WITH XMLNAMESPACES clause or bracketed notation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Alias

  • Review the SELECT statement for any column alias written as AS xmlns or AS "xmlns".
  • Check nested subqueries using FOR XML PATH('') for concatenation tricks, as these are common culprits.
  • Use SSMS (SQL Server Management Studio 21) to run the query in isolation and capture the exact line number from the error output.

Step 2: Correct the Namespace Declaration Syntax

  • Replace improper inline usage with a formal WITH XMLNAMESPACES clause at the top of the query.
  • Example fix:
  WITH XMLNAMESPACES (DEFAULT 'http://www.example.com/schema')
  SELECT col1, col2
  FOR XML PATH('root')
  • If you need a literal attribute named xmlns, escape it using bracket notation: AS "xmlns:prefix" or restructure the alias to avoid the reserved word entirely (e.g., xmlns_value).

Step 3: Validate Query Compatibility Level

  • Confirm the database compatibility level supports the XML schema features you are using by running:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the database was recently migrated from an older version to SQL Server 2025, update compatibility using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025 if compatibility changes do not take effect immediately.

Step 4: Clear Cached Execution Plans

  • Stale cached plans referencing the old malformed XML syntax can sometimes resurface the error even after a fix.
  • Run DBCC FREEPROCCACHE; to clear the plan cache, or target a specific plan handle using DBCC FREEPROCCACHE (plan_handle);.
  • Re-execute the corrected query to confirm the cache was the source of persistence.

Alternative or Verification Steps

  • Verify the fix by re-running the query and confirming FOR XML PATH returns a well-formed XML document without Error 6867 in the Messages tab of SSMS.
  • If the error persists, isolate the issue by testing the query on a minimal reproducible table (e.g., SELECT 1 AS test FOR XML PATH('')) to confirm whether the root cause lies in the schema or in a specific column alias elsewhere in the script.

How to fix Error 6868 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6868 – FOR XML EXPLICIT Mode Not Supported with WITH XMLNAMESPACES

Why This Error Happens

This error occurs because SQL Server’s FOR XML EXPLICIT mode is architecturally incompatible with the WITH XMLNAMESPACES clause, as EXPLICIT mode relies on a legacy column-naming convention (Tag, Parent, ElementName!TagNumber!AttributeName) that cannot process namespace prefix bindings correctly. This is not a bug or configuration defect but a documented engine limitation enforced by the SQL Server 2025 query parser during compilation. The error is thrown at parse time whenever the optimizer detects both constructs in the same query batch, regardless of database compatibility level or collation settings.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact query raising Error 6868 by checking SQL Server Error Logs or the client application’s query trace output.
  • Run the query in isolation using SQL Server Management Studio (SSMS) 21 or Azure Data Studio to confirm the WITH XMLNAMESPACES and FOR XML EXPLICIT clauses coexist in the same statement.
  • Use SET SHOWPLAN_XML ON to inspect the compiled plan and confirm where the conflict originates if the query is dynamically generated.

Step 2: Convert EXPLICIT Mode to PATH Mode

  • Rewrite the query using FOR XML PATH('ElementName') instead of FOR XML EXPLICIT, since PATH mode fully supports WITH XMLNAMESPACES.
  • Map your existing Tag/Parent hierarchy columns to nested PATH subqueries or use the TYPE directive for hierarchical nesting.
  • Test namespace prefix declarations by placing them before the SELECT statement, e.g.:
  WITH XMLNAMESPACES ('http://example.com/ns' AS ns)
  SELECT col1 AS '@ns:attr'
  FOR XML PATH('Root')

Step 3: Separate Namespace Injection from EXPLICIT Queries

  • If EXPLICIT mode must be retained for legacy compatibility, remove the WITH XMLNAMESPACES clause entirely from that query.
  • Manually inject namespace declarations as literal attributes within the EXPLICIT mode column aliases (e.g., xmlns:ns='http://example.com/ns' hardcoded into the root element string).
  • Validate that the manually injected namespace does not conflict with any xsi or xsd prefixes already used downstream by consuming applications.

Step 4: Update Application or ORM Layer

  • Check any .NET, Java, or Python data access layer connecting to SQL Server 2025 for dynamically generated FOR XML queries.
  • Update stored procedures or ORM-generated SQL templates to use the PATH-mode syntax validated in Step 2.
  • Redeploy the updated stored procedures using sqlcmd or SSMS, and clear the plan cache for the affected database using DBCC FREEPROCCACHE to ensure stale execution plans are not reused.

Alternative or Verification Steps

  • Verify the fix by re-executing the corrected query in SSMS and confirming the XML output renders expected namespace prefixes without throwing Error 6868.
  • If immediate query rewriting isn’t feasible, use FOR XML RAW or FOR XML AUTO with WITH XMLNAMESPACES as a temporary alternative, since both modes support namespace clauses natively and require less refactoring than EXPLICIT mode.

How to fix Error 6869 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6869 occurs when SQL Server’s XML parser encounters a query or XML schema collection that attempts to bind the same namespace prefix to two different URIs within the same scope. This is typically caused by malformed FOR XML clauses, conflicting WITH XMLNAMESPACES declarations, or an application layer generating XML that redeclares a prefix inherited from a parent element. Corrupted or poorly templated XML schema collections (XSDs) imported into SQL Server 2025 can also trigger this validation failure during parsing.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Procedure

  • Capture the exact T-SQL statement from SQL Server Profiler, Extended Events, or the application log that triggered Error 6869.
  • Look specifically for WITH XMLNAMESPACES, FOR XML PATH, or FOR XML AUTO clauses in the captured batch.
  • Check if the error correlates with a specific stored procedure or a dynamically generated XML payload from the application tier.

Step 2: Inspect and Correct Namespace Prefix Declarations

  • Open the query in SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and locate the WITH XMLNAMESPACES block.
  • Ensure each prefix (e.g., ns1, ns2) is declared only once per scope — remove any duplicate AS prefix bindings pointing to different URIs.
  • Example fix:
WITH XMLNAMESPACES ('http://schemas.example.com/v1' AS ns, 'http://schemas.example.com/v2' AS ns2)
SELECT ...
  • If using nested XML fragments (via TYPE directive or .nodes()), verify child elements aren’t re-declaring an ancestor’s prefix with a new URI.

Step 3: Validate or Rebuild the XML Schema Collection

  • If the error originates from an XML SCHEMA COLLECTION, run the following to inspect current definitions:
SELECT name, xml_schema_namespace(SCHEMA_NAME(schema_id), name) 
FROM sys.xml_schema_collections;
  • Drop and recreate the schema collection with corrected namespace prefixes:
DROP XML SCHEMA COLLECTION dbo.MySchemaCollection;
CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'<corrected XSD content>';
  • Confirm the source XSD file (often maintained in a .xsd file under the application’s Schemas\ directory) does not have duplicate prefix-to-URI mappings before re-importing.

Step 4: Update Application-Generated XML (If Applicable)

  • If the XML is generated by middleware (e.g., a .NET service using XmlWriter on Windows Server 2025), check the serialization logic for hardcoded namespace prefixes.
  • Ensure XmlSerializerNamespaces objects aren’t adding a prefix that conflicts with one already present in the base document template.
  • Redeploy the corrected application binary and restart the associated application pool in IIS if applicable.

Alternative or Verification Steps

  • Re-run the original query or application transaction and confirm Error 6869 no longer appears in the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) or Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, simplify the XML generation logic by removing explicit prefixes entirely and allowing SQL Server to auto-generate default namespace prefixes, then validate output using SELECT ... FOR XML PATH, TYPE in a test environment before reverting to custom prefixes.

How to fix Error 6866 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6866 — “Use of a System Reserved XML Schema URI Is Not Allowed”

Why This Error Happens

This error occurs when a T-SQL script or application attempts to create, register, or reference an XML schema collection using a namespace URI that is reserved by SQL Server, such as http://schemas.microsoft.com/sqlserver/2004/sqltypes or other http://www.w3.org/* system namespaces. SQL Server 2025 protects these reserved URIs internally for native XML type processing, so any CREATE XML SCHEMA COLLECTION statement or XML data load referencing them directly will be rejected. This is most commonly triggered by migrated scripts, third-party tools, or ORM-generated code that imports XSD files without renaming or aliasing the schema’s target namespace.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Reference

  • Open the failing T-SQL batch or stored procedure and locate the CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement.
  • Search the XSD payload for targetNamespace or xmlns attributes matching reserved URIs like http://schemas.microsoft.com/sqlserver/2004/sqltypes.
  • Run the following query to check existing collections for conflicts:
  SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE name LIKE '%sqltypes%';

Step 2: Rename or Remove the Reserved Namespace

  • Edit the source XSD file and change the targetNamespace value to a custom, non-reserved URI (e.g., http://yourcompany.com/schemas/custom2025).
  • Update any corresponding xmlns import statements in dependent XML documents to match the new namespace.
  • If the reserved namespace was included only for type reference purposes, remove the redundant <xs:import> declaration entirely, since SQL Server registers system namespaces automatically.

Step 3: Re-register the Corrected XML Schema Collection

  • Drop the invalid collection if it was partially created:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Re-run the corrected CREATE XML SCHEMA COLLECTION statement pointing to the updated XSD with the renamed namespace.
  • Restart the SQL Server 2025 service via services.msc on Windows Server 2025 / Windows 11 if schema caching issues persist after the change.

Step 4: Audit Application and ORM Code

  • Check connection strings and ORM mapping files (e.g., Entity Framework, Dapper XML configs) for hardcoded references to the old reserved URI.
  • Update application-layer XML serialization settings to align with the new custom namespace defined in Step 2.

Alternative or Verification Steps

  • Verify the fix by re-executing the original failing script and confirming the XML schema collection is created successfully without Error 6866, then query sys.xml_schema_collections to confirm the new entry exists.
  • If the error persists, use SQL Server Management Studio’s XML Editor to validate the XSD structure independently of SQL Server, ensuring no nested imports still reference reserved Microsoft or W3C namespaces.

How to fix Error 6863 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6863 – Row Tag Omission Incompatible with XMLSCHEMA

Why This Error Happens

This error occurs when a FOR XML AUTO or FOR XML RAW query attempts to omit the row element name (using an empty string '' as the row tag) while simultaneously specifying the XMLSCHEMA directive. The XMLSCHEMA option requires a valid, named row element to properly generate and bind the inline XSD schema, so an empty tag name creates a structural conflict that SQL Server’s XML parser cannot resolve. This is a query syntax design flaw rather than a server configuration or permissions issue, meaning it typically surfaces after a T-SQL script migration or an application update targeting SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the stored procedure or ad-hoc query referenced in the error log.
  • Search specifically for the pattern FOR XML RAW('') or FOR XML AUTO, ELEMENTS, XMLSCHEMA combined with an empty string row identifier.
  • Check the Windows Event Viewer under Applications and Services Logs > Microsoft > Windows > SQL Server for the exact batch text if the query isn’t immediately obvious in application code.

Step 2: Correct the Row Tag Syntax

  • Replace the empty row tag argument with a valid, non-empty string identifier (e.g., change FOR XML RAW('') to FOR XML RAW('row')).
  • If using FOR XML AUTO, ensure you are not manually overriding the automatic table-based naming with an empty override, as AUTO mode does not support tag omission alongside XMLSCHEMA at all.
  • Save the updated query logic to the relevant .sql file or stored procedure definition.

Step 3: Remove XMLSCHEMA if Tag Omission is Required

  • If the application logic strictly requires an unnamed/omitted row tag for downstream XML parsing compatibility, remove the XMLSCHEMA keyword from the FOR XML clause entirely.
  • Switch to the standard FOR XML RAW or FOR XML AUTO without the schema-generation directive if inline XSD metadata is not a hard requirement for the consuming application.
  • Update any client-side XML deserializers (e.g., .NET XmlSerializer classes) that may have been expecting the schema block in the output payload.

Step 4: Restart the SQL Server Service

  • Navigate to the Windows Server 2025 Services console (services.msc).
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart to clear any cached execution plans referencing the faulty syntax.
  • Alternatively, run DBCC FREEPROCCACHE; in a query window to force recompilation without a full service restart.

Alternative or Verification Steps

  • Execute the corrected query directly in SSMS and confirm the result set returns a valid XML document with the <xsd:schema> block properly nested inside the root element without throwing Error 6863.
  • If the error persists, run SELECT @@VERSION; to confirm you are on a fully patched build of SQL Server 2025, as early RC builds had stricter XML parser validation that may require the latest Cumulative Update (CU) to resolve edge-case schema binding bugs.

How to fix Error 6864 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6864 — Row Tag Omission with Attribute-Centric FOR XML

Why This Error Happens

This error occurs when a FOR XML query attempts to omit the row element name (using an empty string for the row tag) while simultaneously using XMLDATA, ELEMENTS, or attribute-centric formatting modes that require a named container element for proper serialization. SQL Server’s XML engine cannot structure attributes without a valid parent tag to attach them to, making the empty row tag and attribute-centric mode mutually exclusive. This is typically caused by malformed or improperly migrated T-SQL syntax, often introduced during application upgrades or script porting to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Review SQL Server error logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact query triggering Error 6864.
  • Use SQL Server Management Studio (SSMS) Activity Monitor or sys.dm_exec_query_stats to correlate the error timestamp with the executed batch.
  • Confirm the query uses FOR XML RAW('') or FOR XML AUTO with an empty row name parameter.

Step 2: Correct the FOR XML Syntax

  • Open the identified stored procedure or query in SSMS connected to your SQL Server 2025 instance.
  • Replace the empty row tag with a valid identifier, for example change:
    FOR XML RAW('') to FOR XML RAW('Row')
  • If attribute-centric output is required, ensure the syntax follows this pattern:
    SELECT col1, col2 FROM table FOR XML RAW('Record'), ELEMENTS XSINIL
  • If a fully tag-less structure is truly needed, switch to FOR XML PATH('') instead, which supports element omission without conflicting with attribute mode.

Step 3: Update Application or ORM-Generated Queries

  • Check middleware or ORM frameworks (Entity Framework, Dapper, custom data layers) that may dynamically generate FOR XML clauses.
  • Search configuration files or generated SQL templates (commonly under C:\inetpub\wwwroot\App_Data\ or your application’s data access layer) for hardcoded empty row-tag parameters.
  • Redeploy the corrected query logic and restart the associated application pool via IIS Manager or Restart-WebAppPool in PowerShell.

Step 4: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to clear cached query plans referencing the faulty syntax.
  • Alternatively, run net stop MSSQLSERVER && net start MSSQLSERVER from an elevated Command Prompt.

Alternative or Verification Steps

  • Re-run the corrected query directly in SSMS and confirm the XML output renders correctly without triggering Error 6864 in the Messages pane.
  • If the error persists, use DBCC FREEPROCCACHE to clear the plan cache in case a stale execution plan is still referencing the old malformed FOR XML clause.

How to fix Error 6865 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6865 — “FOR XML does not support CLR types”

Why This Error Happens

This error occurs because the FOR XML clause in SQL Server cannot natively serialize columns that use CLR-based data types, such as hierarchyid, geometry, geography, or custom CLR user-defined types (UDTs). SQL Server’s XML engine only recognizes native SQL types (like nvarchar, int, varbinary, etc.) when constructing XML output, so it rejects the query at parse time rather than attempting an implicit conversion. This typically surfaces when a query selects a CLR-typed column directly inside a SELECT ... FOR XML statement without first converting it to a string or binary representation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Column

  • Review the SELECT statement tied to the FOR XML clause and locate any columns typed as hierarchyid, geometry, geography, or custom CLR UDTs.
  • Run sp_help 'YourTableName' or check sys.columns joined with sys.types to confirm which columns use system_type_id = 240 (CLR/UDT marker).
  • Check your T-SQL script or stored procedure file (commonly in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Scripts\) for the exact query causing the failure.

Step 2: Explicitly Cast the CLR Type

  • Wrap the CLR column in a CAST() or CONVERT() function to a supported SQL type before it reaches FOR XML.
  • Example for hierarchyid: CAST(YourHierarchyColumn.ToString() AS NVARCHAR(4000)).
  • Example for geography/geometry: CONVERT(NVARCHAR(MAX), YourSpatialColumn.STAsText()).
  • For custom CLR UDTs, call the type’s .ToString() method or a defined serialization method, then cast the result to VARCHAR, NVARCHAR, or VARBINARY.

Step 3: Update the Query and Re-Test

  • Modify the SELECT statement in SQL Server Management Studio (SSMS) 21 or Azure Data Studio to include the cast expression in place of the raw CLR column.
  • Save the updated script and re-execute it against the Windows Server 2025 SQL Server instance.
  • If the query is embedded in an application (e.g., a .NET service calling SQL Server from Windows 11), redeploy the corrected stored procedure or inline query.

Step 4: Audit Related Views and Procedures

  • Search your database for other instances of FOR XML AUTO, FOR XML PATH, or FOR XML RAW that may reference the same CLR columns.
  • Use sys.sql_modules with a LIKE '%FOR XML%' filter to locate all affected objects schema-wide.
  • Apply the same CAST/CONVERT fix to each identified object to prevent recurrence.

Alternative or Verification Steps

  • Verify the fix: Re-run the corrected query in SSMS and confirm the XML output renders without Error 6865; check the Messages tab for a clean execution with no red error text.
  • Alternative approach: If repeated casting becomes cumbersome, create a computed column or a view that pre-converts the CLR type to NVARCHAR/VARBINARY, then reference that view in all FOR XML queries instead of the base table.

How to fix Error 6861 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6861 — Empty Root Tag Name in FOR XML

Why This Error Happens

This error occurs when a FOR XML query (typically using EXPLICIT or PATH mode with the ROOT directive) is executed with an empty string or NULL value passed as the root element name. SQL Server 2025 requires a valid, non-empty identifier for the root tag whenever the ROOT() option is explicitly specified in the query syntax. This is commonly triggered by dynamically constructed SQL strings where a variable intended to hold the root tag name resolves to an empty value at runtime.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Review the SQL Server error log or Extended Events session for the exact query text associated with Error 6861.
  • Search your stored procedures, views, and application code for instances of FOR XML PATH or FOR XML EXPLICIT combined with , ROOT('').
  • Use SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) to run sp_helptext on suspected stored procedures to inspect the raw query definition.

Step 2: Correct the Root Tag Syntax

  • Edit the query to ensure the ROOT clause contains a valid string literal, such as ROOT('RootElement').
  • If the root name is dynamically generated via a variable (e.g., DECLARE @RootName NVARCHAR(50)), add a validation check before query execution:
  • IF @RootName IS NULL OR @RootName = '' SET @RootName = 'DefaultRoot';
  • If you do not require a root element wrapper, remove the ROOT keyword entirely rather than passing an empty string, as FOR XML PATH('') without ROOT will generate a fragment without issue.

Step 3: Update Application-Side Parameter Binding

  • Check the application layer (C#, Python, or PowerShell scripts) that constructs the T-SQL string for the XML export.
  • Ensure that configuration files or environment variables feeding the root tag name (e.g., via appsettings.json or web.config on Windows Server 2025) are populated correctly and not defaulting to an empty string during deployment.
  • Redeploy the application or restart the IIS Application Pool via iisreset if configuration changes were made to a web-based front end.

Step 4: Clear Query Plan Cache

  • Once the query syntax is fixed, clear the stale execution plan to ensure SQL Server does not attempt to reuse a cached plan tied to the faulty parameter sniffing.
  • Execute DBCC FREEPROCCACHE in a new query window against the specific database context.
  • Restart the SQL Server Agent service if the query is part of a scheduled job to ensure the job step picks up the updated logic.

Alternative or Verification Steps

  • Verification: Re-run the specific stored procedure or ad-hoc query manually in SSMS to confirm the XML output renders correctly with the specified root tag and no Msg 6861 errors appear in the Messages tab.
  • Alternative: If the root tag name must remain dynamic and might occasionally be empty by design, wrap the FOR XML logic in a TRY...CATCH block to gracefully fall back to a default tag name (e.g., 'Results') instead of allowing the transaction to fail.

How to fix Error 6862 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6862 – Empty FOR XML Target Inline Schema URI

Why This Error Happens

This error occurs when a FOR XML query includes an XMLSCHEMA clause with an empty string ('') specified as the target namespace URI. SQL Server 2025 requires that if the XMLSCHEMA directive is used, the target namespace must either be omitted entirely or populated with a valid, non-empty URI string. This is typically caused by dynamically generated T-SQL scripts, application-layer ORM mapping tools, or copy-pasted legacy queries that pass a null or blank variable into the schema URI parameter instead of removing the clause.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance and check the Activity Monitor or SQL Server Profiler for the exact query raising Error 6862.
  • Look specifically for syntax resembling: FOR XML AUTO, XMLSCHEMA('').
  • Cross-reference the query against your application’s data access layer (DAL) code, especially stored procedures that build XML strings dynamically.

Step 2: Correct the XMLSCHEMA Syntax

  • If a namespace is not required, remove the XMLSCHEMA argument entirely and replace it with standard FOR XML AUTO, ELEMENTS syntax.
  • If a namespace is required, populate the URI with a valid string. Example of a corrected query:
  SELECT * FROM Sales.Customer 
  FOR XML AUTO, XMLSCHEMA('urn:schemas-mycompany-com:sales')
  • Avoid using string concatenation that could inject an empty variable (e.g., @SchemaURI = '') into the XMLSCHEMA() argument.

Step 3: Update Application Configuration Files

  • If the query originates from a third-party application or middleware running on Windows 11/Server 2025, check the configuration files (usually .config or .json files) for a default “Namespace” setting that may be exporting as blank.
  • Navigate to the application’s install directory (e.g., C:\Program Files\VendorApp\Config\db_settings.json) and ensure the XmlNamespaceURI key contains a valid string rather than "".
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt to clear any cached execution plans.

Step 4: Clear the Procedure Cache

  • If the error persists due to a cached execution plan from before the fix, flush the specific plan to force a recompile.
  • Run the following command in a new query window:
  DBCC FREEPROCCACHE;
  • Note: Use this with caution in production environments as it will cause a temporary performance dip while plans are recompiled.

Alternative or Verification Steps

  • Verification: Re-run the corrected query in SSMS. If successful, the result set should return an XML column without throwing Msg 6862. You can also check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER to confirm the error ID is no longer being logged.
  • Alternative: If modifying the vendor application’s source code is not possible, create a wrapper stored procedure that strips or validates the XMLSCHEMA parameter before passing it to the underlying dynamic SQL execution (sp_executesql).

How to fix Error 6860 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6860 in Microsoft SQL Server 2025

Why This Error Happens

Error 6860 occurs when a FOR XML query attempts to combine the XMLDATA directive with either a ROOT directive or a custom row element name. SQL Server’s XML parsing engine treats XMLDATA as a legacy schema-generation directive that is structurally incompatible with modern root/row tag customization, since both features compete to control the top-level structure of the resulting XML document. This is a syntax-level conflict enforced by the T-SQL parser and is not related to permissions or corrupted files, but rather to deprecated query construction.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the query referenced in the error log or application stack trace.
  • Search specifically for the keywords XMLDATA, ROOT(, or a row tag name directly following RAW or AUTO (e.g., FOR XML RAW('RowName')).
  • Example of a broken query:
  SELECT * FROM Employees FOR XML AUTO, XMLDATA, ROOT('Employees')

Step 2: Remove the Deprecated XMLDATA Directive

  • Since XMLDATA has been deprecated since SQL Server 2005 in favor of XSD, strip it from the query entirely.
  • If you require schema information, replace XMLDATA with the XMLSCHEMA directive instead, which is compatible with ROOT and row names.
  • Corrected syntax example:
  SELECT * FROM Employees FOR XML AUTO, XMLSCHEMA, ROOT('Employees')

Step 3: Isolate ROOT and Row Tag Usage

  • If schema generation is not actually needed, simply drop XMLDATA and keep your ROOT or row name definitions as the primary structure controller.
  • For RAW mode, ensure the row tag name is passed as a single argument and not combined with schema flags:
  SELECT * FROM Employees FOR XML RAW('Employee'), ROOT('Staff')

Step 4: Update Linked Applications or ORM Mappings

  • Check any middleware (e.g., .NET Entity Framework, SSIS packages, or Power BI data connectors) running on Windows Server 2025 that might be auto-generating this legacy syntax.
  • Update connection strings or stored procedures to use the TYPE directive alongside XMLSCHEMA if typed XML is required downstream.

Step 5: Recompile and Test Stored Procedures

  • If the query resides inside a stored procedure, recompile it using:
  EXEC sp_recompile 'dbo.YourStoredProcedureName';
  • Save the updated script and redeploy it to the production environment via SSMS or Azure Data Studio.

Alternative or Verification Steps

  • Verify the Fix: Re-run the corrected query directly in SSMS against SQL Server 2025; a successful execution will return a valid XML result set with the proper <Staff> or custom root wrapping the <Employee> rows without throwing Error 6860.
  • Alternative Approach: If legacy XSD schema generation is a strict business requirement and cannot use XMLSCHEMA, decouple the query into two separate calls—one for the raw data (using ROOT) and a second schema-only query using FOR XML AUTO, XMLDATA without the ROOT directive—then merge the outputs at the application layer.

How to fix Error 6857 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6857 – Invalid XML Identifier in FOR XML ROOT

Why This Error Happens

This error occurs when the ROOT clause in a FOR XML query is assigned a name that violates XML naming specifications, typically because the identifier starts with a numeral, a reserved character, or a space. SQL Server strictly validates the root element name against W3C XML naming rules before serialization, and any non-compliant starting character—such as a digit, hyphen, or symbol—triggers an immediate parsing failure. This is frequently caused by dynamically generated column names or concatenated string variables being passed directly into the ROOT('name') parameter without sanitization.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Character

  • Review the exact error message output; it specifies the invalid character and its hexadecimal Unicode value (e.g., 0x0032 for the numeral ‘2’).
  • Locate the specific T-SQL query using FOR XML AUTO, ROOT('YourTagName') or PATH mode that triggered the event in SQL Server Management Studio (SSMS).
  • Check if the tag name is being generated dynamically via a variable, such as DECLARE @RootName NVARCHAR(50).

Step 2: Sanitize the Root Tag Naming Convention

  • Ensure the identifier adheres to XML 1.0 naming standards: it must start with a letter or an underscore (_), never a digit or punctuation mark.
  • Manually rewrite the query to hardcode a valid static name if the tag is static: SELECT * FROM Employees FOR XML AUTO, ROOT('EmployeeData').
  • If using a variable, add a prefix to the dynamic root name to bypass numeral restrictions: SET @RootName = 'Tag_' + @DynamicValue.

Step 3: Implement Validation Logic for Dynamic Queries

  • For environments using dynamic SQL in Windows Server 2025 (via SQL Agent jobs or Integration Services), add a T-SQL function to strip invalid leading characters before execution.
  • Utilize a CASE statement or PATINDEX to check if the first character of the variable is numeric (PATINDEX('[0-9]', @RootName)) and prepend an underscore if true.
  • Restart the specific SQL Server Agent job via the SSMS Object Explorer to clear any cached execution plans related to the faulty string.

Step 4: Check Application-Side Configuration

  • If the query originates from an external application (e.g., a .NET Core service running on Windows 11), audit the application’s connection string or ORM (Object-Relational Mapping) configuration for hardcoded tag generation logic.
  • Update the application code to validate string inputs against the NCName (Non-Colonized Name) production rules prior to sending the query to the SQL Server 2025 instance.

Alternative or Verification Steps

  • Verification: Re-run the exact FOR XML query in a new query window in SSMS; a successful execution will return a valid XML result set in the results grid without throwing Error 6857.
  • Alternative: If the dynamic name cannot be easily sanitized, switch the query syntax to use FOR XML PATH('') without an explicit ROOT clause, and manually wrap the result in a valid static root tag using string concatenation in the application layer instead of the T-SQL layer.

How to fix Error 6858 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6858 – Invalid Character in XML Schema URI

Why This Error Happens

Error 6858 occurs when SQL Server attempts to parse or register an XML schema collection whose namespace URI contains an invalid or non-printable character that violates XML 1.0 specification rules (such as control characters, unescaped symbols, or malformed Unicode sequences). This is typically caused by a corrupted schema file, improper encoding during export/import (e.g., ANSI vs. UTF-8 mismatches), or manual editing of XSD files that introduced hidden characters. It can also surface after migrating databases from older SQL Server versions where legacy XML schema collections contained characters that newer parsing engines (used in SQL Server 2025) now strictly reject.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate XML schema collections in the affected database:
  • SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;
  • Review the output for the specific %c character and hex code (0x%04X) referenced in the error message.
  • Cross-reference the hex value using a Unicode table to confirm which character is causing the violation (common culprits: 0x0000–0x001F control characters).

Step 2: Export and Sanitize the XML Schema File

  • Export the problematic schema collection to a .xsd file using SQL Server Management Studio (SSMS) or PowerShell:
  • bcp "SELECT xml_schema_namespace FROM YourDB.sys.xml_schema_collections WHERE name = 'YourSchemaName'" queryout C:\Temp\schema_export.xsd -c -T -S YourServerName
  • Open the file in a hex editor (such as HxD on Windows 11/Server 2025) instead of a standard text editor to detect and remove the hidden/invalid byte sequence.
  • Save the corrected file explicitly as UTF-8 without BOM to avoid re-introducing encoding artifacts.

Step 3: Drop and Recreate the XML Schema Collection

  • Drop the corrupted schema collection from the database:
  • DROP XML SCHEMA COLLECTION YourSchemaName;
  • Re-import the sanitized .xsd file using a CREATE XML SCHEMA COLLECTION statement, pointing to the cleaned file content:
  • CREATE XML SCHEMA COLLECTION YourSchemaName AS N'<sanitized_schema_content_here>';
  • Ensure the SQL Server service account has read permissions on the file path (e.g., C:\Temp\) if loading via OPENROWSET(BULK...).

Step 4: Update Application Connection Strings and Collation Settings

  • If the issue stems from client-side XML generation (e.g., a .NET application running on Windows Server 2025), verify the connection string specifies Encrypt=False or proper TLS settings are not mangling character streams.
  • Check that the database collation (e.g., SQL_Latin1_General_CP1_CI_AS) matches the expected character set used by the application layer to prevent re-encoding corruption on next write.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query or stored procedure that triggered Error 6858; additionally, execute SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; to confirm the schema loads without throwing a parsing exception.
  • Alternative Solution: If the hex editor approach fails to resolve the issue, restore the specific table or schema collection from a pre-migration backup (prior to the corruption event) and re-apply only the schema collection object using sp_help to compare metadata differences before merging back into the live Windows Server 2025 environment.

How to fix Error 6859 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6859 – Row Tag Name Restriction in FOR XML

Why This Error Happens

This error occurs when a T-SQL query specifies a row tag name (e.g., FOR XML AUTO, ROOT('RowName') or an explicit row element identifier) while using AUTO or EXPLICIT mode instead of RAW or PATH mode. SQL Server 2025’s XML parsing engine only permits custom row-level tag naming when the query explicitly uses RAW or PATH mode, since AUTO and EXPLICIT modes generate row tags automatically based on table aliases or column mappings. This is a query syntax validation issue rather than a server configuration or permissions problem, meaning it is almost always caused by malformed or migrated T-SQL code rather than an environment fault.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Windows Event Viewer (Event ID 6859) under Applications and Services Logs > MSSQLSERVER to locate the timestamp of the failure.
  • Cross-reference the timestamp with recent query executions using Extended Events or sys.dm_exec_query_stats to pull the exact query text.
  • Look specifically for FOR XML AUTO or FOR XML EXPLICIT clauses combined with a row name parameter, such as FOR XML AUTO, ELEMENTS, ROOT('Data') incorrectly paired with row tag overrides.

Step 2: Correct the FOR XML Mode Syntax

  • Open the query in SQL Server Management Studio (SSMS) 2025 or Azure Data Studio.
  • Change the XML mode from AUTO or EXPLICIT to RAW if you need to rename the row element, using syntax like:
    SELECT * FROM TableName FOR XML RAW('CustomRowName')
  • Alternatively, switch to PATH mode for more granular control:
    SELECT * FROM TableName FOR XML PATH('CustomRowName')
  • Remove any row tag name argument if you intend to keep AUTO or EXPLICIT mode, since those modes do not support custom row naming.

Step 3: Validate Application and ORM-Generated Queries

  • If the query is generated dynamically by an application layer (e.g., Entity Framework, a .NET service, or a reporting tool), inspect the data access layer code for hardcoded FOR XML clauses.
  • Update the query-building logic in the application source (commonly found in stored procedures under Programmability > Stored Procedures in SSMS, or in .cs/.vb files handling XML serialization) to use PATH mode consistently.
  • Redeploy the corrected stored procedure using ALTER PROCEDURE and recompile dependent objects with sp_recompile.

Step 4: Test in a Non-Production Environment

  • Run the corrected query against a staging or development instance of SQL Server 2025 on Windows Server 2025/Windows 11 to confirm the XML output renders as expected.
  • Compare the resulting XML structure against the application’s expected schema to ensure row tags appear correctly.

Alternative or Verification Steps

  • Execute the corrected query directly in SSMS and confirm no error 6859 appears in the Messages tab, then verify the generated XML contains the expected custom row tag names.
  • If switching modes is not feasible due to application dependencies on EXPLICIT mode’s tag/parent hierarchy, restructure the query to remove the row name argument entirely and instead use the mode’s native tag-naming conventions (e.g., naming columns with Tag and Parent identifiers for EXPLICIT mode).

How to fix Error 6855 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6855 – Inline Schema Not Supported with FOR XML PATH

Why This Error Happens

This error occurs when a FOR XML PATH query attempts to use the XMLSCHEMA directive or includes inline schema generation, which is a feature exclusive to FOR XML AUTO and FOR XML RAW modes. SQL Server 2025 enforces stricter XML compliance validation during query parsing, causing it to reject syntax combinations that were previously ignored or silently handled in earlier engine versions. This typically surfaces after migrating legacy T-SQL scripts or stored procedures from older SQL Server instances (such as 2012 or 2016) to a new Windows Server 2025 environment without updating the XML generation syntax.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Syntax

  • Open SQL Server Management Studio (SSMS) and locate the stored procedure or script referenced in the error log (Event Viewer path: Applications and Services Logs > MSSQLSERVER).
  • Search the query text for the pattern FOR XML PATH ('element'), XMLSCHEMA.
  • Confirm that the XMLSCHEMA keyword is present directly adjacent to the PATH clause, as this is the invalid combination triggering Error 6855.

Step 2: Remove or Refactor the Inline Schema Declaration

  • Delete the XMLSCHEMA keyword and any associated namespace identifiers (e.g., XMLSCHEMA('http://schemas.yourcompany.com')) from the query.
  • If a schema is strictly required for downstream validation, rewrite the query to use FOR XML AUTO, XMLSCHEMA instead of PATH, provided the table structure supports auto-generated hierarchy.
  • Alternatively, generate the schema separately using FOR XML PATH for data retrieval and a distinct query using FOR XML AUTO, XMLDATA for schema metadata, then merge the outputs at the application layer.

Step 3: Update Compatibility Level Settings

  • Open a new query window in SSMS and check the current database compatibility level by running:
    SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is below 170 (SQL Server 2025), update it using:
    ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-run the original query to confirm the parser now evaluates the syntax under the correct engine rules.

Step 4: Clear Cached Execution Plans

  • Since SQL Server may cache the invalid execution plan from before the fix, flush the plan cache for the specific database using:
    DBCC FLUSHPROCINDB (db_id('YourDatabaseName'));
  • Restart the SQL Server service via services.msc on Windows Server 2025 if the error persists after the cache flush.

Alternative or Verification Steps

  • Verify the fix by executing the modified stored procedure in a test environment and confirming the XML output returns correctly without Error 6855 appearing in sys.messages logs.
  • If refactoring is not immediately feasible, use FOR XML AUTO as a temporary alternative to PATH for simple table structures, as it natively supports the XMLSCHEMA directive without triggering this validation error.

How to fix Error 6856 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6856 (FOR XML Invalid XML Identifier)

Why This Error Happens

This error occurs when a FOR XML query (typically using AUTO or PATH mode) attempts to generate an XML row tag or element name from a column or table alias that contains characters not permitted in XML identifiers, such as spaces, symbols, or a name starting with a digit. SQL Server allows these names in relational schemas because T-SQL naming rules are more permissive than the W3C XML naming specification. The engine detects the illegal character during serialization and halts output generation rather than producing malformed, non-compliant XML.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column or Alias

  • Run the query in SQL Server Management Studio (SSMS) and note the exact character and hex code reported in the error message (e.g., 0x0020 for a space, or a leading 0x0031 for a digit).
  • Review your SELECT statement for any column names or table aliases used directly as XML tag sources, especially ones pulled from legacy databases with bracketed identifiers like [Order Date] or [1stPayment].
  • Check views or computed columns feeding into the FOR XML clause, as inherited names often carry forbidden characters.

Step 2: Rename Columns Using Valid Aliases

  • Modify the SELECT statement to assign a clean, XML-compliant alias to every column that will become an element or attribute name.
  • Example fix: change SELECT [Order Date] FROM Sales FOR XML AUTO to SELECT [Order Date] AS OrderDate FROM Sales FOR XML AUTO.
  • Ensure aliases start with a letter or underscore and contain only letters, digits, hyphens, underscores, or periods (no spaces or special symbols).

Step 3: Switch to PATH Mode for Granular Control

  • If AUTO mode is causing the issue due to table/alias naming you cannot easily change, switch to FOR XML PATH('Row') to manually define safe tag names.
  • Use the syntax SELECT [Order Date] AS '@OrderDate' or AS 'OrderDate' within the PATH clause to explicitly control both element and attribute naming.
  • This avoids relying on SQL Server to auto-generate tag names from potentially invalid source identifiers.

Step 4: Validate XML Schema Compliance (If Using XSD)

  • If the output XML is validated against an XSD schema afterward, confirm that your renamed elements still match the expected schema definitions in your application layer.
  • Update the consuming application’s XML parser or schema file (.xsd) if column renaming changes the structural contract.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm the XML output renders fully without truncation or Error 6856 appearing in the Messages pane.
  • As a quick alternative, wrap the entire query in an outer SELECT that aliases all columns to generic, safe names (e.g., col1, col2) before applying the FOR XML clause, which bypasses the need to touch the underlying table schema.

How to fix Error 6853 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6853 in Microsoft SQL Server 2025

Why This Error Happens

Error 6853 occurs when a FOR XML PATH query attempts to use a column alias path (e.g., 'node/@attribute' or 'node/text()') on a column whose underlying data type is XML or a CLR (Common Language Runtime) user-defined type. SQL Server cannot apply a final path step—such as an attribute or element directive—directly to these complex data types because they are not treated as simple scalar text nodes during XML serialization. This typically happens when a query mixes relational scalar columns with XML-typed or CLR-typed columns under the same PATH mode without explicit casting or the TYPE directive.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column in the Query

  • Review the T-SQL query generating the error and locate the column alias referenced in the error message (e.g., Column 'node/@id').
  • Check the source table schema using sp_help 'YourTableName' or query sys.columns to confirm if the column is of type xml, geography, geometry, or a custom CLR type.
  • Run the query in SQL Server Management Studio (SSMS) 21 with “Include Actual Execution Plan” disabled to isolate the parsing error quickly.

Step 2: Cast or Convert the XML/CLR Column Appropriately

  • If the column is genuinely XML and you want it embedded as a child node, remove the attribute/text() path step and let SQL Server handle it natively, or explicitly convert it: CONVERT(NVARCHAR(MAX), YourXmlColumn).
  • For CLR types (like geography or geometry), convert to a string representation first: YourCLRColumn.ToString() or CAST(YourCLRColumn AS NVARCHAR(MAX)).
  • Update the query syntax from YourXmlColumn AS 'node/@attribute' to CONVERT(NVARCHAR(MAX), YourXmlColumn) AS 'node/@attribute'.

Step 3: Restructure the FOR XML PATH Clause

  • If you need the raw XML structure preserved (not stringified), remove the trailing path step for that specific column and move it outside the PATH row constructor into a separate TYPE directive.
  • Example fix: Replace SELECT XmlCol AS 'Data/@Value' FROM Table FOR XML PATH('Root') with SELECT (SELECT XmlCol FOR XML PATH(''), TYPE) AS 'Data' FROM Table FOR XML PATH('Root').
  • Save the modified query in a .sql file under your project directory (e.g., C:\Scripts\SQL\FixedQuery.sql) and re-execute via sqlcmd or SSMS 21.

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • Open PowerShell as Administrator on Windows Server 2025 and check your current build: SELECT @@VERSION;.
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025, as early builds sometimes mishandle XML/CLR type inference in FOR XML clauses.
  • Install the patch and restart the SQL Server service via services.msc or Restart-Service -Name 'MSSQLSERVER'.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS 21 and confirm the result set generates valid XML output without throwing Error 6853; validate the output using SELECT ... FOR XML PATH('Root'), TYPE and inspect the resulting xml data type column in the results grid.
  • If the error persists, isolate the query by removing columns one-by-one to confirm no other XML/CLR columns (such as hidden computed columns referencing CLR functions) are implicitly included via SELECT *.

How to fix Error 6854 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6854 — Invalid Column Alias for XML Processing Instruction

Why This Error Happens

This error occurs when a FOR XML PATH query attempts to generate an XML processing instruction using an incorrectly formatted column alias. SQL Server expects the alias to strictly follow the processing-instruction(target) syntax, but the query instead uses a malformed variant—such as missing parentheses, an invalid target name, or extra whitespace/characters inside the alias string. This is purely a T-SQL syntax issue within the query itself and is not caused by server configuration, permissions, or corrupted files.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Open the query or stored procedure referenced in the error message/stack trace.
  • Search for the FOR XML PATH clause combined with a column alias that references “processing-instruction”.
  • Check SQL Server Management Studio (SSMS) error details or the Windows Event Viewer (Event ID 6854) under Applications and Services Logs > MSSQLSERVER for the exact query context.

Step 2: Correct the Column Alias Syntax

  • Ensure the alias is written exactly as processing-instruction(target), where target is a valid XML processing instruction name (no spaces, must start with a letter).
  • Example of an invalid alias:
  SELECT col1 AS [processing-instruction stylesheet]
  FOR XML PATH('')
  • Example of a valid alias:
  SELECT col1 AS [processing-instruction(stylesheet)]
  FOR XML PATH('')
  • Double-check that the target name does not contain the reserved string “xml” (case-insensitive), as SQL Server disallows this per the W3C XML specification.

Step 3: Test the Query in Isolation

  • Run the corrected query directly in SSMS or Azure Data Studio connected to your SQL Server 2025 instance.
  • Confirm the XML output renders the processing instruction correctly, e.g., <?stylesheet ...?>.
  • If the query is inside a stored procedure or view, redeploy the updated object:
  ALTER PROCEDURE dbo.YourProcedureName
  AS
  BEGIN
      -- corrected query here
  END

Step 4: Review Application or ORM-Generated Queries

  • If the query is dynamically generated by an application (e.g., via Entity Framework, a reporting tool, or a custom data layer), inspect the code that builds the alias string.
  • Update the source code or template to always wrap the target in parentheses using string formatting, e.g.:
  string alias = $"processing-instruction({targetName})";
  • Redeploy the application or report after the fix.

Alternative or Verification Steps

  • Verify the fix by executing the query/procedure again and confirming no Error 6854 appears in SSMS or the Windows Application Event Log on Windows Server 2025/Windows 11.
  • As an alternative, if dynamic target names are required, validate and sanitize the target string in application code before query execution to guarantee it conforms to processing-instruction(target) format prior to sending it to SQL Server.

How to fix Error 6851 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6851 – Invalid Data Type for Attribute-Centric XML Serialization in FOR XML PATH

Why This Error Happens

This error occurs when a FOR XML PATH query attempts to serialize a column whose data type is not supported for attribute-centric XML output, such as text, ntext, image, sql_variant, xml, or CLR user-defined types used directly as attributes. SQL Server 2025 enforces stricter type validation during XML serialization, so columns aliased with the @ attribute prefix must resolve to a scalar type that can be safely converted to a string representation. This typically surfaces after a schema change, a data type migration (like upgrading deprecated text/ntext columns), or when a query was written against an older SQL Server version with looser type coercion rules.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Run the failing query and note the full error message, which includes the column name/alias in the %.*ls placeholder.
  • Check the SELECT list for any column mapped to an XML attribute (using AS '@AttributeName' or implicit path-based aliasing).
  • Use sp_help 'YourTableName' or query sys.columns joined with sys.types to confirm the exact data type of the flagged column.

Step 2: Cast or Convert the Column to a Supported Type

  • Wrap the problematic column in an explicit CAST or CONVERT function, for example: CAST(YourColumn AS NVARCHAR(MAX)) AS '@AttributeName'.
  • For sql_variant columns, extract the base value first using CONVERT(NVARCHAR(MAX), SQL_VARIANT_PROPERTY(YourColumn, 'BaseType')) logic or a direct cast depending on the stored type.
  • For xml or CLR type columns, convert to NVARCHAR(MAX) before assigning them as an attribute, or restructure the query to use element-centric mode (FOR XML PATH('') without the @ prefix) instead.

Step 3: Update Deprecated Data Types in the Schema

  • If the column uses legacy types like text, ntext, or image, run ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR(MAX) (or NVARCHAR(MAX)/VARBINARY(MAX) as appropriate).
  • Back up the table first using SQL Server Management Studio (SSMS) 21 or BACKUP TABLE scripts, since altering column types on large tables can lock resources.
  • Re-run the original FOR XML PATH query to confirm the schema change resolves the serialization conflict.

Step 4: Rebuild and Test the XML Query Logic

  • Re-test the query in SSMS connected to your SQL Server 2025 instance, confirming the execution plan no longer throws Error 6851.
  • If the query is embedded in a stored procedure or SSIS package, redeploy the updated object so cached execution plans don’t reference the old data type definitions.

Alternative or Verification Steps

  • Verify the fix by executing the query with SET SHOWPLAN_XML ON disabled and confirming the result set returns valid XML output without errors in the Messages tab of SSMS.
  • As an alternative, if casting is not feasible due to application constraints, switch the affected columns to element-centric XML formatting (remove the @ prefix) since elements support a broader range of implicit type conversions than attributes.

How to fix Error 6852 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6852 in FOR XML PATH Queries

Why This Error Happens

This error occurs because of a column ordering violation in a FOR XML PATH query where attribute-centric columns (those aliased with @AttributeName) are defined after a non-attribute (element-centric) sibling column in the SELECT statement. SQL Server’s XML construction engine processes columns sequentially and requires that all attributes for a given node be declared before any child elements or text nodes are generated. This is not a database corruption or permissions issue, but strictly a T-SQL syntax/ordering problem introduced by the query author or an automated report-generation tool.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact stored procedure, view, or ad-hoc query referenced in the SQL Server error log or Activity Monitor that triggered Error 6852.
  • Use sys.dm_exec_query_stats combined with sys.dm_exec_sql_text to pull the exact query text if the error was logged without the full query.
  • Search specifically for the FOR XML PATH clause and note the column list immediately preceding it.

Step 2: Reorder the Column Aliases in the SELECT Statement

  • Open the query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Move all columns aliased with the @ prefix (e.g., AS '@ID', AS '@Type') to the top of the column list, immediately after the SELECT keyword.
  • Ensure non-attribute columns (e.g., AS 'Name', AS 'Description', or unnamed columns generating nested elements) appear after all attribute columns.
  • Example correction:
  -- Incorrect (causes 6852)
  SELECT Name AS 'Name', ID AS '@ID' FROM Employees FOR XML PATH('Employee')

  -- Corrected
  SELECT ID AS '@ID', Name AS 'Name' FROM Employees FOR XML PATH('Employee')

Step 3: Validate Nested Subqueries and Computed Columns

  • Check for nested FOR XML PATH subqueries used to generate child elements; ensure these subqueries are also placed after attribute columns in their respective parent SELECT scope.
  • If using CROSS APPLY or derived tables to build complex XML hierarchies, verify that the attribute-generating columns within each derived table maintain the same “attributes-first” rule independently at every nesting level.

Step 4: Test the Query in Isolation

  • Run the corrected query directly in SSMS against a non-production instance running on Windows Server 2025 to confirm the XML output generates without throwing Error 6852.
  • Check the Messages tab in SSMS for a clean execution with no XML parsing warnings.

Step 5: Update Application Code or SSIS Packages

  • If the query is embedded in a .NET application, SSIS package, or Power BI data source, redeploy the corrected query string to the relevant .dtsx package or application binary.
  • Restart the associated application pool in IIS (if applicable) or the SQL Server Agent job to clear any cached execution plans referencing the old, malformed query.

Alternative or Verification Steps

  • Verification: Execute the query manually in SSMS and confirm the XML result pane renders correctly with attributes nested inside the opening tag of their parent element (e.g., <Employee ID="1"><Name>John</Name></Employee>).
  • Alternative: If reordering columns is not feasible due to complex dynamic SQL generation, wrap the attribute logic in a separate subquery using CROSS APPLY to explicitly control the column emission order before the outer FOR XML PATH call is executed.

How to fix Error 6849 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6849 – Invalid FOR XML PATH Simple Path Expression

Why This Error Happens

This error occurs when the column alias used in a FOR XML PATH query contains an invalid path expression, specifically a double slash (//) or a leading/trailing single slash (/). SQL Server’s XML path parser interprets these aliases as XPath-like node paths, and malformed slash placement violates the simple path expression syntax rules. This typically results from manually constructed dynamic SQL, copy-pasted query templates, or programmatically generated column aliases that fail to sanitize the path string before execution.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Alias

  • Review the full error message text, which includes the specific column name in the format: FOR XML PATH error in column '%.*ls'.
  • Open SQL Server Management Studio (SSMS) and locate the exact query from the error log or ERRORLOG file, typically found at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Search the query text for aliases formatted with AS '...' that contain slash characters.

Step 2: Correct the Malformed Path Syntax

  • Remove any double slashes (//) from the column alias; replace with a single forward slash (/) if node nesting was intended.
  • Strip leading slashes (e.g., /Node/SubNode should become Node/SubNode).
  • Strip trailing slashes (e.g., Node/SubNode/ should become Node/SubNode).
  • Example fix: Change SELECT col AS '/Root//Child/' to SELECT col AS 'Root/Child'.

Step 3: Validate Dynamic SQL Generation Logic

  • If the alias is generated programmatically (via C#, PowerShell, or a stored procedure), inspect the string concatenation logic.
  • Add a sanitation function or REPLACE() call to strip consecutive slashes before the query is executed:
  • SET @ColumnAlias = REPLACE(@ColumnAlias, '//', '/')
  • Trim leading and trailing slashes using TRIM(@ColumnAlias, '/') (supported in SQL Server 2022 and later, including SQL Server 2025).

Step 4: Test the Query in Isolation

  • Run the corrected SELECT statement independently in a new SSMS query window against a test database.
  • Confirm the query executes without throwing Error 6849 before redeploying it to production stored procedures or reports.

Alternative or Verification Steps

  • Verify the fix by executing the query against a small dataset and confirming the resulting XML output contains the expected node structure without parser exceptions.
  • If the alias must dynamically support nested paths, use the PATH('NodeName') explicit syntax instead of inline slash-delimited aliases to avoid ambiguity in path construction.

How to fix Error 6850 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6850 – Invalid XML Identifier in FOR XML Clause

Why This Error Happens

This error occurs when SQL Server’s FOR XML clause attempts to convert a column, table, or alias name into an XML element or attribute name, but the identifier contains characters that are not valid according to XML naming specifications. Valid XML names cannot start with numbers, spaces, or certain punctuation marks, and cannot contain characters like #, %, !, @, or embedded spaces unless properly escaped. This typically surfaces after a database migration, a schema change, or when querying legacy tables that used permissive naming conventions now exposed through a FOR XML query in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Identifier

  • Review the full error message text — it explicitly names the invalid identifier and the offending character (e.g., '#'(0x0023)).
  • Run the query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF and execute in isolation to confirm which column/table triggers the fault.
  • Check system views using SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName') to cross-reference suspicious names.

Step 2: Alias the Problematic Column or Table

  • In your SELECT statement, wrap the offending column in an alias using valid XML-safe characters (letters, digits, underscores, hyphens, periods — starting with a letter or underscore).
  • Example fix:
  SELECT [Order#ID] AS OrderID
  FROM Sales.Orders
  FOR XML AUTO
  • Avoid starting aliases with numbers or using reserved XML tokens like xml (case-insensitive) as a prefix.

Step 3: Rename the Source Object (If Alias Is Not Feasible)

  • For permanent fixes, rename the underlying column or table using sp_rename:
  EXEC sp_rename 'Sales.Orders.Order#ID', 'OrderID', 'COLUMN';
  • Update any dependent views, stored procedures, or application code referencing the old name on both Windows Server 2025 and Windows 11 client environments.
  • Re-test the FOR XML query to confirm the identifier now passes validation.

Step 4: Use EXPLICIT Mode for Full Control (Advanced Scenarios)

  • If renaming is not possible due to legacy dependencies, switch from FOR XML AUTO to FOR XML EXPLICIT or FOR XML PATH, which allow manual control over output element/attribute names independent of source column names.
  • Example:
  SELECT [Order#ID] AS '@OrderID'
  FROM Sales.Orders
  FOR XML PATH('Order')

Alternative or Verification Steps

  • Verify the fix by re-running the original query and confirming Error 6850 no longer appears in the SSMS Messages pane or SQL Server Error Log (Event Viewer > Windows Logs > Application on Windows Server 2025).
  • As an alternative, use FOR JSON instead of FOR XML if XML-compliant naming is not a hard requirement for your downstream consumers, since JSON key naming rules are far less restrictive.

How to fix Error 6848 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6848 — XMLDATA Mapping Failure

Why This Error Happens

This error occurs when a FOR XML query uses the XMLDATA directive in AUTO or RAW mode against a column whose SQL data type (such as sql_variant, xml, or certain CLR user-defined types) has no corresponding XDR (XML-Data Reduced) schema type. XMLDATA is a legacy, deprecated schema-generation method that only supports a limited subset of SQL Server data types, and it has effectively been superseded by the XMLSCHEMA directive, which supports the full XSD (XML Schema Definition) type system. Because XDR was deprecated starting in older SQL Server versions and carried forward through SQL Server 2025, any query relying on it against modern or complex column types will fail with Error 6848.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Column

  • Locate the exact SELECT ... FOR XML AUTO, XMLDATA or FOR XML RAW, XMLDATA statement referenced in the SQL Server error log or application exception trace.
  • Run the query in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance and note the specific column name reported in the error message (the %.*ls placeholder).
  • Check the column’s data type using:
  SELECT COLUMN_NAME, DATA_TYPE 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_NAME = 'YourTableName';

Step 2: Replace XMLDATA with XMLSCHEMA in the Query

  • Modify the query to use XMLSCHEMA instead of XMLDATA, for example:
  SELECT * FROM YourTable FOR XML AUTO, XMLSCHEMA;

or for RAW mode:

  SELECT * FROM YourTable FOR XML RAW, XMLSCHEMA;
  • If a specific schema namespace is required, specify it explicitly:
  SELECT * FROM YourTable FOR XML AUTO, XMLSCHEMA('urn:your-namespace'), ELEMENTS;

Step 3: Update Application Code and Stored Procedures

  • Search your application’s source code, ORM mappings, and stored procedures (using SSMS “Find in Files” or sp_helptext) for any remaining references to XMLDATA.
  • Update connection strings or middleware (e.g., ADO.NET, JDBC) that may still expect XDR-formatted XML output, since XMLSCHEMA produces XSD-compliant XML with a different structure.
  • Recompile and redeploy any affected stored procedures:
  EXEC sp_recompile 'YourStoredProcedureName';

Step 4: Validate Data Types Against XDR/XSD Compatibility

  • If you must retain XMLDATA for legacy compatibility reasons, avoid using unsupported types like sql_variant, xml, hierarchyid, or spatial types in the SELECT list.
  • Cast unsupported columns to a compatible base type (e.g., VARCHAR, INT, DATETIME2) before including them in the XML output:
  SELECT CAST(YourColumn AS NVARCHAR(MAX)) AS YourColumn 
  FROM YourTable FOR XML AUTO, XMLDATA;

Step 5: Restart Dependent Services (If Applicable)

  • If the query is embedded in an SSIS package, SSRS report, or a cached execution plan, clear the procedure cache:
  DBCC FREEPROCCACHE;
  • Restart the SQL Server Agent service or affected application pool in IIS on Windows Server 2025 to ensure cached query plans are refreshed.

Alternative or Verification Steps

  • Re-run the original query with XMLSCHEMA in SSMS and confirm it executes successfully, returning well-formed XML with an embedded <xsd:schema> element instead of throwing Error 6848.
  • As an alternative, migrate the query entirely to FOR XML PATH or FOR JSON AUTO mode if schema generation isn’t strictly required — this bypasses the XDR/XMLSCHEMA limitation entirely and is the Microsoft-recommended modern approach.

How to fix Error 6846 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6846 — Missing XML Namespace Prefix Declaration in FOR XML

Why This Error Happens

This error occurs when a FOR XML query (typically using EXPLICIT or PATH mode) references a namespace prefix on a column or element name without first declaring that prefix in the WITH XMLNAMESPACES clause or the directive syntax. SQL Server’s XML serialization engine requires every prefix used in a tag name (e.g., prefix:ElementName) to have a corresponding namespace URI binding before it can construct valid XML output. This is commonly caused by a typo in the prefix name, a missing WITH XMLNAMESPACES block, or copy-pasted query logic from a different schema context where the declaration was stripped out.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Prefix

  • Check the SQL Server error log or SSMS output pane for the exact prefix name and column/element name referenced in the message (%.*ls).
  • Locate the specific FOR XML PATH, FOR XML EXPLICIT, or FOR XML AUTO statement in your stored procedure, view, or ad-hoc query that is throwing Error 6846.
  • Use SELECT OBJECT_DEFINITION(OBJECT_ID('YourProcName')) in SSMS to pull the full T-SQL text if the query is embedded in a compiled object.

Step 2: Add or Correct the WITH XMLNAMESPACES Declaration

  • Prepend a WITH XMLNAMESPACES clause before your SELECT statement, explicitly binding every prefix used in the column aliases.
  • Example fix:
WITH XMLNAMESPACES ('http://example.com/ns' AS ns1)
SELECT col1 AS '[ns1:ElementName]'
FROM YourTable
FOR XML PATH('root');
  • Ensure the prefix declared (ns1 in this example) exactly matches the prefix used later in the column alias, including case sensitivity.

Step 3: Validate Nested or Default Namespace Usage

  • If using the default namespace (no prefix), confirm you are using the correct syntax: WITH XMLNAMESPACES (DEFAULT 'http://example.com/ns').
  • For FOR XML EXPLICIT mode, verify the TAG and PARENT columns in your UNION ALL structure also carry consistent prefix references across all branches of the query.
  • Re-run the query in SSMS (press Ctrl+E) to confirm the parser no longer throws Error 6846.

Step 4: Update Application or Integration Code

  • If the query is generated dynamically by an application (e.g., via Entity Framework, SSIS, or a .NET data layer), update the source code template responsible for building the FOR XML clause.
  • Redeploy the stored procedure using ALTER PROCEDURE and clear the plan cache for that object using DBCC FREEPROCCACHE (OBJECT_ID('YourProcName')) to ensure SQL Server recompiles with the corrected syntax.

Alternative or Verification Steps

  • Run the corrected query independently in SSMS against SQL Server 2025 and confirm valid XML output is returned without errors; inspect the result using the XML Editor (click the XML link in the results grid).
  • If the error persists, use SELECT * FROM sys.dm_exec_describe_first_result_set(N'YourQueryText', NULL, 0) to validate that the query compiles correctly before execution, which helps isolate schema-level binding issues from syntax issues.

How to fix Error 6847 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6847 occurs when SQL Server attempts to build or update a Full-Text Index on a table that contains a column defined with the sql_variant data type. The Full-Text Indexing engine (part of the SQL Server instance’s Full-Text and Semantic Extraction service) cannot tokenize or catalog sql_variant data because the underlying data type is ambiguous until runtime, making it incompatible with the fixed-schema requirements of the full-text catalog. This typically happens during a CREATE FULLTEXT INDEX statement or when an automated schema migration script includes all columns in a table without filtering out unsupported types.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Open SQL Server Management Studio (SSMS) and run the failing CREATE FULLTEXT INDEX or ALTER FULLTEXT INDEX statement to capture the exact column name referenced in the error message.
  • Alternatively, run the following query to list all sql_variant columns in the target table:
SELECT c.name AS ColumnName, t.name AS DataType
FROM sys.columns c
JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE t.name = 'sql_variant' AND c.object_id = OBJECT_ID('YourTableName');

Step 2: Exclude the Column from the Full-Text Index Definition

  • Modify your CREATE FULLTEXT INDEX statement to explicitly list only the columns you want indexed, omitting the sql_variant column(s).
  • Example corrected syntax:
CREATE FULLTEXT INDEX ON dbo.YourTableName(Description, Notes)
KEY INDEX PK_YourTableName
ON YourFullTextCatalog;
  • If the index already exists, use ALTER FULLTEXT INDEX ... DROP (ColumnName) to remove the specific sql_variant column from the existing catalog.

Step 3: Evaluate Schema Design (Optional but Recommended)

  • If the sql_variant column needs to be searchable, consider converting it to a more specific, indexable data type (e.g., NVARCHAR(MAX)) using a computed column or a persisted shadow column.
  • Example of a workaround using a computed column:
ALTER TABLE dbo.YourTableName
ADD Description_AsText AS CAST(Description AS NVARCHAR(4000)) PERSISTED;
  • Add this new persisted column to the full-text index instead of the original sql_variant field.

Step 4: Rebuild and Validate the Full-Text Catalog

  • Run ALTER FULLTEXT CATALOG YourFullTextCatalog REBUILD; to ensure the catalog metadata is clean after removing the incompatible column.
  • Verify the rebuild completes without further type-related errors in the SQL Server Error Log (Windows Server 2025 path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\).

Alternative or Verification Steps

  • Verify the fix by querying sys.fulltext_index_columns joined with sys.columns to confirm the sql_variant column no longer appears in the full-text index metadata.
  • If you cannot remove the column due to application dependencies, bypass full-text indexing entirely for that table and use a standard non-clustered index combined with LIKE or CONTAINS-alternative T-SQL string functions for search functionality.

How to fix Error 6843 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6843 in Microsoft SQL Server 2025

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query attempts to directly tag an xml or CLR (Common Language Runtime) data type column as a CDATA directive. The SQL Server XML engine cannot natively serialize these complex binary/XML object types into a CDATA text block without an explicit conversion step first. Essentially, the query is asking the parser to treat structured data as raw text without telling it how to “flatten” that structure into a string representation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Review the exact error message to find the column name mentioned in the %.*ls placeholder.
  • Check your T-SQL query’s SELECT statement and locate where this column is being assigned a CDATA tag mode (usually formatted as TableAlias!TagNumber!ColumnName!CDATA).
  • Confirm the source data type of that column using sp_help 'YourTableName' in SQL Server Management Studio (SSMS) 21.

Step 2: Apply Explicit Type Casting

  • Modify the query to wrap the problematic column in a CAST or CONVERT function before the CDATA tag is applied.
  • For standard xml data types, use: CAST(YourXmlColumn AS NVARCHAR(MAX)).
  • For CLR User-Defined Types (UDTs), you must first convert the type to XML (if supported by the UDT) and then cast that result to a string: CAST(CAST(YourClrColumn AS XML) AS NVARCHAR(MAX)).
  • Update the SELECT clause to use this new casted value in the CDATA mode slot.

Step 3: Verify Collation and String Length Compatibility

  • Ensure the target string type (e.g., NVARCHAR(MAX)) does not truncate the XML data; avoid using fixed-length strings like VARCHAR(255) for large XML blobs.
  • Check for collation conflicts if the CLR type involves Unicode characters that might clash with the database’s default collation settings in Windows Server 2025.
  • Re-run the query in a new SSMS query window to clear any cached execution plans that might reference the old schema.

Step 4: Restart Related SQL Services (If Issue Persists)

  • Open the Services console (services.msc) on your Windows Server 2025 host.
  • Locate SQL Server (MSSQLSERVER) or your specific named instance.
  • Right-click and select Restart to clear any transient memory locks related to CLR integration that might be causing the parser to misbehave.

Alternative or Verification Steps

  • Verification: Execute the corrected query and confirm the output XML string displays the data correctly wrapped in <![CDATA[...]]> tags without throwing Error 6843.
  • Alternative: If CLR conversion to XML is not supported by the specific UDT, bypass the CDATA directive entirely and use the standard ELEMENT or XMLTEXT modes in your FOR XML EXPLICIT schema definition, as these modes handle raw type serialization differently than CDATA blocks.

How to fix Error 6844 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6844

Why This Error Happens

Error 6844 occurs when SQL Server’s XML Schema Collection validator encounters two elements that share the same name but have conflicting type definitions, and these elements are not positioned as direct siblings within the same hierarchical level. This typically results from a malformed or inconsistent XSD schema being registered in a XML Schema Collection, often introduced during an application update, schema migration, or manual edit of the schema definition. Corrupted schema collection metadata after an in-place upgrade to SQL Server 2025 can also trigger this validation failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate schema collections in the affected database:
  • SELECT name, schema_id FROM sys.xml_schema_collections;
  • Cross-reference the element name reported in the error message (%.*ls) against the schema definitions using:
  • SELECT xml_schema_namespace(SCHEMA_NAME(schema_id), name) FROM sys.xml_schema_collections WHERE name = 'YourCollectionName';
  • Export the result to a .xsd file for manual inspection.

Step 2: Correct the XSD Structure

  • Open the exported XSD in a validator (Visual Studio 2025 or an online XSD linter works well).
  • Search for duplicate element names that exist at different nesting levels with mismatched type attributes.
  • Rename conflicting elements or consolidate them into a shared complex type if they are meant to represent the same structure.
  • Ensure elements intended to share a type are declared as direct siblings inside the same <xs:sequence> or <xs:choice> block.

Step 3: Drop and Recreate the Schema Collection

  • Back up the database before making changes:
  • BACKUP DATABASE [YourDB] TO DISK = 'C:\Backups\YourDB_PreFix.bak';
  • Drop the broken collection (ensure no columns/tables currently reference it, or alter those first):
  • DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  • Recreate it using the corrected XSD:
  • CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS N'<corrected XSD content here>';

Step 4: Apply Latest Cumulative Update

  • Open SQL Server Setup or Windows Update on Windows Server 2025 / Windows 11 and check for SQL Server 2025 Cumulative Updates.
  • Install the latest CU, as early builds of SQL Server 2025 had a known XML validation engine bug affecting nested schema collections.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after the update completes.

Alternative or Verification Steps

  • After recreating the schema collection, re-run any INSERT/UPDATE statements that previously failed with Error 6844 to confirm the validation now passes.
  • If the error persists, use sqlcmd -S localhost -Q "DBCC CHECKDB('YourDB') WITH NO_INFOMSGS" to rule out underlying database corruption affecting system catalog views related to XML schemas.

How to fix Error 6845 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6845 — Ambiguous Optional Elements in XML Schema (SQL Server 2025)

Why This Error Happens

This error occurs when SQL Server attempts to compile an XML schema collection (XSD) that contains two or more elements with the same name marked as minOccurs="0" (optional) at the same particle level, typically within an xs:choice or xs:sequence group. The SQL Server XML parser cannot deterministically validate incoming XML against the schema because it cannot distinguish which optional element instance corresponds to which declaration when both could legitimately be absent or present in ambiguous order. This is almost always caused by a malformed or hand-edited XSD file, or by a schema generated from a source system (such as an ORM, BizTalk map, or third-party export tool) that produces non-deterministic content models.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate the schema collection referenced in the error message:
  • SELECT name, schema_collection_id FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Extract the raw XSD definition for inspection:
  • SELECT xml_schema_namespace(N'dbo', N'YourSchemaName');
  • Note the exact element name reported in the error (%.*ls will be replaced with the real element name in your actual error log — check ERRORLOG or SSMS output).

Step 2: Edit the XSD to Resolve the Ambiguity

  • Open the exported XSD in a text editor or Visual Studio XML Schema Designer.
  • Locate the two sibling elements sharing the same name inside the same xs:choice or xs:sequence block.
  • Merge the duplicate optional declarations into a single element definition, or convert them into direct siblings under separate unambiguous parent groups.
  • As an alternative fix, set nillable="true" on the element and map NULL values to xsi:nil="true" instead of omitting the element entirely:
  • <xs:element name="OrderDate" type="xs:dateTime" nillable="true" minOccurs="1"/>

Step 3: Drop and Recreate the XML Schema Collection

  • Drop the broken collection (ensure no dependent XML columns/tables reference it first):
  • DROP XML SCHEMA COLLECTION dbo.YourSchemaName;
  • Recreate it using the corrected XSD:
  • CREATE XML SCHEMA COLLECTION dbo.YourSchemaName AS N'<paste corrected XSD here>';
  • If the schema is tied to a column, re-run ALTER TABLE to reapply the CONTENT/DOCUMENT binding if it was temporarily removed.

Step 4: Update the Source Application Mapping Layer

  • If the XSD originates from an external tool (BizTalk, Entity Framework, custom ETL job), regenerate the schema export after confirming the source data contract no longer emits duplicate optional nodes.
  • On Windows Server 2025, check any scheduled SSIS packages (%ProgramFiles%\Microsoft SQL Server\160\DTS\Packages\) that may auto-generate or re-upload this schema, and update the package’s XML source definition accordingly.

Alternative or Verification Steps

  • Validate the corrected XSD independently before reloading it into SQL Server by using xmllint --schema YourSchema.xsd --noout (available via Windows Subsystem for Linux or a standalone XML validator) to confirm there are no remaining content-model ambiguities.
  • As a quick verification, insert a test XML document that includes both optional elements in varying combinations (both present, one present, both absent) against the typed XML column bound to the schema collection and confirm no Error 6845 is raised on INSERT.

How to fix Error 6841 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6841 – FOR XML Serialization Failure

Why This Error Happens

Error 6841 occurs when the FOR XML clause in a SQL query attempts to serialize data containing control characters (such as 0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F) that are illegal in the XML 1.0 specification. This typically happens when source data was imported from legacy systems, flat files, or external applications that allow binary or control characters within character/text columns. SQL Server’s XML serialization engine strictly validates character ranges and refuses to produce malformed XML output, halting the query rather than silently corrupting the result set.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Character and Column

  • Run the query without FOR XML first to isolate the result set and inspect suspicious columns manually.
  • Use a diagnostic query with PATINDEX to locate illegal characters, for example:
    SELECT PATINDEX('%[' + CHAR(0) + '-' + CHAR(8) + CHAR(11) + CHAR(12) + CHAR(14) + '-' + CHAR(31) + ']%', YourColumn) FROM YourTable
  • Note the exact 0x hex code referenced in the error message (e.g., 0x0002) to confirm which character is triggering the failure.

Step 2: Cleanse or Convert the Data Using BINARY BASE64

  • If the control characters are expected (e.g., binary payloads) and must be preserved, convert the column to VARBINARY and use the BINARY BASE64 directive in your FOR XML query instead of standard text serialization.
  • Example: SELECT CAST(YourColumn AS VARBINARY(MAX)) AS [node()] FOR XML PATH(''), BINARY BASE64
  • This bypasses the XML character validation entirely by encoding the data as Base64 text.

Step 3: Strip Illegal Characters at the Source

  • If the control characters are not needed, use a REPLACE or custom cleansing function to remove them before serialization.
  • Example: UPDATE YourTable SET YourColumn = REPLACE(YourColumn, CHAR(2), '') WHERE YourColumn LIKE '%' + CHAR(2) + '%'
  • For multiple character codes, create a scalar function using PATINDEX in a loop to strip all non-XML-compliant ranges in one pass.

Step 4: Validate Application-Level Data Entry Points

  • On Windows Server 2025 / Windows 11 hosts, check the application or ETL pipeline (SSIS packages, API endpoints) that originally inserted the data, located typically under C:\Program Files\Microsoft SQL Server\160\DTS\Packages\.
  • Add input validation or sanitization logic at the application layer to prevent control characters from being written to SQL Server in the future.

Alternative or Verification Steps

  • Re-run the original FOR XML query after cleansing; if it executes without Error 6841, the fix is confirmed.
  • As a quick workaround without modifying data, wrap the column in BINARY BASE64 serialization (Step 2) to retrieve the raw data safely for client-side decoding, especially useful when data integrity must be preserved for forensic or audit purposes.

How to fix Error 6842 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6842 – Invalid XML Character During Serialization

Why This Error Happens

Error 6842 occurs when SQL Server 2025 attempts to serialize data containing control characters (such as 0x0000-0x001F, excluding tab, line feed, and carriage return) that are explicitly disallowed by the XML 1.0 specification. This typically happens when binary or legacy data containing non-printable characters is stored in a column that gets converted to XML, or when application code writes raw binary content into an NVARCHAR/VARCHAR field without proper sanitization. The underlying issue is a data integrity mismatch — the source data was never validated against XML character restrictions before being passed to a FOR XML query, XML data type method, or Service Broker message serialization.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Character and Source Column

  • Note the hexadecimal character code (0x%04X) reported in the error message — this is your primary diagnostic clue.
  • Run a diagnostic query using PATINDEX with a pattern like %[^ + char ranges ]% to locate rows containing control characters below 0x0020 (excluding 0x09, 0x0A, 0x0D).
  • Example: SELECT * FROM YourTable WHERE PATINDEX('%[' + CHAR(0) + '-' + CHAR(8) + ']%', YourColumn) > 0
  • Check the originating application, ETL job, or import process that populated this data.

Step 2: Convert the Data to Binary Instead of XML

  • As suggested by the error text, cast the problematic column to VARBINARY or VARBINARY(MAX) instead of serializing directly as XML.
  • Update the query: replace CAST(YourColumn AS XML) with CAST(YourColumn AS VARBINARY(MAX)) when the column may contain non-XML-safe bytes.
  • If using FOR XML queries, apply TYPE directive carefully and pre-filter columns with known binary content using a CASE statement to substitute a placeholder or convert to Base64.

Step 3: Sanitize Data at the Application or ETL Layer

  • Implement a cleansing function (CLR function or T-SQL scalar function) that strips or replaces disallowed control characters before insertion.
  • Example T-SQL cleansing approach: use nested REPLACE() calls or a loop with STUFF() to remove characters in the 0x00–0x1F range excluding 0x09, 0x0A, 0x0D.
  • Update SSIS packages, application connection code, or middleware (on Windows Server 2025 / Windows 11 clients) to validate incoming strings against XML 1.0 character rules prior to writing to SQL Server.

Step 4: Apply Base64 Encoding for Legitimate Binary Payloads

  • If the data is intentionally binary (e.g., encrypted blobs, hashes, or serialized objects), do not force it through XML serialization at all.
  • Use SELECT CAST(N'' AS XML).value('xs:base64Binary(sql:column("YourColumn"))', 'VARCHAR(MAX)') patterns or encode with CONVERT(VARCHAR(MAX), YourBinaryColumn, 1) to produce a safe hex/Base64 string before any XML operation.

Step 5: Patch and Update SQL Server 2025

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as XML serialization edge cases are periodically patched.
  • Check via: SELECT @@VERSION; and compare against the latest CU build listed in Microsoft’s servicing documentation.
  • Apply the update through SQL Server Setup or Windows Update (if using the integrated Windows Server 2025 servicing channel).

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 6842 after remediation; confirm it completes without throwing the serialization error, and spot-check output for data integrity.
  • If the error persists intermittently, enable SQL Server Extended Events (xml_deadlock_report channel is unrelated — instead use a custom XE session filtering on errorreported for errornumber = 6842) to capture the exact query and session context triggering the fault in production workloads.

How to fix Error 6839 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6839 – FOR XML EXPLICIT XMLTEXT Conflict with IDREFS/NMTOKENS

Why This Error Happens

This error occurs because the FOR XML EXPLICIT clause places an XMLTEXT directive on a tag that also contains fields marked with the IDREFS or NMTOKENS directives, which SQL Server’s XML engine does not support simultaneously. The underlying cause is a structural conflict in the query’s column definitions, not a server configuration or permissions issue. This typically surfaces after a schema migration, an application upgrade, or when legacy T-SQL scripts written for older SQL Server versions are executed against SQL Server 2025, where XML schema validation has become stricter.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Tag

  • Locate the exact stored procedure, view, or ad-hoc query triggering Error 6839 by checking SQL Server Management Studio (SSMS) error details or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • Note the specific tag name (%.*ls in the error message) referenced in the FOR XML EXPLICIT statement.
  • Run the query in isolation using SSMS on Windows Server 2025 or Windows 11 to reproduce the exact failure point.

Step 2: Review and Separate Column Directives

  • Open the T-SQL script and locate the SELECT statement using FOR XML EXPLICIT.
  • Check the column alias definitions formatted like TagName!TagNumber!AttributeName!Directive.
  • Identify columns using !XMLTEXT directive on the same tag number as columns using !IDREFS or !NMTOKENS.
  • Split the conflicting fields into separate tags or separate levels in the tag hierarchy so that XMLTEXT is not combined with IDREFS/NMTOKENS on the same tag.

Step 3: Rewrite Using FOR XML PATH or Native XML Methods

  • Since FOR XML EXPLICIT is a legacy syntax, migrate the query to FOR XML PATH or FOR XML AUTO, which handles mixed content and token lists more reliably in SQL Server 2025.
  • Use .value() and .nodes() XML data type methods for complex token list formatting instead of relying on EXPLICIT mode directives.
  • Test the rewritten query against a sample dataset in a non-production environment before deploying.

Step 4: Apply Latest Cumulative Update

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm the current build version via SELECT @@VERSION;.
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as XML engine parsing fixes are frequently included in servicing updates.
  • Restart the SQL Server (MSSQLSERVER) service from the Services.msc console after installation completes.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm the XML output generates without Error 6839; validate the resulting XML against your target schema using an XML validator tool.
  • If rewriting the query is not immediately feasible, use FOR XML RAW or FOR XML AUTO with TYPE directive as a temporary workaround to bypass the EXPLICIT mode restriction while planning a permanent query redesign.

How to fix Error 6840 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6840 (XMLDATA/XMLSCHEMA Namespace Conflict)

Why This Error Happens

This error occurs because the FOR XML clause in your T-SQL query is attempting to combine the XMLDATA or XMLSCHEMA directive with a namespace prefix declaration (such as WITH XMLNAMESPACES). SQL Server 2025’s query engine explicitly disallows inline schema generation when a custom namespace is applied to the output, as the schema-inference logic cannot reliably map namespace-qualified elements or attributes. This is a syntax-level restriction in the SQL parser rather than a configuration or permissions issue, meaning it will trigger consistently regardless of server load or user roles.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Locate the exact SELECT ... FOR XML statement referenced in the Event Viewer log (Application log, Source: MSSQLSERVER, Event ID: 6840).
  • Check the query text for the coexistence of XMLSCHEMA (or the deprecated XMLDATA) alongside a WITH XMLNAMESPACES clause or an xmlns prefix.

Step 2: Remove the Namespace Prefix Declaration

  • If the schema generation is required for your downstream application, strip out the namespace declaration from the query header.
  • Locate and delete the WITH XMLNAMESPACES ('uri' AS prefix) block preceding your SELECT statement.
  • Re-run the query to confirm the schema generates correctly without the namespace binding.

Step 3: Alternatively, Remove the XML Schema Directive

  • If the namespace declaration is business-critical (e.g., for SOAP or specific B2B integration standards), remove the schema generation instead.
  • Modify your FOR XML clause to exclude the XMLSCHEMA or XMLDATA keyword, leaving just FOR XML AUTO or FOR XML RAW.
  • Validate that the output XML still meets the structural requirements of the consuming application without the embedded schema.

Step 4: Restart the Application Pool or Service Context

  • Navigate to the IIS Manager or the specific service (e.g., SSRS, custom .NET app) that triggered the stored procedure.
  • Recycle the Application Pool via powershell Restart-WebAppPool -Name "YourAppPoolName" to clear any cached connection pooling errors related to the failed query.
  • Confirm the SQL Server Agent job (if applicable) is set to retry with the updated query logic.

Alternative or Verification Steps

  • Verification: Execute the corrected query directly in SSMS against the Windows Server 2025 instance; a successful run will return a valid XML result set in the “Results” grid without throwing Error 6840 in the Messages tab.
  • Alternative: If a namespace is strictly required in the final output alongside a schema, manually construct the schema using TYPE directive and CAST the result as XML, then manipulate the namespace via string concatenation post-query rather than relying on the native XMLSCHEMA directive.

How to fix Error 6836 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6836 (FOR XML EXPLICIT Column Ordering)

Why This Error Happens

This error occurs because the FOR XML EXPLICIT clause enforces a strict column ordering rule: attribute-centric IDREFS or NMTOKENS fields must be defined before any element-centric IDREFS or NMTOKEN fields in the SELECT statement. SQL Server’s XML parser processes columns sequentially when constructing the XML tree, and when it encounters an element-centric IDREFS/NMTOKEN field before its attribute-centric counterpart, it cannot correctly resolve the schema hierarchy. This is typically caused by a manually constructed query where column tags (using the Tag and Parent syntax) were added or reordered without respecting the directive precedence rules required by EXPLICIT mode.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column in the Query

  • Open the query that is throwing Error 6836 in SQL Server Management Studio (SSMS) on your Windows Server 2025/Windows 11 instance.
  • Locate the exact field name referenced in the error message (the %.*ls placeholder will show the actual column name at runtime).
  • Check whether this field uses the !TAG!COLUMN!IDREFS or !TAG!COLUMN!NMTOKENS directive with xml as the data type, and whether it is marked as element-centric (no !TAG!COLUMN!ATTRIBUTE hint).

Step 2: Reorder Column Definitions in the SELECT Statement

  • Rewrite the SELECT clause so that all attribute-centric IDREFS/NMTOKENS columns appear physically before any element-centric IDREFS/NMTOKEN columns in the column list.
  • Example fix pattern:
  SELECT 1 AS Tag, NULL AS Parent,
         EmployeeID AS [Employee!1!EmpID!IDREFS],   -- attribute-centric, must come first
         ManagerIDs AS [Employee!1!MgrList!IDREFS]  -- element-centric, must come after
  FROM Employees
  FOR XML EXPLICIT
  • Save the modified query as a .sql file in your project directory (e.g., C:\Scripts\SQL\FixedXMLQuery.sql) for version control.

Step 3: Validate the XML Schema Mapping

  • Re-run the query in SSMS against a test database to confirm the FOR XML EXPLICIT statement executes without throwing Error 6836.
  • Cross-check the generated XML output against your expected schema using an XML validator or the OPENXML function to ensure attribute and element nodes are correctly nested.

Step 4: Consider Migrating to FOR XML PATH or AUTO Mode

  • If the EXPLICIT mode logic is overly complex, rewrite the query using FOR XML PATH('Employee') syntax, which handles attribute/element ordering automatically and reduces the risk of this directive conflict.
  • Test the PATH-based query for functional equivalence before deploying to production on SQL Server 2025.

Alternative or Verification Steps

  • Run SELECT @@VERSION; in SSMS to confirm you are patched to the latest SQL Server 2025 Cumulative Update, as XML parsing engine fixes are occasionally included in servicing releases.
  • If reordering columns does not resolve the issue, export the query results to a flat table first, then apply FOR XML EXPLICIT on the pre-sorted temp table to bypass inline ordering conflicts.

How to fix Error 6838 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6838 – IDREFS/NMTOKENS Field Conflict in FOR XML EXPLICIT

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query attempts to mix an attribute-centric column (typed as IDREFS or NMTOKENS) with an element-centric column (marked with the ELEMENT directive) of type TEXT, NTEXT, or IMAGE within the same tag. SQL Server’s XML serialization engine cannot resolve the attribute-style token list against a large object (LOB) element because LOB data types are streamed differently than standard attribute values. Essentially, the query schema is asking the engine to render two incompatible XML construction modes on the same node simultaneously.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Column Definitions

  • Open the stored procedure or query that triggered Error 6838 in SQL Server Management Studio (SSMS) on your Windows Server 2025 instance.
  • Locate the FOR XML EXPLICIT clause and scan the column aliases for the pattern TagName!TagNumber!AttributeName!IDREFS or !NMTOKENS.
  • Cross-reference this against any column in the same tag number using !ELEMENT with an underlying TEXT, NTEXT, or IMAGE data type.

Step 2: Apply the ELEMENT Directive to the IDREFS/NMTOKENS Field

  • Modify the column alias so the IDREFS or NMTOKENS field also includes the ELEMENT directive, changing the format from TagName!1!AttrName!IDREFS to TagName!1!AttrName!IDREFSELEMENT.
  • Example syntax: SELECT 1 AS Tag, NULL AS Parent, RefColumn AS [Root!1!RefAttr!IDREFSELEMENT], LobColumn AS [Root!1!LobAttr!ELEMENT] FROM YourTable FOR XML EXPLICIT.
  • Save and re-run the query to confirm the directive syntax is accepted by the parser.

Step 3: Remove the ELEMENT Directive as an Alternative Fix

  • If converting the IDREFS/NMTOKENS field is not desirable, instead strip the !ELEMENT directive from the TEXT/NTEXT/IMAGE column.
  • Convert the LOB column to a standard attribute by changing !ELEMENT to a plain attribute mapping, provided the data size does not exceed attribute value limits in your XML schema.
  • Cast the LOB field to VARCHAR(MAX) or NVARCHAR(MAX) beforehand using CAST(LobColumn AS NVARCHAR(MAX)) to maintain compatibility if downstream parsing expects string types.

Step 4: Refactor to FOR XML PATH or AUTO Mode (Optional Long-Term Fix)

  • Since FOR XML EXPLICIT is legacy and error-prone with mixed directives, rewrite the query using FOR XML PATH('Root') with nested subqueries for better control over attribute vs. element serialization.
  • Use the data() function or explicit column aliasing with @AttributeName syntax to avoid ambiguity between attribute and element rendering.

Step 5: Validate Query Execution Plan and Output

  • Execute the corrected query in SSMS and confirm no Error 6838 appears in the Messages pane.
  • Check the generated XML output structure using SELECT CAST(ResultColumn AS XML) to ensure the tags render as expected with correct attribute/element placement.

Alternative or Verification Steps

  • Run DBCC CHECKDB and review the SQL Server Error Log (via Get-EventLog -LogName Application -Source MSSQLSERVER in PowerShell) to confirm Event ID 6838 no longer recurs after query execution.
  • If the issue persists after both fixes, migrate the entire query logic to FOR XML PATH or use OPENXML/JSON-based serialization as a workaround, since EXPLICIT mode has known limitations with mixed LOB and token-list types in SQL Server 2025.

How to fix Error 6834 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6834 – Invalid XML Document in XMLTEXT Field

Why This Error Happens

Error 6834 occurs when SQL Server’s XML parser encounters data in an XMLTEXT field that does not conform to well-formed XML structure, typically due to a missing or malformed root element, unclosed tags, or invalid characters embedded in the document. This can happen when data is imported via BCP, BULK INSERT, or OPENROWSET from a source file that was truncated, encoded incorrectly (e.g., UTF-8 BOM issues), or generated by an application that produced non-compliant XML. It may also surface after a corrupted data page or an incomplete transaction left partial XML content in the field.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Record

  • Run a query isolating the column using TRY_CAST or TRY_CONVERT to XML type to locate which row fails silently versus which throws the hard error.
  • Example: SELECT ID, XMLColumn FROM YourTable WHERE TRY_CONVERT(xml, XMLColumn) IS NULL AND XMLColumn IS NOT NULL;
  • Export the flagged raw string value to a .xml file for manual inspection in VS Code or Notepad++.

Step 2: Validate the Root Tag and Encoding

  • Open the exported file and confirm there is exactly one root element wrapping all child nodes (XML requires a single parent node).
  • Check for a Byte Order Mark (BOM) or invisible Unicode characters at the start of the file, which SQL Server’s parser rejects as invalid preamble content.
  • Strip the BOM using PowerShell: Get-Content -Path "C:\Temp\file.xml" -Encoding UTF8 | Set-Content -Path "C:\Temp\file_fixed.xml" -Encoding ASCII

Step 3: Re-Import or Repair the Data Source

  • If the data originates from an ETL job or BULK INSERT on Windows Server 2025, verify the format file (.fmt) correctly maps the field length so the XML isn’t truncated mid-tag.
  • Check the source application’s export logic for proper tag closure (e.g., ensure <root>...</root> pairs match).
  • Update the application connection string to use SQLXML library version compatible with SQL Server 2025 if legacy drivers are generating malformed payloads.

Step 4: Apply a Corrective Update Script

  • If the root cause is a known malformed pattern (e.g., ampersands & not escaped as &amp;), run a REPLACE() function within an UPDATE statement to sanitize existing invalid characters before re-casting to XML.
  • Wrap the fix in a transaction to allow rollback if the CAST still fails: BEGIN TRAN; UPDATE YourTable SET XMLColumn = REPLACE(XMLColumn, '&', '&amp;') WHERE ID = @BadID; SELECT CAST(XMLColumn as XML) FROM YourTable WHERE ID = @BadID;

Alternative or Verification Steps

  • Verify the Fix: Re-run the original INSERT or UPDATE statement that triggered the 6834 error; if it processes without throwing an exception and SELECT ISNULL(XMLColumn, '').value('(/*/text())[1]', 'varchar(max)') returns expected data, the document is now well-formed.
  • Alternative Fix: If manual repair is impractical for bulk data, use OPENROWSET(BULK...) with the SINGLE_CLOB option to load the data as plain text first, allowing a C# or PowerShell pre-processing script to validate/correct the XML schema before final insertion into the XMLTEXT column.

How to fix Error 6835 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6835 — FOR XML EXPLICIT HIDE Directive Conflict

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query defines the same column with the HIDE directive more than once in the column alias naming convention (e.g., TagName!TagIndex!AttributeName!HIDE). SQL Server’s XML parser enforces strict uniqueness on directive declarations per field, so duplicate HIDE flags on the same logical field across different SELECT statements within the UNIONed query cause a parsing conflict. This is typically a query-authoring mistake rather than a server configuration or permissions issue, often introduced during manual query edits or copy-paste errors across multiple SELECT blocks in the EXPLICIT mode hierarchy.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Alias

  • Open the query in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Locate the exact field name referenced in the error message (the %.*ls placeholder will show the real column alias in the actual error output).
  • Search all SELECT statements in the UNION ALL chain for that Tag/TagIndex/AttributeName combination.

Step 2: Audit the FOR XML EXPLICIT Column Definitions

  • Review each column alias pattern, which follows the format: ColumnName!TagIndex!AttributeName!Directive.
  • Confirm that !HIDE appears only once per unique TagIndex!AttributeName pair across the entire query.
  • Remove or rename the duplicate !HIDE directive from any redundant SELECT block — only one instance per field should carry this directive.

Step 3: Rewrite and Validate the Query Logic

  • If the query was auto-generated by an ORM or reporting tool, regenerate it using a corrected template that applies HIDE once per field only.
  • For manually written queries, save a backup copy, then edit the .sql file (commonly stored under C:\Scripts\ or your project’s query repository) to remove the duplicate directive.
  • Re-run the query using sqlcmd -S <ServerName> -d <DatabaseName> -i FixedQuery.sql or execute it directly in SSMS to confirm the syntax parses correctly.

Step 4: Check for Nested or Inherited Column Definitions

  • If the query uses dynamic SQL (built via EXEC or sp_executesql), inspect the string concatenation logic that assembles the column list.
  • Ensure any looping or templated code generating the !HIDE tag doesn’t inadvertently apply it to the same field twice when combining multiple tag levels.

Alternative or Verification Steps

  • Run the corrected query in isolation using SET FMTONLY ON (or a TOP 1 test execution) to confirm it compiles without throwing Error 6835 before deploying it to production reports.
  • If the error persists and the query is complex, consider migrating from FOR XML EXPLICIT to FOR XML PATH or FOR XML AUTO, which use a simpler syntax and eliminate manual directive management entirely.

How to fix Error 6832 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6832 – FOR XML AUTO Cannot Generate URL for Binary Data with Binary Primary Key

Why This Error Happens

This error occurs because FOR XML AUTO with the ELEMENTS XSINIL or binary retrieval mode needs to construct a dbobject URL to represent binary column data, and this URL generation logic requires the primary key to be of a non-binary, convertible type. When the primary key itself is defined as binary, varbinary, image, or a related binary type, SQL Server 2025’s XML engine cannot serialize the key into the URL string format it needs, causing the generation process to fail. This is a design limitation in how the SQLXML/XML AUTO feature encodes row identifiers, not a corruption or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Table and Primary Key

  • Run sp_help 'YourTableName' in SQL Server Management Studio (SSMS) to confirm the primary key’s data type.
  • Look specifically for binary, varbinary(n), varbinary(max), or image types on the PK column.
  • Note any columns also storing binary BLOB data (e.g., images, files) that triggered the original FOR XML AUTO query.

Step 2: Modify the Primary Key Data Type or Add a Surrogate Key

  • Since changing an existing PK can break foreign key relationships, prefer adding a new surrogate key instead:
ALTER TABLE YourTableName ADD RowID INT IDENTITY(1,1) NOT NULL;
ALTER TABLE YourTableName ADD CONSTRAINT PK_RowID PRIMARY KEY (RowID);
  • If the binary column must remain the logical key, drop the binary PK constraint and keep it as a unique index instead:
ALTER TABLE YourTableName DROP CONSTRAINT PK_YourTableName;
ALTER TABLE YourTableName ADD CONSTRAINT UQ_BinaryKey UNIQUE (BinaryColumn);
  • Update any application logic or stored procedures that depend on the old PK definition.

Step 3: Rewrite the Query to Avoid the Binary PK Conflict

  • Use an explicit TYPE directive or convert binary columns to varchar(max) using BINARY_CHECKSUM() or CONVERT(varchar(max), BinaryColumn, 1) before passing to FOR XML.
  • Example query adjustment:
SELECT RowID, CONVERT(varchar(max), BinaryColumn, 1) AS BinaryColumnHex
FROM YourTableName
FOR XML AUTO, ELEMENTS;
  • Avoid referencing the raw binary PK directly in the XML AUTO projection list.

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Setup or Windows Update on Windows Server 2025 / Windows 11 and check for the latest Cumulative Update (CU) for SQL Server 2025.
  • Navigate to C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log to confirm patch installation history.
  • Restart the SQL Server service via services.msc or run:
Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the original FOR XML AUTO query after applying the surrogate key fix; confirm Error 6832 no longer appears in SSMS or the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • As an alternative, use FOR XML PATH or FOR JSON AUTO instead of FOR XML AUTO, since these methods do not impose the same binary primary key URL-generation restriction.

How to fix Error 6833 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6833 – FOR XML EXPLICIT Parent Tag Ordering Issue

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query attempts to assign a child row to a parent tag ID that has not yet been opened in the result set, violating the hierarchical structure required by the EXPLICIT mode. The root cause is almost always an incorrect ORDER BY clause, or a missing/misaligned sort on the Tag and Parent columns, causing SQL Server to process child rows before their corresponding parent rows appear in the stream. Less commonly, this can also surface after an in-place upgrade to SQL Server 2025 where legacy query plans or compatibility-level settings alter row delivery order for UNION-based EXPLICIT queries.

Step-by-Step Resolution Guide

Step 1: Validate the ORDER BY Clause in Your Query

  • Open the query in SSMS (SQL Server Management Studio 21 or later, compatible with SQL Server 2025).
  • Confirm the ORDER BY clause explicitly sorts by the Tag column first, then by Parent, exactly matching the tag number sequence used in your UNION ALL branches.
  • Example fix: ORDER BY Tag, Parent — never rely on implicit ordering from a single branch of the UNION.

Step 2: Check Tag Numbering and Hierarchy Logic

  • Review each SELECT branch in your EXPLICIT query and confirm Tag numbers increase sequentially without gaps that skip a parent level.
  • Ensure every child branch’s Parent column value matches an actual Tag value defined in a preceding branch — not a value from a tag that appears later or not at all.
  • Cross-check against %d in the error message; this tells you exactly which Parent ID SQL Server expected but could not locate as “open.”

Step 3: Verify Database Compatibility Level and Query Plan

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the database is running at the expected level post-upgrade to SQL Server 2025.
  • If the database was recently migrated, test the query under the prior compatibility level temporarily using ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; to rule out optimizer-driven row ordering changes.
  • If behavior differs between compatibility levels, update statistics with UPDATE STATISTICS and re-test before reverting the compatibility level.

Step 4: Rebuild the Query Using FOR XML PATH or AUTO as a Workaround

  • If EXPLICIT mode ordering issues persist due to complex joins, rewrite the query using FOR XML PATH with nested subqueries, which handles hierarchy automatically without manual tag management.
  • Test output structure against your original XML schema requirements to ensure no loss of attribute-centric formatting that EXPLICIT mode provided.

Alternative or Verification Steps

  • Run the corrected query in isolation using SET STATISTICS XML ON and inspect the generated XML output in SSMS’s results grid to confirm no 6833 error appears and the parent-child nesting is correct.
  • If the error persists only in production but not in a test environment, check for differing index statistics or parallelism settings using SELECT * FROM sys.dm_exec_query_stats to rule out a parallel execution plan reordering rows unexpectedly.

How to fix Error 6830 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6830 – FOR XML AUTO Column Ownership Issue

Why This Error Happens

This error occurs when a FOR XML AUTO query attempts to generate a URL-type XML representation for a column, but SQL Server cannot determine which table “owns” that column due to ambiguous or unsupported query construction. This typically happens when the query uses computed columns, aggregate functions, or expressions in the SELECT list without proper aliasing, breaking the implicit table-to-column mapping that FOR XML AUTO relies on. It can also occur when columns are pulled from views, derived tables, or UNION results where the original table lineage is lost.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic Column in the Query

  • Review the SELECT statement and locate any computed columns, expressions, or function calls (e.g., SUM(), CAST(), string concatenation) that lack an explicit column alias.
  • Check whether the column originates from a JOIN, subquery, or view rather than a base table directly referenced in the FROM clause.
  • Enable SQL Server Profiler or check the XEvent session logs to capture the exact query text that triggered Error 6830.

Step 2: Add Explicit Aliases and Simplify the Query Structure

  • Add an explicit AS <alias> to every computed or derived column in the SELECT list.
  • Example fix:
  SELECT OrderID, (Quantity * Price) AS TotalAmount
  FROM Sales.Orders
  FOR XML AUTO
  • If the column comes from a UNION, CTE, or nested subquery, consider switching to FOR XML PATH or FOR XML RAW instead, since AUTO mode requires a clear table hierarchy.
  • Avoid wrapping tables in views when using FOR XML AUTO; query the base tables directly where possible.

Step 3: Update SQL Server 2025 and Validate Compatibility Level

  • Open SQL Server Management Studio (SSMS) and confirm you are running the latest Cumulative Update for SQL Server 2025 via Help > About.
  • Run the following to check database compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If compatibility level is set below SQL Server 2025 defaults (160+), update it:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 after applying updates.

Step 4: Rewrite Query Using FOR XML PATH as a Workaround

  • If FOR XML AUTO continues to fail due to structural limitations, convert the query to FOR XML PATH('Row'), which gives explicit control over element/attribute naming and does not rely on automatic table inference.
  • Example:
  SELECT OrderID AS '@ID', CustomerName AS 'Customer'
  FROM Sales.Orders
  FOR XML PATH('Order')

Alternative or Verification Steps

  • Verify the fix: Re-run the original query after adding aliases or switching to FOR XML PATH; confirm the XML output generates without Error 6830 and matches expected schema structure.
  • Alternative solution: If legacy application code requires FOR XML AUTO specifically, isolate the problematic column into a separate subquery with a clean, single-table source, then join it back in the outer query before applying FOR XML AUTO.

How to fix Error 6831 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6831 – FOR XML AUTO Requires Primary Keys

Why This Error Happens

This error occurs because the FOR XML AUTO clause needs to establish parent-child nesting relationships between tables in the result set, and it relies on primary key metadata to generate these hierarchical references automatically. When a table or view referenced in the query lacks a defined primary key (or the key is not recognized due to permissions or schema binding), SQL Server 2025 cannot determine how to structure the nested XML elements. This commonly happens with views, temporary tables, or tables where the primary key constraint was dropped or never created.

Step-by-Step Resolution Guide

Step 1: Identify the Table Missing a Primary Key

  • Run the query independently (without FOR XML AUTO) to determine which table in the JOIN is causing the issue.
  • Check existing constraints using: SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('YourTableName');
  • If the query returns no rows, the table has no primary key defined.

Step 2: Add a Primary Key Constraint to the Table

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Execute an ALTER statement to add the missing key:
  ALTER TABLE YourTableName
  ADD CONSTRAINT PK_YourTableName PRIMARY KEY (YourIDColumn);
  • If the column contains duplicate or NULL values preventing a standard primary key, create a unique, non-nullable surrogate key column first.

Step 3: Switch to Explicit Mode for Views or Complex Joins

  • If the error originates from a VIEW where altering the underlying table isn’t feasible, modify the T-SQL query to use FOR XML EXPLICIT or FOR XML PATH instead of AUTO.
  • Rewrite the query logic to manually define the XML hierarchy using PATH('') syntax, bypassing the need for AUTO detection of keys entirely.
  • Save the updated stored procedure or query script to the application’s repository.

Step 4: Verify Database Compatibility Level

  • Ensure the database compatibility level is set correctly for SQL Server 2025 features by running: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is outdated (e.g., set to a legacy SQL Server 2014 level), update it using: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verification: Re-run the original SELECT ... FOR XML AUTO query in SSMS; the output should now generate a hierarchical XML tree without throwing Error 6831.
  • Alternative: If adding a physical primary key is not possible due to application constraints, restructure the query to use FOR XML RAW instead, as this mode does not require primary key definitions to flatten the result set into XML nodes.

How to fix Error 6828 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6828 – XMLTEXT Column Data Type Mismatch

Why This Error Happens

This error occurs when the OPENXML function or an XMLTEXT clause references a column that is not explicitly defined as a varchar, nvarchar, text, ntext, or xml data type. SQL Server 2025’s query parser strictly validates that the source column used for XML parsing contains string-based or native XML content before it attempts to shred or process the data. This commonly surfaces after a schema migration or an application update where a column’s data type was inadvertently changed to a numeric, binary, or date type while legacy XML-handling code remained unchanged.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Query

  • Locate the exact stored procedure, function, or ad-hoc query referenced in the Event ID 6828 log entry.
  • Open SQL Server Management Studio (SSMS) and run sp_helptext '<ProcedureName>' to view the full query definition.
  • Pinpoint the specific column name mentioned in the error message’s %.*ls placeholder.

Step 2: Verify the Column’s Current Data Type

  • Run the following query to check the schema definition:
  SELECT COLUMN_NAME, DATA_TYPE 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_NAME = 'YourTableName';
  • Confirm whether the column is currently set to an incompatible type (e.g., int, datetime, or binary).
  • Cross-reference this against the application’s expected schema documentation to see if a type mismatch was introduced during a recent deployment.

Step 3: Correct the Data Type or Cast the Value

  • If the column should contain XML/string data, alter the table to restore the correct type:
  ALTER TABLE YourTableName 
  ALTER COLUMN YourColumnName NVARCHAR(MAX);
  • If the underlying data type cannot be changed due to other dependencies, modify the query to explicitly cast the column before passing it to OPENXML:
  SELECT * FROM OPENXML(@hDoc, '/ROOT/Row', 1) 
  WITH (ColumnName NVARCHAR(MAX) 'CAST(YourColumnName AS NVARCHAR(MAX))');

Step 4: Clear the XML Document Handle and Retest

  • Ensure the XML handle is properly released and reinitialized to avoid cached parsing errors:
  EXEC sp_xml_removedocument @hDoc;
  EXEC sp_xml_preparedocument @hDoc OUTPUT, @xmlData;
  • Re-run the stored procedure or query in a Windows Server 2025 test environment to confirm the parser no longer throws Error 6828.

Alternative or Verification Steps

  • Verification: Execute the corrected query in SSMS and check the Messages tab for a clean execution with zero errors; additionally, monitor the Windows Event Viewer (Application Log) to confirm Event ID 6828 no longer appears during subsequent application runs.
  • Alternative: If altering the column type is not feasible due to third-party application constraints, migrate the logic away from OPENXML/XMLTEXT entirely and use the native XML data type with .nodes() and .value() methods, which offer stricter type safety and better performance in SQL Server 2025.

How to fix Error 6829 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6829 – FOR XML EXPLICIT/RAW Binary Column URL Conflict

Why This Error Happens

This error occurs because the FOR XML EXPLICIT or FOR XML RAW query modes do not support the XMLDATA, BINARY BASE64, or URL-addressing directives when applied to binary data types (such as varbinary, image, or binary) in combination with certain column annotations meant for AUTO mode. SQL Server 2025 enforces stricter parsing validation on XML column directives, and when a binary column is flagged for URL-style addressing (typically via an ID, IDREF, or hyperlink-style annotation reserved for FOR XML AUTO), the query compiler rejects the statement outright. Essentially, the query is attempting to use a feature combination that is structurally incompatible with the chosen XML retrieval mode.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column in the Query

  • Open the failing query in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Locate the column name referenced in the error message (it will be explicitly named in the %.*ls placeholder of Error 6829).
  • Check the column’s data type using sp_help 'YourTableName' or by inspecting sys.columns to confirm it is binary, varbinary, or image.

Step 2: Remove or Modify the URL Addressing Directive

  • Edit the SELECT statement and remove any TYPE, XMLDATA, or hyperlink/URL-style column annotations applied to the binary column (commonly a tag like [ColumnName!TableTag!1!hiddenURL] in EXPLICIT mode).
  • If the binary data needs to be returned, convert it using BINARY BASE64 only — do not combine it with URL-addressing syntax, which is exclusive to FOR XML AUTO.
  • Example fix: Replace FOR XML EXPLICIT binary URL column syntax with a plain BINARY BASE64 directive instead:
  SELECT 1 AS Tag, NULL AS Parent,
         FileData AS [Files!1!FileData!BINARY BASE64]
  FOR XML EXPLICIT

Step 3: Switch to FOR XML AUTO or PATH Mode if URL Addressing Is Required

  • If your application genuinely requires binary data to be exposed as a retrievable URL endpoint, rewrite the query to use FOR XML AUTO with the XMLDATA option, which is the only mode supporting binary URL addressing.
  • Alternatively, use FOR XML PATH('') with explicit BINARY BASE64 encoding and handle URL generation at the application layer instead of within SQL Server’s XML engine.

Step 4: Validate Compatibility Level Settings

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the database is running under SQL Server 2025’s expected compatibility level (160 or higher).
  • If the compatibility level is outdated, update it using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-run the query after the compatibility level change, as older compatibility modes may parse XML directives differently.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS and confirm it returns results without raising Error 6829; check the Messages tab for a clean execution with zero errors.
  • If the error persists, run DBCC CHECKDB on the target database to rule out metadata corruption affecting column definitions, then retest the query against a copy of the table in a scratch database.

How to fix Error 6826 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6826 – “Every IDREFS or NMTOKENS Column Must Appear in a Separate SELECT Clause”

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query attempts to combine multiple columns typed as IDREFS or NMTOKENS within the same SELECT statement branch, which violates the XML data type requirements for multi-value attribute columns. The SQL Server XML parser requires each IDREFS or NMTOKENS column to be isolated in its own SELECT clause because these data types represent space-separated token lists that cannot be merged or interleaved with other columns at the same tag/parent level. This is not a permissions or connectivity issue, but rather a syntax structure violation specific to how FOR XML EXPLICIT mode constructs hierarchical XML output.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Columns

  • Open SQL Server Management Studio (SSMS) 2025 and locate the exact query referenced in the error stack trace or application log.
  • Review the column aliasing syntax, specifically looking for columns formatted as TagName!TagNumber!AttributeName!IDREFS or !NMTOKENS.
  • Check if two or more of these typed columns exist under the same TagNumber grouping in a single SELECT statement.

Step 2: Separate the Columns into Distinct SELECT Clauses

  • Rewrite the query so that each IDREFS or NMTOKENS column resides in its own standalone SELECT block.
  • Use UNION ALL to join these separated SELECT statements back together, ensuring the TagNumber and Parent columns remain consistent across all unioned blocks.
  • Example fix pattern: Convert SELECT Tag, Parent, Col1!1!Attr1!IDREFS, Col2!1!Attr2!IDREFS FROM... into two separate SELECT statements joined by UNION ALL, one for Col1 and one for Col2.

Step 3: Validate Tag and Parent Consistency

  • Ensure the Tag and Parent integer values match exactly across all newly separated SELECT clauses so the XML hierarchy reconstructs correctly.
  • Confirm that NULL placeholders are inserted for non-relevant columns in each separated clause to maintain column count parity.
  • Re-run the query in a test environment (non-production database) before deploying to Windows Server 2025 production instances.

Step 4: Consider Migrating to FOR XML PATH or AUTO Mode

  • If the EXPLICIT mode logic has become overly complex, evaluate refactoring the query to use FOR XML PATH('') instead, which does not impose the same single-column restriction for token-list types.
  • Test output compatibility with downstream consumers (APIs, BizTalk, or legacy parsers) since PATH mode generates slightly different XML formatting than EXPLICIT.

Step 5: Apply Latest Cumulative Update

  • Verify you are running the latest Cumulative Update (CU) for SQL Server 2025 via SELECT @@VERSION; in a new query window.
  • Download and install any pending CU from the Microsoft Update Catalog if the build number is outdated, as XML parsing edge-case fixes are occasionally included in servicing releases.

Alternative or Verification Steps

  • Execute the corrected query using SET STATISTICS XML ON or simply run it standalone in SSMS to confirm the result set returns valid, well-formed XML without triggering Error 6826.
  • If the error persists after restructuring, temporarily substitute IDREFS/NMTOKENS typed columns with standard string type output and manually format the space-separated values using STRING_AGG() as a workaround.

How to fix Error 6827 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6827 — Multiple XMLTEXT Columns in FOR XML EXPLICIT

Why This Error Happens

This error occurs because the FOR XML EXPLICIT clause enforces a strict rule that only one XMLTEXT directive can be assigned per tag within the column alias definition. When a query’s SELECT statement attempts to map two or more columns to the same tag using the XMLTEXT directive, SQL Server 2025 cannot determine which column should supply the raw, unescaped XML content for that specific tag. This is not a permissions or configuration issue, but rather a syntax violation in the T-SQL query structure that the Query Optimizer rejects during the parsing phase.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Column Aliases

  • Open the query in SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance.
  • Locate the specific column referenced in the error message (e.g., Column 'Tag1_XMLTEXT').
  • Check the SELECT clause for multiple instances of AS [Tag!1!XMLTEXT] sharing the same Tag number.

Step 2: Consolidate or Remove Redundant XMLTEXT Directives

  • Determine which column holds the primary raw XML data you intend to inject into the output.
  • Remove the XMLTEXT directive from the secondary, conflicting column.
  • If the second column contains standard text data, change its directive to a standard element or attribute mapping instead (e.g., AS [Tag!1!ElementName]).

Step 3: Restructure Using UNION ALL for Multiple Data Sources

  • If you genuinely need to pull raw XML from two different sources into the same tag, do not attempt to use two XMLTEXT columns in one row set.
  • Split the query into two separate SELECT statements, each handling one XMLTEXT source, and combine them using a UNION ALL statement.
  • Ensure the Tag and Parent values align correctly between the two UNION ALL segments to merge into a single XML hierarchy.

Step 4: Validate Syntax in a Query Analyzer

  • Run the corrected query in a isolated test window within SSMS or Azure Data Studio.
  • Check the “Messages” tab for Error 6827 or any subsequent syntax errors (like Error 6828) that often appear once the primary conflict is resolved.

Alternative or Verification Steps

  • Verification: Execute the modified query and expand the resulting XML result in the grid view to confirm the raw XML data appears correctly nested under the intended parent tag without truncation or escaping (e.g., &lt; instead of <).
  • Alternative: If the logic is overly complex for EXPLICIT mode, consider migrating the query to FOR XML PATH or FOR XML AUTO mode, which handles raw XML injection via the TYPE directive and generally offers more flexible syntax for merging multiple XML fragments into a single tag.

How to fix Error 6824 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6824 (FOR XML EXPLICIT Clause)

Why This Error Happens

Error 6824 occurs when the FOR XML EXPLICIT clause encounters an invalid tag number, parent tag number, or column structure in the universal table format. This typically stems from a malformed query where the Tag or Parent column values fall outside the acceptable range (1-255) or where the column naming convention (TagNumber!ParentTagNumber!ElementName!Directive) is incorrectly structured. It can also surface when metadata about the XML hierarchy becomes inconsistent due to improperly aliased columns or a corrupted query plan cache referencing an outdated schema.

Step-by-Step Resolution Guide

Step 1: Validate the Tag and Parent Column Values

  • Open the query in SQL Server Management Studio (SSMS) and locate the SELECT statement using FOR XML EXPLICIT.
  • Confirm that every Tag value is a positive integer between 1 and 255.
  • Confirm that every Parent value either matches an existing Tag number or is NULL for root-level elements.
  • Run: SELECT Tag, Parent, [ElementName!Tag!Column!Directive] FROM UniversalTable ORDER BY Tag; to visually inspect hierarchy integrity.

Step 2: Correct Column Naming Syntax

  • Review each column alias to ensure it strictly follows the format: TagNumber!ParentTagNumber!AttributeName!XMLDataType.
  • Remove any extra exclamation marks, typos, or missing segments in the alias string.
  • Example of a valid alias: 1!1!CustomerID!element.
  • Re-run the query in isolation (without joins) to confirm the base tag structure compiles without throwing Error 6824.

Step 3: Clear the Procedure Cache and Rebuild the Query Plan

  • Open an elevated Command Prompt or SSMS query window on the Windows Server 2025 instance.
  • Execute: DBCC FREEPROCCACHE; to remove potentially corrupted or outdated execution plans.
  • If using a stored procedure, execute: EXEC sp_recompile 'YourStoredProcedureName';
  • Restart the SQL Server service via services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER if the issue persists after cache clearing.

Step 4: Migrate to FOR XML PATH (Optional Long-Term Fix)

  • If the EXPLICIT mode continues to generate structural errors, rewrite the query using the more modern and less error-prone FOR XML PATH('ElementName') syntax.
  • Use nested subqueries with PATH mode to replicate the hierarchy previously defined by Tag/Parent pairs.
  • Test the rewritten query against a sample dataset to confirm identical XML output structure.

Alternative or Verification Steps

  • Verify the fix by executing the query with SET STATISTICS XML ON; and confirming no error is thrown while the correct nested XML structure returns.
  • If Error 6824 persists after cache clearing, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; to rule out underlying metadata corruption in the database itself.

How to fix Error 6825 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 6825 occurs when a T-SQL query uses the FOR XML clause with the ELEMENTS directive on a mode that does not support it—typically EXPLICIT or an improperly formatted PATH mode query. SQL Server 2025 enforces stricter XML serialization validation during query compilation, so any legacy query that mixed ELEMENTS with EXPLICIT mode (which was tolerated with warnings in older engines) now fails outright. This is almost always a query-authoring issue rather than a server configuration or permissions problem, though cached execution plans from an older compatibility level can sometimes mask the root cause until a plan recompile occurs.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 / Windows 11 instance.
  • Run SELECT * FROM sys.dm_exec_query_stats joined with sys.dm_exec_sql_text to locate recently failed queries containing FOR XML.
  • Confirm the query uses FOR XML EXPLICIT combined with ELEMENTS — this combination is invalid.

Step 2: Correct the FOR XML Syntax

  • Replace FOR XML EXPLICIT, ELEMENTS with a supported mode such as:
    SELECT ... FOR XML RAW, ELEMENTS
    or
    SELECT ... FOR XML AUTO, ELEMENTS
  • If ROOT is required, ensure it’s correctly paired:
    SELECT ... FOR XML RAW('Row'), ROOT('Results'), ELEMENTS
  • Save the corrected script to C:\Scripts\SQLFixes\FixXMLQuery.sql for version control.

Step 3: Clear Cached Execution Plans

  • Run DBCC FREEPROCCACHE; to remove stale plans compiled under the old, invalid syntax.
  • Alternatively, target a specific plan with DBCC FREEPROCCACHE (plan_handle) to avoid a full cache flush on production servers.

Step 4: Validate Database Compatibility Level

  • Check the current level: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';
  • If running an older compatibility level (e.g., 150 or 160) under SQL Server 2025 (170), update it:
    ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 170;
  • This ensures the XML parser engine aligns with SQL Server 2025’s stricter validation rules.

Step 5: Re-run and Monitor

  • Execute the corrected query in SSMS or via sqlcmd -S ServerName -d YourDB -i FixXMLQuery.sql.
  • Check the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for any recurrence of Event ID 6825.

Alternative or Verification Steps

  • Confirm resolution by re-running the original failing stored procedure or application call and checking that XML output is returned without error.
  • If the error persists in a third-party application you can’t modify directly, use an SQL Server Extended Events session filtered on error_reported (error number 6825) to capture the exact query text for escalation to the vendor.

How to fix Error 6819 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6819 — “FOR XML clause is not allowed in a %ls statement”

Why This Error Happens

This error occurs because the FOR XML clause was applied to a Transact-SQL statement type that does not support it, such as inside a subquery, a derived table, a CASE expression, or alongside certain INSERT/UPDATE/DELETE constructs. SQL Server 2025’s query parser strictly validates where FOR XML can be used, and it is only permitted on the outermost SELECT statement of a query. This is a query-authoring/syntax issue rather than a server configuration, permissions, or corruption problem.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Statement Causing the Error

  • Open the query in SQL Server Management Studio (SSMS) and locate the line number referenced in the error message.
  • Check if FOR XML is being used inside a subquery, CTE, IF/CASE block, or as part of an INSERT INTO ... SELECT statement.
  • Confirm the SQL Server version and compatibility level using SELECT @@VERSION; and SELECT compatibility_level FROM sys.databases WHERE name = 'YourDBName';.

Step 2: Restructure the Query to Isolate FOR XML

  • Move the FOR XML clause so it only appears on the final, outermost SELECT statement of the batch.
  • If you need XML output from a subquery, use it inside a derived table/CTE first without FOR XML, then apply FOR XML only on the final wrapping SELECT.
  • Example fix:
  -- Incorrect
  SELECT * FROM (SELECT col1 FOR XML PATH('')) AS t;

  -- Corrected
  SELECT (SELECT col1 FOR XML PATH('')) AS XmlData FROM SomeTable;

Step 3: Replace Unsupported Combinations with Variables

  • If FOR XML is being used inside an INSERT, UPDATE, or DELETE statement directly, assign the FOR XML result to a variable first.
  • Use this pattern:
  DECLARE @XmlResult XML;
  SET @XmlResult = (SELECT col1, col2 FROM SomeTable FOR XML AUTO);
  INSERT INTO LogTable (XmlColumn) VALUES (@XmlResult);
  • Avoid nesting FOR XML inside CASE expressions; compute it separately beforehand.

Step 4: Validate Database Compatibility Level

  • Run ALTER DATABASE [YourDBName] SET COMPATIBILITY_LEVEL = 170; (or the appropriate level for SQL Server 2025) if the database was migrated from an older version and is running in legacy compatibility mode, which can affect FOR XML parsing behavior.
  • Re-run the corrected query after adjusting compatibility level.

Step 5: Test in a Minimal Reproduction Script

  • Strip the query down to the smallest reproducible case and test FOR XML in isolation on a simple SELECT * FROM TableName FOR XML AUTO; to confirm baseline functionality works.
  • Gradually reintroduce complexity (joins, subqueries, filters) until the error reappears, pinpointing the exact offending clause.

Alternative or Verification Steps

  • Verify the fix by executing the corrected query in SSMS and confirming it returns valid XML output without Error 6819 in the Messages pane.
  • As an alternative, use OUTER APPLY or a temporary table/table variable to pre-stage the FOR XML result, then reference that staged result in your final INSERT/UPDATE logic instead of nesting FOR XML directly.

How to fix Error 6820 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6820 (FOR XML EXPLICIT Column Naming)

Why This Error Happens

This error occurs because the FOR XML EXPLICIT clause enforces a strict, positional naming convention for columns in the query’s SELECT list, and the query writer has supplied a column alias that does not match the expected metadata tag format. Specifically, SQL Server requires columns beyond the mandatory Tag and Parent columns to follow the syntax ElementName!TagNumber!AttributeName, and any deviation—such as a typo, missing exclamation point, or incorrect casing—triggers this validation failure. This is purely a syntax/schema definition issue within the T-SQL query itself rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Index

  • Locate the exact column number referenced in the error message (e.g., “column 3”).
  • Open the query in SQL Server Management Studio (SSMS) and count the columns in your SELECT statement, including Tag and Parent, to find the specific alias causing the conflict.
  • Compare the expected name (%ls) provided in the error text against your actual alias (%.*ls).

Step 2: Correct the Column Alias Syntax

  • Ensure every data column following Tag and Parent adheres to the pattern ElementName!TagNumber!AttributeName.
  • Verify there are no extra spaces inside the alias brackets, such as [Customer!1!CustomerID] instead of [Customer !1!CustomerID].
  • If you are using an attribute-centric mode, confirm the attribute name is spelled exactly as referenced in other parts of the UNION ALL statement for the same Tag number.

Step 3: Validate Consistency Across UNION Statements

  • Since FOR XML EXPLICIT typically relies on multiple SELECT statements combined via UNION ALL, check that the column name for a specific Tag number is identical in every sub-query.
  • Update any mismatched aliases so that Tag!1!Attribute in the first SELECT matches exactly with Tag!1!Attribute in the second SELECT.
  • Save the script and re-execute it in a new query window to clear any cached execution plans.

Step 4: Migrate to a Modern Syntax (Recommended)

  • If the complexity continues to cause naming conflicts, consider rewriting the query using FOR XML PATH or FOR JSON AUTO, as these modes are available in SQL Server 2025 and offer more flexible, less error-prone syntax for hierarchical data.
  • Use STUFF and PATH for simpler hierarchical construction if the Explicit mode isn’t strictly required by the application.

Alternative or Verification Steps

  • Verification: Run the corrected query independently and confirm that the XML output generates successfully in the “Results to Grid” pane without throwing Error 6820.
  • Alternative: If column names must remain dynamic or variable, switch the query logic entirely to FOR XML PATH('') combined with explicit AS aliases, which bypasses the strict Tag!Number!Attribute naming requirement altogether.

How to fix Error 6821 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6821 – GROUP BY and Aggregate Functions Not Supported with FOR XML AUTO

Why This Error Happens

Error 6821 occurs because SQL Server’s FOR XML AUTO mode is designed to shape XML output directly from table/column hierarchies inferred from the SELECT and FROM clauses, and it does not have logic to reconcile that automatic shaping with the row-collapsing behavior of GROUP BY or aggregate functions like SUM(), COUNT(), or AVG(). This is a query-level syntax limitation rather than a server configuration or permissions issue, meaning it will occur consistently regardless of SQL Server edition, patch level, or the underlying OS (Windows Server 2025 / Windows 11). The engine throws this error at parse/compile time because it cannot deterministically map aggregated result sets to the nested XML structure that AUTO mode requires.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact SELECT statement referenced in the application log or SSMS error output that triggered Error 6821.
  • Check the query for any combination of GROUP BY, SUM(), COUNT(), AVG(), MIN(), or MAX() used alongside FOR XML AUTO.
  • Confirm the error reproduces in SQL Server Management Studio (SSMS) by running the isolated query against Microsoft SQL Server 2025.

Step 2: Refactor Using a Derived Table or CTE

  • Separate the aggregation logic from the XML generation logic by wrapping the aggregate query in a subquery or Common Table Expression (CTE).
  • Example pattern:
  ;WITH AggregatedData AS (
      SELECT CustomerID, COUNT(OrderID) AS OrderCount
      FROM Sales.Orders
      GROUP BY CustomerID
  )
  SELECT CustomerID, OrderCount
  FROM AggregatedData
  FOR XML AUTO;
  • This ensures the aggregation completes first, producing a flat, non-aggregated result set that FOR XML AUTO can safely process.

Step 3: Switch to FOR XML PATH or FOR XML RAW if Structure Control Is Needed

  • If AUTO mode’s automatic nesting is not strictly required, convert the query to use FOR XML PATH('row') or FOR XML RAW, both of which support aggregates without restriction.
  • Example:
  SELECT CustomerID, COUNT(OrderID) AS OrderCount
  FROM Sales.Orders
  GROUP BY CustomerID
  FOR XML PATH('Customer'), ROOT('Customers');
  • Adjust downstream consumers (apps, SSIS packages, or reporting services) if the XML tag structure changes as a result.

Step 4: Update Application or ORM-Generated Queries

  • If the query is generated dynamically by an ORM (e.g., Entity Framework) or a reporting tool, inspect the data access layer or stored procedure that builds the SQL string.
  • Add explicit query overrides or stored procedures to bypass auto-generated FOR XML AUTO aggregate calls.
  • Redeploy the updated stored procedure using SQLCMD or SSMS:
  sqlcmd -S localhost -d YourDatabase -i C:\Scripts\Fix_XMLAuto_Procedure.sql

Alternative or Verification Steps

  • Re-run the corrected query in SSMS connected to your SQL Server 2025 instance and confirm no Error 6821 is thrown, and validate the output XML structure matches application expectations.
  • As a quick alternative, if restructuring is not immediately feasible, temporarily replace FOR XML AUTO with FOR XML PATH('') to unblock reporting while a permanent CTE-based fix is scheduled for deployment.

How to fix Error 6816 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6816 (FOR XML EXPLICIT Clause)

Why This Error Happens

Error 6816 occurs when the FOR XML EXPLICIT clause encounters an invalid column organization in the underlying SELECT statement, typically because the Tag and Parent columns are not correctly defined as the first two columns, or element/attribute-named columns violate the required TagNumber!TagName!AttributeName naming convention. This is a query-authoring issue rather than a server configuration fault, often triggered after a schema change, a column reorder, or a migration from an older SQL Server instance to SQL Server 2025 where stricter XML schema validation is enforced. Corrupted or incomplete metadata in system views (such as sys.columns) referenced by the query can also surface this error intermittently.

Step-by-Step Resolution Guide

Step 1: Validate the Column Structure of the EXPLICIT Query

  • Confirm that the first column in the SELECT list is named Tag and is of type tinyint or int.
  • Confirm the second column is named Parent and correctly references the parent Tag value (or NULL for root level).
  • Check that all subsequent columns follow the exact naming pattern TagNumber!TagName!AttributeName with no extra spaces or typos.

Step 2: Rebuild the Query Using SQL Server Management Studio (SSMS) 21

  • Open SSMS 21 (compatible with SQL Server 2025) and connect to the affected instance on Windows Server 2025 / Windows 11.
  • Run the query in isolation against a small test dataset to isolate which UNION ALL block is causing the malformed tag structure.
  • Use SET FMTONLY ON (or sys.dm_exec_describe_first_result_set) temporarily to validate the result set schema before executing the full XML generation.

Step 3: Check for Elementxsinil or Hide Directive Conflicts

  • Inspect any columns using !element!xsinil or !hide directives — these commonly break the required column order rules in SQL Server 2025’s updated XML engine.
  • Remove or reorder conflicting directive columns, ensuring !hide columns still maintain positional sequence relative to their Tag number.
  • Re-run DBCC CHECKDB on the source database (path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) to rule out metadata corruption affecting sys.columns.

Step 4: Apply the Latest Cumulative Update

  • Navigate to Microsoft’s official download center and install the latest Cumulative Update (CU) for SQL Server 2025.
  • Restart the SQL Server service via services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER from an elevated PowerShell prompt.
  • Re-test the original FOR XML EXPLICIT query to confirm the CU resolved any known engine-level parsing bugs.

Alternative or Verification Steps

  • Run the corrected query with FOR XML EXPLICIT and confirm it returns well-formed XML without error 6816 in the Messages pane of SSMS.
  • If the error persists, rewrite the query using FOR XML PATH or FOR XML AUTO as a modern alternative, since Microsoft recommends these methods over EXPLICIT mode for new development in SQL Server 2025.

How to fix Error 6817 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6817 — “FOR XML EXPLICIT cannot combine multiple occurrences of ELEMENT”

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query attempts to merge two or more columns marked with the ELEMENT directive under the same tag name and parent hierarchy level without proper qualification. SQL Server 2025’s XML parser cannot resolve ambiguity when multiple columns share an identical !TagName!ColumnName!ELEMENT pattern within the same row set, since each ELEMENT-tagged column must map to a distinct node. This is typically caused by a malformed column alias structure in the SELECT statement rather than a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Review the FOR XML EXPLICIT Column Alias Syntax

  • Open the query in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Locate every column alias formatted as TagName!TagNumber!AttributeName!ELEMENT.
  • Identify any instance where two or more columns share the exact same TagNumber and AttributeName combination with !ELEMENT appended.

Step 2: Rename Duplicate Element Mappings

  • Assign a unique AttributeName to each column that is intended to produce a distinct child element.
  • Example fix: change Orders!1!CustomerID!ELEMENT and a duplicate Orders!1!CustomerID!ELEMENT to Orders!1!CustomerID!ELEMENT and Orders!1!CustomerName!ELEMENT respectively.
  • Ensure no two columns at the same TagNumber level use an identical combination of AttributeName and ELEMENT directive.

Step 3: Consolidate Repeated Data Using UNION ALL Instead

  • If the intent was to combine multiple source columns into a single repeating element (e.g., multiple comments or tags), restructure the query using separate SELECT branches joined with UNION ALL, each producing one row per element instance.
  • Re-map the TagNumber and parent-child (Parent!Child) relationships explicitly for each branch to avoid collision.

Step 4: Consider Migrating to FOR XML PATH or AUTO

  • On Windows Server 2025 / Windows 11 hosts running SQL Server 2025, evaluate replacing legacy FOR XML EXPLICIT logic with FOR XML PATH('') or FOR XML AUTO, which handle element nesting automatically and avoid manual tag numbering errors.
  • Test performance and output structure against your original EXPLICIT mode requirements before fully switching.

Step 5: Validate Query Execution Plan and Syntax

  • Run the corrected query using SET SHOWPLAN_XML ON to confirm the parser no longer throws Error 6817.
  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for any residual XML parsing warnings.

Alternative or Verification Steps

  • Execute the modified query directly in SSMS and confirm the XML output renders without throwing Error 6817, then validate the resulting XML structure against your expected schema using an XML validator.
  • If the error persists, isolate the issue by commenting out column groups incrementally to pinpoint which specific ELEMENT mapping is causing the conflict, then rebuild the tag hierarchy from scratch using sequential TagNumber values.

How to fix Error 6814 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6814 in FOR XML EXPLICIT Clause

Why This Error Happens

Error 6814 occurs when the FOR XML EXPLICIT clause encounters a column in the universal table that does not conform to the required naming convention (TagName!TagNumber!AttributeName!Directive). This typically happens due to a malformed column alias, an incorrect tag number reference that doesn’t match a parent tag, or a missing ! delimiter in the SELECT statement. Corrupted query metadata or a mismatch between the specified XML directive and the actual data type being returned can also trigger this validation failure.

Step-by-Step Resolution Guide

Step 1: Validate the Universal Table Column Syntax

  • Open the query in SQL Server Management Studio (SSMS) and locate the SELECT statement feeding the FOR XML EXPLICIT clause.
  • Confirm every column alias strictly follows the pattern TagName!TagNumber!AttributeName!Directive (e.g., 1!1!CustomerID).
  • Check for missing exclamation marks ! or extra spaces within the alias string, as even a single misplaced character triggers Error 6814.

Step 2: Verify Tag Number Hierarchy and Parent References

  • Ensure that every child TagNumber has a corresponding parent TagNumber defined earlier in the UNION ALL structure.
  • Run the query with just the SELECT portion (without FOR XML EXPLICIT) to visually inspect the Tag and Parent columns for logical consistency.
  • Correct any orphaned tags where the Parent column value does not match an existing Tag value in the result set.

Step 3: Check Directive Compatibility with Data Types

  • Review any columns using special directives like xmltext, cdata, or hide and confirm the underlying column data type supports XML serialization.
  • Cast ambiguous data types explicitly using CAST(column AS NVARCHAR(MAX)) to prevent SQL Server from rejecting the directive during parsing.
  • Save the script and re-run it in a new query window in SSMS connected to the Windows Server 2025 instance to clear any cached execution plan errors.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Navigate to the Microsoft Update Catalog and check if a newer Cumulative Update (CU) is available for your specific build of SQL Server 2025.
  • Apply the update via the Windows Server 2025 Server Manager to rule out a known parser bug in the XML engine.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to ensure the patch is fully loaded.

Alternative or Verification Steps

  • Verification: Execute the corrected query and confirm the XML output renders correctly in the SSMS “Results to Grid” tab without throwing Error 6814.
  • Alternative: If the complexity of FOR XML EXPLICIT continues to cause syntax conflicts, migrate the query logic to use FOR XML PATH('') or FOR XML AUTO, which offer simpler syntax validation and achieve similar hierarchical XML structuring with less risk of tag-naming errors.

How to fix Error 6815 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6815 in FOR XML EXPLICIT Clause

Why This Error Happens

Error 6815 occurs when the FOR XML EXPLICIT clause encounters an invalid tag number or parent tag number in the universal table structure, typically because the tag values are non-sequential, exceed the allowed range (1-255), or a child tag references a parent tag that doesn’t exist in the hierarchy. This is a query-authoring issue rather than a server configuration fault, often introduced after a schema change, a copy-pasted query template, or manual edits to the Tag and Parent columns. It can also surface after upgrading to SQL Server 2025 if deprecated XML parsing behaviors were silently tolerated in older engine versions but are now strictly validated.

Step-by-Step Resolution Guide

Step 1: Review the Tag and Parent Column Values

  • Open the query that uses FOR XML EXPLICIT and locate the Tag and Parent integer aliases in each SELECT statement of the UNION ALL block.
  • Confirm that every Tag value is a unique whole number between 1 and 255.
  • Verify that every Parent value correctly references an existing Tag from a preceding SELECT statement (or is NULL for root-level elements).

Step 2: Validate the Element/Attribute Naming Syntax

  • Check column aliases follow the correct ElementName!TagNumber!AttributeName or ElementName!TagNumber!AttributeName!Directive pattern.
  • Look for typos in directives such as !hide, !element, !xml, !xmltext, or !cdata.
  • Run the query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF to isolate the parsing step and capture the exact line raising Error 6815.

Step 3: Rebuild the Universal Table Incrementally

  • Comment out all but the first two SELECT statements in the UNION ALL chain and execute to confirm they parse correctly.
  • Add back one SELECT block at a time, re-running the query after each addition to pinpoint which tag introduced the invalid reference.
  • Correct the tag sequencing so values increase logically and parents always point to a valid prior tag.

Step 4: Check for SQL Server 2025 Compatibility Level Issues

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; in SSMS.
  • If the database was upgraded from an older version, temporarily test with ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; to see if the error persists, which confirms whether stricter 2025 parsing is the trigger.
  • Update the query to meet current standards rather than permanently lowering compatibility level.

Step 5: Apply the Latest Cumulative Update

  • On Windows Server 2025 or Windows 11, open Settings > Windows Update or use SQL Server Setup to check for the latest Cumulative Update (CU) for SQL Server 2025.
  • Install any available CU, as early releases of major versions sometimes contain XML parser edge-case bugs that get patched quickly.
  • Restart the SQL Server service via SQL Server Configuration Manager after installation.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm the XML output renders without Error 6815, then validate the resulting XML structure using an XML viewer or FOR XML AUTO/PATH as a cross-check.
  • If FOR XML EXPLICIT continues to cause issues, consider migrating the query logic to FOR XML PATH or FOR JSON, which offer simpler syntax and are less prone to tag-numbering errors.

How to fix Error 6812 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6812 – XML Tag ID Redeclaration Conflict

Why This Error Happens

This error occurs when SQL Server’s XML parser encounters an internal XML schema or binary XML blob where a numeric tag ID has been mapped to two different namespace URIs or element names. This typically happens due to corruption in an XML data type column, a malformed WITH XMLNAMESPACES clause that redefines a prefix inconsistently within the same document, or application code that incorrectly serializes XML documents with conflicting internal tag dictionaries. It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML indexes were built under older collation or parsing rules.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Query and XML Source

  • Capture the exact query via SQL Server Profiler or Extended Events (filter on Error Number = 6812).
  • Identify which table, column, or variable is passing the XML data causing the conflict.
  • Run DBCC CHECKDB on the affected database to rule out underlying page-level corruption:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 2: Validate and Repair the XML Document

  • Extract the problematic XML value into a standalone .xml file for inspection:
  SELECT XmlColumn FROM YourTable WHERE PrimaryKeyID = <ID>;
  • Check for duplicate or conflicting xmlns prefix declarations within nested elements.
  • If using WITH XMLNAMESPACES, ensure each prefix is declared only once per batch and not redefined mid-document.
  • Re-serialize the XML using a clean .NET XmlDocument or XElement object to strip inconsistent internal tag dictionaries before re-inserting it into SQL Server.

Step 3: Rebuild XML Indexes and Schema Collections

  • Drop and recreate any Primary/Secondary XML Indexes on the affected column, as legacy indexes may retain stale tag dictionaries:
  DROP INDEX IX_XML_Primary ON YourTable;
  CREATE PRIMARY XML INDEX IX_XML_Primary ON YourTable (XmlColumn);
  • If using XML Schema Collections, validate them against the current document using sys.xml_schema_collections and refresh if the schema was registered under a prior SQL Server version.

Step 4: Apply Latest Cumulative Update

  • Navigate to the Microsoft Update Catalog and confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as early XML parser builds had known tag-dictionary caching bugs.
  • Check current build via:
  SELECT @@VERSION;
  • Install the CU via the standard SQL Server Setup wizard or silent install:
  SQLServer2025-KB*****-x64.exe /quiet /IAcceptSQLServerLicenseTerms

Alternative or Verification Steps

  • Re-run the original query that triggered Error 6812; if it completes without exception and returns valid XML output via SELECT ... FOR XML AUTO, the fix is confirmed.
  • If the error persists only on a specific row, consider exporting all unaffected data, truncating the table, and re-importing the sanitized XML dataset to bypass the corrupted binary XML blob entirely.

How to fix Error 6813 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6813 – “FOR XML EXPLICIT cannot combine multiple occurrences of ID”

Why This Error Happens

This error occurs when a FOR XML EXPLICIT query contains a column marked with the id directive appearing more than once for the same tag number in the UNION-based result set. SQL Server’s XML EXPLICIT mode requires a single, unique identifier column per tag to correctly construct the parent-child hierarchy, and duplicate id declarations break this mapping logic. This typically stems from a malformed query structure, often introduced during manual query edits, ORM-generated SQL, or a migration script ported from an older SQL Server version without validation against SQL Server 2025’s stricter XML parser.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Use the SQL Server Error Log (Management > SQL Server Logs) or Extended Events session to capture the exact query text that triggered Error 6813.
  • Search the query body for the FOR XML EXPLICIT clause and identify all AS [TagNumber!TagName!AttributeName!Directive] column aliases.

Step 2: Audit the Column Directives

  • Review every column alias formatted as [Tag!TagName!Column!id] across all SELECT statements joined by UNION ALL.
  • Confirm that only one column per unique Tag number uses the !id directive; all other identifying columns for that tag should omit the directive or use hide instead.
  • Example fix — change:
  1 AS Tag, NULL AS Parent,
  CustomerID AS [Customer!1!CustomerID!id],
  OrderID AS [Customer!1!OrderID!id]  -- duplicate id, remove this

to:

  1 AS Tag, NULL AS Parent,
  CustomerID AS [Customer!1!CustomerID!id],
  OrderID AS [Customer!1!OrderID]

Step 3: Rebuild and Test the Query Incrementally

  • Break the UNION ALL query into individual SELECT blocks and run each in isolation in SSMS to confirm correct tag/column mapping.
  • Reassemble the blocks one at a time, re-running the full query after each addition to catch the exact block introducing the duplicate id.
  • Save a corrected version of the stored procedure or script using ALTER PROCEDURE or CREATE OR ALTER PROCEDURE.

Step 4: Clear Cached Execution Plans

  • If the procedure was recently altered but the error persists, flush the stale plan from cache:
  DBCC FREEPROCCACHE;
  • Alternatively, target a single procedure’s plan using sp_recompile 'YourProcedureName'; to avoid a full cache flush on production servers.

Alternative or Verification Steps

  • Re-run the corrected query directly in SSMS and confirm it returns valid XML output without Error 6813; check the Results to Grid/XML pane for proper nested element structure.
  • As an alternative, consider migrating the logic to FOR XML PATH or FOR XML AUTO with TYPE directives, which offer simpler syntax and avoid the strict tag/id pairing rules enforced in EXPLICIT mode.

How to fix Error 6810 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6810 – Duplicate Column Name in XML Tag Generation

Why This Error Happens

This error occurs when a SELECT ... FOR XML query (typically using EXPLICIT or PATH mode) attempts to generate the same attribute name more than once on a single XML element. This is usually caused by duplicate column aliases in the query’s column list, improper use of the same attribute-named column across joined tables, or a poorly constructed XMLDATA/EXPLICIT schema where two columns resolve to identical tag/attribute names. In SQL Server 2025, this validation is enforced strictly during XML serialization, so even accidental duplication (such as from SELECT * combined with aliasing) will trigger a hard failure instead of a silent overwrite.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the full T-SQL statement from the application log or SQL Server error log that triggered Error 6810.
  • Run the query manually in SQL Server Management Studio (SSMS) or Azure Data Studio against Windows Server 2025 to reproduce the error.
  • Note the exact column/attribute name mentioned in the %.*ls placeholder of the error message.

Step 2: Audit Column Aliases in the SELECT List

  • Check every column in the FOR XML EXPLICIT or FOR XML PATH clause for duplicate aliases (e.g., AS CustomerID appearing twice).
  • Pay special attention to JOIN statements where two tables have identically named columns (such as ID or Name) that haven’t been explicitly aliased.
  • Rename conflicting aliases using unique names, for example: SELECT a.ID AS 'Account!1!ID', b.ID AS 'Account!1!RefID'.

Step 3: Correct the XML EXPLICIT Tag Structure

  • Verify the Tag and Parent column structure in your FOR XML EXPLICIT query to ensure no attribute is mapped twice to the same TagName!TagNumber!AttributeName pattern.
  • Remove or consolidate any redundant UNION ALL branches that may be injecting the same attribute name into the same tag level.
  • If using FOR XML PATH, ensure @ prefixed attribute aliases (e.g., '@id') are not repeated within the same row-generating subquery.

Step 4: Update SQL Server 2025 Cumulative Update (If Applicable)

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm your current build version via SELECT @@VERSION.
  • Navigate to the official Microsoft Update Catalog and install the latest Cumulative Update (CU) for SQL Server 2025, as early CU releases had stricter-than-intended validation logic for FOR XML EXPLICIT.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after patching.

Step 5: Rewrite Using FOR XML AUTO or JSON as a Workaround

  • If the EXPLICIT/PATH structure is too complex to debug quickly, consider rewriting the query using FOR XML AUTO, ELEMENTS to let SQL Server auto-generate non-conflicting tag names.
  • Alternatively, evaluate whether FOR JSON PATH meets the application’s data-retrieval needs, bypassing the XML attribute collision entirely.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm the XML output renders fully without triggering Error 6810, then validate the output against an XML schema (XSD) if one is required by the consuming application.
  • If the error persists after alias correction, use SET SHOWPLAN_XML ON to inspect the query execution plan for hidden computed columns that might be auto-generating duplicate attribute names during optimization.

How to fix Error 6811 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 6811 — FOR XML Incompatible with COMPUTE Expressions

Why This Error Happens

This error occurs because SQL Server’s FOR XML clause cannot process result sets that include COMPUTE or COMPUTE BY expressions, as these two features use fundamentally incompatible result-set generation engines. The COMPUTE clause produces supplementary summary rows outside the standard relational row format, which the XML serialization engine is architecturally unable to parse. This typically surfaces when legacy T-SQL scripts—often migrated from older SQL Server versions—are executed against SQL Server 2025, since COMPUTE is a deprecated feature retained only for backward compatibility.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact stored procedure, view, or ad-hoc query that triggered Error 6811 by checking SQL Server Management Studio (SSMS) output or the application’s error log.
  • Use SQL Server Profiler or Extended Events on Windows Server 2025 to capture the exact batch text if the error is intermittent or buried in a large application codebase.
  • Search the query text for both COMPUTE and FOR XML keywords appearing in the same statement.

Step 2: Remove the COMPUTE Clause

  • Open the query in SSMS and delete the COMPUTE or COMPUTE BY clause entirely, since this feature has been deprecated since SQL Server 2012 and has no place in modern XML-based reporting.
  • Replace the aggregate functionality previously provided by COMPUTE with a GROUP BY clause combined with ROLLUP or CUBE for subtotal/grand-total behavior.
  • Example rewrite: change SELECT * FROM Sales COMPUTE SUM(Amount) to SELECT CategoryID, SUM(Amount) FROM Sales GROUP BY ROLLUP(CategoryID).

Step 3: Restructure the Query for FOR XML Compatibility

  • Wrap the aggregated GROUP BY/ROLLUP logic in a Common Table Expression (CTE) or derived table before applying FOR XML PATH or FOR XML AUTO.
  • Ensure column aliases are explicitly defined in the CTE output, as FOR XML requires named columns to generate valid element or attribute names.
  • Test the rewritten query in isolation (without FOR XML) first to confirm the result set returns correctly before reattaching the XML clause.

Step 4: Update Application and Deployment Scripts

  • Search your application’s codebase, SSIS packages, and deployment scripts (typically located in C:\Program Files\Microsoft SQL Server\160\DTS\Packages\ or your custom repo) for any remaining COMPUTE usage.
  • Update stored procedure definitions directly in the database using ALTER PROCEDURE to persist the fix.
  • Redeploy affected SSIS/ETL jobs via SQL Server Agent to ensure the corrected logic is used in production.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm it returns a well-formed XML result set without raising Error 6811; check the Results to Grid or Results to Text pane for valid XML output.
  • If subtotal/grand-total reporting is still required, consider generating the XML output in two separate steps: retrieve aggregated data via GROUP BY/ROLLUP first, then use client-side (C#/PowerShell) or SSRS-based XML transformation instead of relying on native FOR XML with legacy aggregation syntax.

How to fix Error 6808 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6808 – XML Tag ID Could Not Be Added

Why This Error Happens

Error 6808 occurs when SQL Server’s internal XML parser runs out of available memory in the buffer pool while attempting to allocate a new XML tag ID during parsing or shredding operations. This is typically triggered by processing extremely large or deeply nested XML documents under memory pressure, or when the server’s memory configuration is too restrictive for the workload. In some cases, this can also surface due to memory fragmentation caused by other memory-intensive processes competing for resources on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Allocation and Pressure

  • Open SQL Server Management Studio (SSMS) and run sp_configure 'max server memory' to check the current ceiling.
  • Query sys.dm_os_memory_clerks and filter for MEMORYCLERK_XML to confirm if XML processing is consuming excessive memory.
  • Check Windows Performance Monitor (PerfMon) for the Memory\Available MBytes counter to rule out OS-level memory starvation.

Step 2: Adjust SQL Server Memory Configuration

  • Increase max server memory (MB) via SSMS (Server Properties > Memory) or T-SQL:
    EXEC sp_configure 'max server memory', 16384; RECONFIGURE;
  • Ensure min server memory is not set too high, as this can starve the OS and other applications on Windows Server 2025.
  • If running on a VM, confirm that dynamic memory allocation in Hyper-V isn’t ballooning memory away from the SQL instance.

Step 3: Optimize or Chunk the XML Processing Query

  • Break large XML documents into smaller batches using OPENXML or nodes() method with pagination logic.
  • Avoid using sp_xml_preparedocument without immediately calling sp_xml_removedocument to release the document handle from memory (MSXML parser cache).
  • Rewrite queries to use native XML data type methods instead of the deprecated OPENXML rowset provider, which is more memory-intensive.

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Run the installer with elevated privileges: Setup.exe /ACTION=Patch /INSTANCENAME=MSSQLSERVER /IACCEPTSQLSERVERLICENSETERMS.
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER.

Alternative or Verification Steps

  • Verify the Fix: Re-run the failing query/job and monitor sys.dm_os_ring_buffers for any recurrence of RING_BUFFER_OOM (Out of Memory) entries.
  • Alternative Solution: If the error persists despite available memory, restart the SQL Server instance to clear the internal XML parser cache, as fragmented memory clerks sometimes require a cold restart to fully reset.

How to fix Error 6809 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 6809 – Unnamed Tables/Columns in FOR XML

Why This Error Happens

Error 6809 occurs when a FOR XML query (typically using AUTO, RAW, or PATH modes) attempts to serialize a result set that contains a derived table, subquery, or computed column without an explicit alias. SQL Server’s XML engine requires every table and column referenced in the output to resolve to a valid XML element or attribute name, and it cannot auto-generate one from an expression, function call, or unaliased join result. This typically surfaces after upgrading to SQL Server 2025 query engine builds, where stricter XML schema validation rejects queries that previously may have returned null-named nodes silently.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact FOR XML statement throwing Error 6809.
  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025 to capture the full query context and session ID.
  • Run the query in isolation (without FOR XML) to visually inspect the result set’s column headers for blanks or “(No column name)” entries.

Step 2: Alias Every Unnamed Column and Derived Table

  • Add explicit AS aliases to any computed columns, aggregates, or expressions in the SELECT list.
  SELECT SUM(SalesAmount) AS TotalSales, OrderID AS OrderID
  FROM Sales.Orders
  FOR XML AUTO
  • For derived tables or subqueries used as a source, assign a table alias immediately after the closing parenthesis.
  SELECT t.OrderID, t.TotalSales
  FROM (SELECT OrderID, SUM(Amount) AS TotalSales FROM Orders GROUP BY OrderID) AS t
  FOR XML AUTO
  • Double-check joined tables for missing aliases, since FOR XML AUTO uses table names/aliases to generate nested XML element names.

Step 3: Validate Nested and Computed Expressions

  • Review any CASE, CAST, CONVERT, or scalar function calls embedded directly in the SELECT clause — these are common unnamed-column culprits.
  • Rename each one explicitly, even if the name seems redundant (e.g., CAST(Price AS DECIMAL(10,2)) AS Price).
  • Re-run the query after each change to confirm Error 6809 no longer appears in the Messages pane.

Step 4: Clear Cached Execution Plans (If Error Persists)

  • If the corrected query still throws the error due to a stale cached plan, run DBCC FREEPROCCACHE in a test environment (avoid on production during business hours).
  • Alternatively, target the specific plan using DBCC FREEPROCCACHE (plan_handle) retrieved from sys.dm_exec_cached_plans.
  • Re-execute the corrected query to force SQL Server to recompile against the new aliased structure.

Alternative or Verification Steps

  • Run the corrected query and confirm the output switches from grid/text view to valid XML in the Results pane without throwing Error 6809 in the Messages tab.
  • If the issue persists across multiple queries, audit any stored procedures or views feeding into the FOR XML statement using sp_helptext '<ObjectName>' to ensure no unaliased columns are inherited upstream.