Troubleshooting Guide: SQL Server Error 6309 – XML Well-Formedness Check Failure
Why This Error Happens
Error 6309 occurs when SQL Server attempts to convert relational data into XML format (typically via FOR XML queries) and encounters a character that violates XML 1.0 specification rules. This commonly happens with control characters (such as 0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F) stored in character or binary columns that were inserted without proper validation. The underlying data itself is not corrupted from SQL Server’s perspective, but it cannot be legally serialized into an XML document without modification or encoding.
Step-by-Step Resolution Guide
Step 1: Identify the Offending Character and Column
- Note the hexadecimal value (0x%04X) provided in the error message, as this identifies the exact invalid character.
- Run a diagnostic query against the suspected table to locate rows containing control characters:
SELECT * FROM YourTable
WHERE YourColumn LIKE '%' + NCHAR(0x0B) + '%'
- Adjust the
NCHAR()value to match the hex code reported in your specific error.
Step 2: Sanitize the Data Using a Cleanup Script
- Use a
PATINDEXor a user-defined function (UDF) to strip illegal characters before theFOR XMLoperation runs. - Apply a
REPLACEorTRANSLATEfunction to scrub the specific character:
UPDATE YourTable
SET YourColumn = REPLACE(YourColumn, NCHAR(0x0B), '')
WHERE YourColumn LIKE '%' + NCHAR(0x0B) + '%'
- If multiple control characters exist, consider building a loop that iterates through the range 0x00–0x1F (excluding valid whitespace like Tab, CR, and LF) to clean the dataset in bulk.
Step 3: Implement a Permanent Encoding Workaround
- For scenarios where you need to preserve the raw binary/control data (rather than deleting it), convert the column to
VARBINARYand useBINARY BASE64encoding in your XML output instead of raw text. - Alternatively, wrap the query logic in a
TRY...CATCHblock to handle future instances gracefully without crashing the application thread. - Update front-end input validation (e.g., in the connecting application layer) to reject control characters at the point of data entry, preventing recurrence.
Step 4: Restart the Service and Clear Query Cache
- Navigate to SQL Server Configuration Manager on your Windows Server 2025 instance.
- Restart the SQL Server (MSSQLSERVER) service to clear any cached execution plans that might be holding onto the faulty data pointers.
- Run
DBCC FREEPROCCACHEto ensure the query optimizer recompiles theFOR XMLstatement against the newly cleaned data.
Alternative or Verification Steps
- Verification: Re-run the original
FOR XMLquery that triggered the error. If it returns a valid XML result set without throwing Error 6309, the sanitation was successful. - Alternative: If editing production data is too risky, use the
FOR XML EXPLICITdirective with aCDATAsection wrapper, which allows for a broader range of characters to pass through without breaking the XML schema validation.