Why This Error Happens
Error 9445 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data being inserted into an xml-typed column or processed via OPENXML, sp_xml_preparedocument, or XML data type methods. This typically stems from mismatched tags, invalid special characters, incorrect namespace declarations, or truncated XML strings caused by application-layer encoding mismatches (e.g., UTF-8 vs UTF-16) or buffer size limits. In Windows Server 2025 / Windows 11 environments running SQL Server 2025, this can also surface after driver updates (ODBC/OLE DB) that alter how XML payloads are serialized before transmission.
Step-by-Step Resolution Guide
Step 1: Identify the Exact Line and Character Causing the Failure
- Run the failing query in SQL Server Management Studio (SSMS) and capture the full error message, which includes the line number and often a character position.
- Use
SELECT CAST(@XMLVariable AS NVARCHAR(MAX))to print the raw XML string and manually inspect the indicated line. - Check for common culprits: unescaped
&,<,>characters, or unclosed tags.
Step 2: Validate XML Encoding and Structure Externally
- Export the suspect XML payload to a
.xmlfile and open it in Visual Studio Code or an XML validator (e.g.,xmllint --noout file.xmlvia WSL on Windows Server 2025). - Confirm the XML declaration matches the actual encoding:
<?xml version="1.0" encoding="UTF-8"?>must match the byte order mark (BOM) of the file/stream. - If the source is an application, check the connection string’s
CharsetorEncodingparameter in the ODBC/OLE DB driver configuration.
Step 3: Correct the Application-Side XML Generation Logic
- Review the application or ETL job generating the XML (e.g., SSIS package, .NET
XmlWriter, or Pythonlxmlexport) for improper string concatenation instead of proper XML serialization. - Ensure special characters are escaped using
XmlWriter.WriteString()or equivalent library methods rather than raw string building. - Increase buffer sizes in the data access layer if XML is being truncated mid-tag (common with
NVARCHAR(4000)limits instead ofNVARCHAR(MAX)).
Step 4: Re-test Insertion with a Sanitized Payload
- Replace the problematic XML fragment with a corrected version and re-run the
INSERTorUPDATEstatement. - If using
sp_xml_preparedocument, confirm you’re also callingsp_xml_removedocumentafterward to avoid memory/handle leaks that can sometimes mask secondary parsing errors.
Alternative or Verification Steps
- Verify the fix by running
SELECT TOP 10 * FROM YourTable WHERE XMLColumn IS NOT NULLand confirming the data loads without triggering Error 9445 again. - If the error persists intermittently, enable SQL Server Extended Events with the
sql_statement_completedevent filtered on your database to capture the exact XML payload at the moment of failure for deeper forensic analysis.