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

Troubleshooting Guide: SQL Server Error 9626 (Service Broker Internal Error)

Why This Error Happens

Error 9626 occurs when the Service Broker engine detects that an internal object—such as a conversation endpoint, queue, or dialog—is in a state that does not match the operation being attempted, usually due to internal metadata corruption or a race condition during high-concurrency message processing. This is often triggered by abrupt shutdowns, storage-level corruption affecting system tables (sys.conversation_endpoints, sys.transmission_queue), or a bug/edge-case in the Service Broker transport layer interacting with Windows Server 2025 networking stack. In rare cases, it can also be triggered by conflicting third-party antivirus or EDR software intercepting named pipes or TCP ports used by Service Broker.

Step-by-Step Resolution Guide

Step 1: Check SQL Server and Windows Event Logs

  • Open SQL Server Management Studio (SSMS) and navigate to Management > SQL Server Logs.
  • Cross-reference the timestamp of Error 9626 with the Windows Event Viewer (Application and System logs) to check for disk I/O errors, memory dumps, or hardware-level warnings.
  • Look for accompanying errors like 824 (I/O error) or 3313 (recovery error), which indicate underlying corruption rather than a standalone Service Broker glitch.

Step 2: Run Database Consistency Checks (DBCC CHECKDB)

  • Execute the following command to scan for corruption in the system and user databases:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is found specifically in Service Broker objects, you may need to run DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS option, but only after taking a full backup, as this can result in the loss of unprocessed messages.

Step 3: Disable and Re-enable Service Broker

  • Sometimes resetting the Broker GUID and clearing the message queue resolves the “stuck” state.
  • Run the following T-SQL to disable broker:
  ALTER DATABASE YourDatabaseName SET DISABLE_BROKER;
  • Re-enable it immediately after:
  ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
  • Verify the is_broker_enabled flag is set to 1 in sys.databases.

Step 4: Clear the Transmission Queue and Restart the Service

  • Navigate to Services.msc on Windows Server 2025 and restart the SQL Server (MSSQLSERVER) service to clear any locked in-memory objects related to the broker.
  • If the queue remains stuck, manually purge expired conversations using:
  END CONVERSATION 'conversation_handle' WITH CLEANUP;
  • Check sys.transmission_queue to ensure the error count is decreasing after the restart.

Step 5: Apply the Latest Cumulative Update (CU)

  • Verify your current build number by running SELECT @@VERSION;.
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update for SQL Server 2025, as this specific internal state error is frequently patched in service packs related to the new Broker threading model.
  • Install the patch during a scheduled maintenance window, as it requires a service restart.

Alternative or Verification Steps

  • Verification: After restarting the service, query sys.dm_broker_queue_monitors to confirm that queue monitors are in a RUNNING state rather than DISABLED or UNKNOWN.
  • Alternative: If the error persists after a CU update, restore the specific database from the last known good backup taken before the corruption occurred, as this is often faster than manually rebuilding Service Broker objects.

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

Troubleshooting Guide: SQL Server Error 9624 – “The Key Size Is Unacceptable for This Key Object”

Why This Error Happens

This error typically occurs when SQL Server encounters an encryption key (such as a certificate or asymmetric key) whose key length does not meet the minimum or maximum size requirements enforced by the current cryptographic provider or SQL Server 2025’s updated security policies. This is common when keys were generated using outdated algorithms (like older RSA key lengths below 2048-bit) or when an Extensible Key Management (EKM) provider rejects the key size during an encryption/decryption operation. It can also surface after upgrading to SQL Server 2025 on Windows Server 2025, where stricter FIPS compliance and cryptographic module validation have been enforced at the OS level.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Key and Its Size

  • Run the following query to inspect certificate and key properties in the affected database:
  SELECT name, key_length, algorithm_desc 
  FROM sys.certificates;
  • For asymmetric or symmetric keys, check sys.asymmetric_keys or sys.symmetric_keys instead.
  • Confirm whether the key length falls below SQL Server 2025’s minimum requirement (2048-bit for RSA, 256-bit for AES).

Step 2: Regenerate the Key with a Supported Size

  • Drop the non-compliant key or certificate:
  DROP CERTIFICATE YourCertificateName;
  • Recreate it with a compliant key size:
  CREATE CERTIFICATE YourCertificateName 
  WITH SUBJECT = 'New Compliant Certificate', 
  EXPIRY_DATE = '2030-01-01';
  • If using TDE (Transparent Data Encryption), ensure the Database Encryption Key (DEK) is recreated using AES-256.

Step 3: Verify Cryptographic Provider Compatibility

  • If using an EKM provider (e.g., Azure Key Vault, Thales, or a HSM), confirm the provider DLL supports the key size being requested.
  • Check the provider configuration path, typically located at:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\
  • Update the provider driver if a newer version supporting larger key sizes is available.

Step 4: Check Windows Server 2025 FIPS and Cryptographic Policy Settings

  • Open Local Security Policy (secpol.msc) on Windows Server 2025 / Windows 11.
  • Navigate to:
    Security Settings > Local Policies > Security Options
  • Review the setting: “System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing”.
  • If enabled, ensure all SQL Server keys meet FIPS 140-3 minimum key length standards before re-enabling.

Step 5: Restart SQL Server Services and Validate

  • Restart the SQL Server service via SQL Server Configuration Manager to apply changes.
  • Re-run the operation that originally triggered Error 9624 (backup, restore, or encryption task) to confirm resolution.

Alternative or Verification Steps

  • Run sp_verify_database_ownership or re-attempt the BACKUP CERTIFICATE / OPEN SYMMETRIC KEY command to confirm the error no longer appears.
  • If the issue persists, use the SQL Server Error Log (ERRORLOG in MSSQL\Log directory) to trace which specific key or provider is rejecting the request, and consider migrating to a Windows CNG-compliant provider instead of legacy CryptoAPI (CAPI) keys.

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

Why This Error Happens

Error 9625 occurs when SQL Server’s cryptographic provider detects a mismatch between the stored key buffer length and the expected modulus size defined by the key’s algorithm (e.g., RSA 2048 vs. RSA 4096). This typically happens due to corruption in the encryption hierarchy—often within the Database Master Key (DMK), Service Master Key (SMK), or an Asymmetric Key/Certificate—usually caused by an incomplete key restoration, a failed ALTER operation on the key, or disk-level corruption affecting the master database. In rarer cases, this is triggered by compatibility issues when migrating keys from older SQL Server versions to SQL Server 2025 running on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the Integrity of the Master Database

  • Run DBCC CHECKDB('master') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for preceding I/O warnings or Event ID 824 entries that might indicate disk-level corruption.

Step 2: Identify and Isolate the Corrupted Key

  • Query sys.asymmetric_keys and sys.certificates to list all keys and check the algorithm_desc and key_length columns for anomalies.
  • Example query:
  SELECT name, algorithm_desc, key_length FROM sys.asymmetric_keys;
  • Cross-reference the key_length value with the actual modulus size of the original key file (if available) to confirm the mismatch.

Step 3: Drop and Recreate the Affected Key

  • If the key is a Database Master Key, back up the current state first (even if corrupted) for forensic purposes:
  BACKUP MASTER KEY TO FILE = 'C:\Backup\DMK_Backup.key' ENCRYPTION BY PASSWORD = 'StrongPassword123!';
  • Drop the corrupted key using DROP ASYMMETRIC KEY [KeyName] or ALTER MASTER KEY REGENERATE WITH ENCRYPTION BY PASSWORD = 'NewStrongPassword!';.
  • Recreate the key using CREATE ASYMMETRIC KEY or CREATE MASTER KEY, ensuring the correct algorithm (RSA2048, RSA3072, or RSA_4096) is explicitly specified to match the intended modulus size.

Step 4: Restore from a Known Good Backup (If Recreation Fails)

  • Navigate to your backup repository and locate the last known good backup of the master database taken prior to the corruption event.
  • Restore the master database in single-user mode via SQLCMD:
  sqlcmd -S localhost -E -Q "RESTORE DATABASE master FROM DISK='D:\Backups\master.bak' WITH REPLACE"
  • Restart the SQL Server service via services.msc or net start MSSQLSERVER once the restore completes.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query or stored procedure that triggered Error 9625; also execute SELECT * FROM sys.dm_exec_describe_first_result_set wrapped around the encryption function to ensure no further exceptions are thrown.
  • Alternative Fix: If key regeneration breaks dependent encrypted data (e.g., Always Encrypted columns), use the SQL Server Configuration Manager to re-import the certificate from a trusted Certificate Authority (CA) store on the Windows Server 2025 host rather than regenerating it internally.

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

Troubleshooting Guide: SQL Server Error 9623 — “The Key Passed in for This Operation Is in the Wrong State”

Why This Error Happens

Error 9623 typically occurs when SQL Server’s encryption hierarchy encounters a key object (symmetric or asymmetric) that is either corrupted, has been opened/closed out of sequence, or is incompatible with the cryptographic operation being requested. This often happens when a key is used after it has already been closed, when the Database Master Key (DMK) or Service Master Key (SMK) is in an inconsistent state, or when there’s a mismatch between the algorithm the key was created with and the operation attempting to use it. In SQL Server 2025 running on Windows Server 2025/Windows 11, this can also surface after OS-level security patches alter underlying CNG (Cryptography API: Next Generation) provider behavior.

Step-by-Step Resolution Guide

Step 1: Verify Key State and Session Scope

  • Check if the key was opened in the same session where the operation is being executed by running OPEN SYMMETRIC KEY YourKeyName DECRYPTION BY CERTIFICATE YourCert; immediately before the query.
  • Confirm the key hasn’t been closed prematurely with CLOSE SYMMETRIC KEY YourKeyName; earlier in the script or a different connection/session.
  • Run SELECT * FROM sys.openkeys; to see all currently open keys in the session and validate the target key appears in the list.

Step 2: Validate the Database Master Key and Service Master Key

  • Run OPEN MASTER KEY DECRYPTION BY PASSWORD = 'YourStrongPassword'; to ensure the DMK is accessible and not corrupted.
  • Check DMK encryption status using SELECT * FROM sys.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##';.
  • If the DMK appears corrupted, restore it from backup using RESTORE MASTER KEY FROM FILE = 'C:\Backup\DMK_Backup.bak' DECRYPTION BY PASSWORD = 'OldPassword' ENCRYPTION BY PASSWORD = 'NewPassword';.
  • Verify the SMK is intact by checking SQL Server error logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for SMK-related warnings during startup.

Step 3: Recreate or Re-Encrypt the Problematic Key

  • If the key object itself is flagged as corrupted, drop and recreate it: DROP SYMMETRIC KEY YourKeyName; CREATE SYMMETRIC KEY YourKeyName WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE YourCert;.
  • Ensure the algorithm specified (e.g., AES_256) matches what downstream encryption/decryption calls expect — mismatched algorithms are a common trigger for Error 9623.
  • Re-encrypt any data that relied on the old key using the newly created key to maintain data integrity.

Step 4: Check Windows CNG Provider and Certificate Store Health

  • Open PowerShell as Administrator and run certutil -verifystore My to confirm the certificate backing the key hasn’t expired or become corrupted in the Windows Certificate Store.
  • Restart the CNG Key Isolation service via Restart-Service -Name "KeyIso" since Windows Server 2025 security updates sometimes leave this service in a degraded state after patching.
  • Confirm SQL Server’s service account has appropriate read/execute permissions on C:\ProgramData\Microsoft\Crypto\Keys where machine-level key material is stored.

Step 5: Restart SQL Server Service to Clear Cached Key Handles

  • Open Services.msc (or use Restart-Service -Name "MSSQLSERVER" in PowerShell) to restart the SQL Server instance, which clears any stale in-memory key handles.
  • Re-run the original encryption/decryption query that triggered Error 9623 to confirm resolution.

Alternative or Verification Steps

  • Run SELECT crypt_type_desc FROM sys.certificates WHERE name = 'YourCert'; after applying fixes to confirm the certificate and key relationship is valid and active.
  • If the error persists, use DBCC CHECKDB on the affected database to rule out underlying page-level corruption affecting system catalog views related to key storage.

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

Troubleshooting Guide: SQL Server Error 9621 – Service Broker and Database Mirroring Transport Error

Why This Error Happens

Error 9621 occurs when the Service Broker or Database Mirroring transport layer fails to process a message, typically due to a malformed or corrupted message packet traveling across the TCP endpoint. This is often triggered by network instability, firewall interference that fragments packets incorrectly, or a mismatch in transport security (certificates or encryption) between the two endpoints. In some cases, outdated network drivers or SQL Server cumulative updates missing critical Service Broker bug fixes can also cause this behavior.

Step-by-Step Resolution Guide

Step 1: Verify Endpoint Configuration and Status

  • Run SELECT * FROM sys.database_mirroring_endpoints; on both the principal and mirror/partner instances to confirm the endpoint state is STARTED.
  • Check that the TRANSPORT_PROTOCOL is set to TCP and the port number matches on both sides (default is typically 5022).
  • Confirm the endpoint role matches its intended use: SELECT role_desc FROM sys.database_mirroring_endpoints;.

Step 2: Validate Certificates and Encryption Settings

  • If using certificate-based authentication, confirm certificates haven’t expired: SELECT name, expiry_date FROM sys.certificates;.
  • Ensure the ENCRYPTION algorithm (AES or RC4) matches on both endpoints — a mismatch will cause message parsing failures.
  • Re-issue and exchange public key certificates between instances if corruption or expiration is detected, then restart the endpoints with ALTER ENDPOINT.

Step 3: Check Firewall and Network Path Integrity

  • Open Windows Defender Firewall with Advanced Security on Windows Server 2025 and confirm an inbound/outbound rule exists for the SQL Server mirroring port (e.g., TCP 5022).
  • Use Test-NetConnection -ComputerName <PartnerServer> -Port 5022 in PowerShell to confirm the port is reachable without packet loss.
  • Disable any intermediate network inspection tools (deep packet inspection proxies) that may be fragmenting Service Broker traffic.

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.
  • Install the update on all nodes participating in the mirroring/Service Broker conversation, not just the primary.
  • Restart the SQL Server service (SQL Server (MSSQLSERVER)) via services.msc or Restart-Service MSSQLSERVER in PowerShell after installation.

Step 5: Review SQL Server Error Log and Extended Events

  • Open the SQL Server Error Log via SSMS (Management > SQL Server Logs) and search for recurring 9621 entries with accompanying detail codes.
  • Set up an Extended Events session tracking broker_transport_error and mirroring_transport_error to capture the exact failure point in real time.
  • Cross-reference the specific sub-error code reported alongside 9621 to identify if it’s a checksum failure, protocol version mismatch, or timeout.

Alternative or Verification Steps

  • After applying fixes, run a manual ALTER ENDPOINT [Mirroring] STATE = STOPPED; followed by STATE = STARTED; on both instances, then monitor the error log for 10–15 minutes to confirm no recurrence of Error 9621.
  • If the issue persists, drop and recreate the database mirroring session entirely (ALTER DATABASE SET PARTNER OFF and reconfigure) to rule out stale session metadata causing the transport conflict.

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

Troubleshooting Guide: SQL Server Error 9622 — “The Crypto Provider Context Is Not Initialized”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to use Extensible Key Management (EKM) or Transparent Data Encryption (TDE) functionality but cannot establish a valid handle to the underlying cryptographic provider. This is typically caused by a missing or corrupted cryptographic provider DLL registration, an improperly configured Hardware Security Module (HSM) connection, or insufficient permissions on the SQL Server service account to access the key store. It can also surface after an OS-level update to Windows Server 2025 or Windows 11 that alters Cryptographic API: Next Generation (CNG) provider registrations.

Step-by-Step Resolution Guide

Step 1: Verify the Cryptographic Provider Registration

  • Run SELECT * FROM sys.cryptographic_providers; in SQL Server Management Studio (SSMS) to confirm the provider is listed and enabled.
  • Check that the enabled column returns 1. If it returns 0, run ALTER CRYPTOGRAPHIC PROVIDER [ProviderName] ENABLE;.
  • Confirm the provider DLL path is valid, typically located at C:\Program Files\<VendorName>\<ProviderName>.dll.

Step 2: Re-register the Provider DLL with SQL Server

  • Drop the existing provider reference using DROP CRYPTOGRAPHIC PROVIDER [ProviderName]; (only if safe to do so and no active encryption depends on it).
  • Re-add the provider using CREATE CRYPTOGRAPHIC PROVIDER [ProviderName] FROM FILE = 'C:\Program Files\<VendorName>\<ProviderName>.dll';
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 3: Validate Service Account Permissions

  • Open Local Security Policy (secpol.msc) on Windows Server 2025 and confirm the SQL Server service account has the “Log on as a service” right.
  • Grant the service account read/execute permissions on the provider DLL folder and any associated HSM client configuration files (e.g., C:\ProgramData\<VendorName>\Config\).
  • If using an HSM, verify the client-side credentials (PIN, token, or certificate) are valid and not expired using the vendor’s management console.

Step 4: Re-initialize the Master Key and Provider Session

  • Run ALTER CRYPTOGRAPHIC PROVIDER [ProviderName] FORCE; to force SQL Server to re-establish the provider session.
  • If using TDE with EKM, verify the asymmetric key mapping with SELECT * FROM sys.asymmetric_keys WHERE crypto_provider_id IS NOT NULL;.
  • Restart the SQL Server instance again to apply the refreshed provider handle.

Alternative or Verification Steps

  • To verify the fix, run a test encryption operation (e.g., OPEN MASTER KEY or a TDE certificate backup) and confirm no Error 9622 appears in the SQL Server Error Log (ERRORLOG file under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\).
  • If the issue persists, reinstall the HSM/EKM vendor client software completely, reboot Windows Server 2025, and reconfigure the cryptographic provider from scratch before retrying the CREATE CRYPTOGRAPHIC PROVIDER statement.

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

Troubleshooting Guide: SQL Server Error 9619 – Remote Service Binding Already Exists

Why This Error Happens

This error occurs when Service Broker attempts to create a remote service binding that references a service name already bound to a certificate in the local database. SQL Server enforces a one-to-one relationship between a remote service binding and its target service, so duplicate CREATE REMOTE SERVICE BINDING statements—often triggered by re-run deployment scripts or migration jobs—will fail. This is also commonly seen after a database restore or copy operation where existing Service Broker metadata was not cleaned up before reapplying configuration scripts.

Step-by-Step Resolution Guide

Step 1: Identify the Existing Remote Service Binding

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance on Windows Server 2025 / Windows 11.
  • Run the following query to list current bindings:
  SELECT name, service_name, principal_id 
  FROM sys.remote_service_bindings;
  • Confirm whether the binding name in the error message matches an existing entry tied to the same service_name.

Step 2: Drop the Conflicting Binding (If Safe to Do So)

  • If the existing binding is outdated or part of a failed deployment, drop it before re-running your script:
  DROP REMOTE SERVICE BINDING [BindingName];
  • Verify no active conversations are using this binding by checking sys.conversation_endpoints to avoid disrupting live message traffic.

Step 3: Modify Deployment Scripts to Prevent Duplicates

  • Update your Service Broker setup scripts to include existence checks before creation:
  IF NOT EXISTS (
      SELECT 1 FROM sys.remote_service_bindings WHERE name = 'BindingName'
  )
  CREATE REMOTE SERVICE BINDING [BindingName]
      TO SERVICE 'TargetServiceName'
      WITH USER = [CertificateUser];
  • Ensure this logic is version-controlled in your deployment pipeline (e.g., Azure DevOps or GitHub Actions) to prevent recurrence in future releases.

Step 4: Recreate the Binding with Correct Parameters

  • If the original binding had incorrect certificate or user mapping, recreate it cleanly:
  CREATE REMOTE SERVICE BINDING [BindingName]
      TO SERVICE 'TargetServiceName'
      WITH USER = [CorrectCertificateUser];
  • Confirm the associated certificate is still valid and not expired using sys.certificates.

Alternative or Verification Steps

  • Re-run the original deployment script after cleanup; the CREATE REMOTE SERVICE BINDING statement should now complete without Error 9619.
  • If the issue persists, check for orphaned Service Broker objects by querying sys.services and sys.service_contracts, as a mismatched service definition can also trigger false-positive binding conflicts.

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

Troubleshooting Guide: SQL Server Error 9620 – “The activation stored procedure ‘%.*ls’ is invalid. Functions are not allowed.”

Why This Error Happens

This error occurs when a Service Broker queue is configured with an activation stored procedure, but SQL Server detects that the specified object is actually a scalar or table-valued function rather than a true stored procedure. Service Broker’s internal activation engine strictly requires an object of type PROCEDURE because it needs to execute the object asynchronously via sp_executesql-style invocation, which functions do not support. This typically happens after a deployment script, migration, or refactoring effort accidentally points the ACTIVATION PROCEDURE_NAME clause to the wrong schema object, or when a function was renamed/mistaken for a procedure during object creation.

Step-by-Step Resolution Guide

Step 1: Identify the Queue and Invalid Activation Object

  • Run the following query to locate the queue and its configured activation procedure name:
SELECT name, is_activation_enabled, activation_procedure 
FROM sys.service_queues 
WHERE activation_procedure IS NOT NULL;
  • Cross-reference the activation_procedure value against sys.objects to confirm its type column — look specifically for FN (scalar function), TF (table-valued function), or IF (inline table-valued function) instead of P (stored procedure).

Step 2: Disable Activation Temporarily

  • Before making changes, disable activation on the affected queue to stop SQL Server from repeatedly attempting (and failing) to invoke the invalid object:
ALTER QUEUE [YourQueueName] WITH ACTIVATION (STATUS = OFF);
  • This prevents error log flooding and stops unnecessary Broker task retries while you correct the configuration.

Step 3: Recreate or Point to a Valid Stored Procedure

  • If a stored procedure already exists with the correct logic, re-point the queue to it explicitly by name (ensure correct schema qualification, e.g., dbo.ProcessMessages).
  • If no valid procedure exists, convert the function logic into a proper CREATE PROCEDURE object:
CREATE PROCEDURE dbo.ProcessMessages
AS
BEGIN
    -- migrated logic from the function goes here
END;
  • Re-enable activation pointing to the corrected procedure:
ALTER QUEUE [YourQueueName] 
WITH ACTIVATION (
    STATUS = ON,
    PROCEDURE_NAME = dbo.ProcessMessages,
    MAX_QUEUE_READERS = 5,
    EXECUTE AS OWNER
);

Step 4: Validate Permissions and Execution Context

  • Confirm the EXECUTE AS principal (owner or specified user) has EXECUTE permission on the new procedure and SELECT/RECEIVE permission on the queue.
  • On Windows Server 2025 / Windows 11 hosts, also verify the SQL Server service account hasn’t been restricted by newly applied Group Policy or Windows Defender Application Control (WDAC) rules that could block procedure execution contexts.

Alternative or Verification Steps

  • Verify the fix by sending a test message into the service and monitoring sys.transmission_queue and the SQL Server error log — Error 9620 should no longer appear, and the queue’s is_activation_enabled column should remain 1 without being auto-disabled.
  • If the error persists, use sp_helptext on the procedure name to confirm there isn’t a naming collision between a same-named function and procedure in different schemas, and explicitly two-part name (schema.object) the PROCEDURE_NAME parameter to eliminate ambiguity.

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

Troubleshooting Guide: SQL Server Error 9618

Why This Error Happens

This error occurs when a Service Broker message attempts to route to a target service queue that has been explicitly disabled via ALTER QUEUE ... STATUS = OFF, while retention is simultaneously enabled on that same queue. SQL Server blocks delivery because a disabled queue cannot accept new messages, but since retention is ON, the engine refuses to silently drop or reroute the message, instead throwing error 9618 to preserve conversation integrity. This typically happens after a maintenance script, deployment rollback, or administrator action disables a queue without accounting for in-flight dialog traffic still targeting it.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Queue and Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting Error 9618.
  • Run the following query to locate disabled queues with retention enabled:
SELECT name, is_receive_enabled, is_enqueue_enabled, is_retention_enabled
FROM sys.service_queues
WHERE is_receive_enabled = 0 OR is_enqueue_enabled = 0;
  • Note the exact queue name and schema referenced in the error message (%.*ls placeholder).

Step 2: Re-enable the Service Queue

  • Execute an ALTER QUEUE statement to restore the queue’s active status:
ALTER QUEUE [SchemaName].[QueueName]
WITH STATUS = ON;
  • If the queue was disabled intentionally during a deployment window, confirm with the application team before re-enabling.
  • Ensure both ENQUEUE and RETENTION settings align with intended business logic:
ALTER QUEUE [SchemaName].[QueueName]
WITH STATUS = ON, RETENTION = ON;

Step 3: Drain or Process Pending Messages

  • Check the queue depth to see how many messages are backlogged:
SELECT COUNT(*) FROM [SchemaName].[QueueName];
  • If messages have accumulated due to the outage, manually process them using RECEIVE statements or trigger the associated activation stored procedure.
  • Restart the SQL Server Service Broker task via ALTER DATABASE [YourDB] SET ENABLE_BROKER; if activation appears stalled (verify this doesn’t disrupt active transactions first).

Step 4: Audit Automated Scripts and Maintenance Jobs

  • Review SQL Agent Jobs or deployment pipelines (e.g., Azure DevOps YAML, DACPAC deployments) for scripts that disable queues during schema updates.
  • Check msdb.dbo.sysjobhistory and Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for correlating timestamps when the queue was disabled.
  • Add safeguards (e.g., IF EXISTS checks) to prevent queues from being left disabled after maintenance windows.

Alternative or Verification Steps

  • Verify the fix by re-sending a test message through the dialog and confirming it lands in the target queue without triggering Error 9618 in the SQL Server Error Log.
  • If the queue continues to reject messages, check for orphaned conversation endpoints using sys.conversation_endpoints and consider ending stale dialogs with END CONVERSATION before retrying.

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

Troubleshooting Guide: SQL Server Error 9616 – XML Validation Failure in Service Broker Messages

Why This Error Happens

Error 9616 occurs when Service Broker receives a message that does not conform to the XML schema expected for that message type, typically because the message body is malformed, truncated, or was generated by an application using an outdated or mismatched contract definition. This can also result from encoding mismatches (e.g., UTF-16 vs UTF-8) between the sender and receiver endpoints, or from corruption introduced during message transmission across linked SQL Server instances. In some cases, the issue stems from a message type incorrectly configured as VALIDATION = WELL_FORMED_XML or VALIDATION = VALID_XML WITH SCHEMA COLLECTION when the sending application never intended to send strict XML.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Conversation and Message

  • Run the following query to pull details on the failed conversation using the Conversation ID from the error message:
  SELECT conversation_handle, far_service, message_type_name, state_desc
  FROM sys.conversation_endpoints
  WHERE conversation_id = 'PASTE-CONVERSATION-ID-HERE';
  • Check the Service Broker transmission queue for the raw message body:
  SELECT * FROM sys.transmission_queue
  WHERE conversation_handle = 'PASTE-CONVERSATION-HANDLE-HERE';
  • Inspect the transmission_status column for additional clues alongside the 9616 error.

Step 2: Validate the Message Type and Schema Collection Definition

  • Query the current validation setting on the message type:
  SELECT name, validation, validation_desc
  FROM sys.service_message_types
  WHERE name = 'YourMessageTypeName';
  • If validation_desc returns VALID_XML WITH SCHEMA COLLECTION, verify the schema collection still matches the application’s payload structure:
  SELECT xml_collection_id, name
  FROM sys.xml_schema_collections
  WHERE name = 'YourSchemaCollectionName';
  • If the application has changed its payload structure, update the schema collection using ALTER XML SCHEMA COLLECTION to reflect the new XSD.

Step 3: Capture and Inspect the Raw Payload

  • Use SQL Server Profiler or Extended Events (Broker:Message Classify and Broker:Conversation events) to capture the exact XML payload being sent.
  • Copy the captured XML into a validator (e.g., Visual Studio XML Editor or xmllint on Windows Server 2025 via WSL) to pinpoint the exact line/node causing the schema mismatch.
  • Check for BOM (Byte Order Mark) issues or encoding mismatches — SQL Server Service Broker expects UTF-16 encoded XML by default unless explicitly cast.

Step 4: Correct the Application or Contract Configuration

  • If the sending application is generating malformed XML, update the serialization logic (e.g., ensure proper namespace declarations and closing tags).
  • If the message type was configured too strictly, consider relaxing validation temporarily for diagnosis:
  ALTER MESSAGE TYPE YourMessageTypeName
  VALIDATION = WELL_FORMED_XML;
  • Redeploy the corrected application build or stored procedure that constructs the XML message body, then resend a test message through the same service/contract.

Step 5: Clear Poisoned Queues and Restart Broker Activity

  • If the queue has entered a poison message state (5 consecutive failures), re-enable it manually:
  ALTER QUEUE YourQueueName WITH STATUS = ON;
  • Restart the SQL Server Broker task if conversations remain stuck:
  ALTER DATABASE YourDatabaseName SET DISABLE_BROKER;
  ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
  • Monitor the SQL Server error log (Windows Server 2025 path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for recurrence of Error 9616 after the fix.

Alternative or Verification Steps

  • Send a manual test message through sys.sp_send_message using a known-valid XML payload to confirm the schema collection and validation settings now accept correctly formed messages.
  • If errors persist across all message types, consider temporarily dropping schema validation entirely (VALIDATION = NONE) as a diagnostic fallback to isolate whether the issue is XML-specific or a deeper transport/encoding problem on the Windows Server 2025 network stack.

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

Troubleshooting Guide: SQL Server Error 9617 – “The Service Queue Is Currently Disabled”

Why This Error Happens

This error occurs when a Service Broker queue has its STATUS property set to OFF, either manually by an administrator, automatically by SQL Server due to a “poison message” (a transaction that fails repeatedly and is rolled back), or as a default state following a database restore or attach operation. When a queue is disabled, SQL Server blocks all SEND and RECEIVE operations against it to prevent further message processing until the underlying issue is resolved. In Windows Server 2025 / Windows 11 environments, this is purely a logical database-state issue rather than an OS-level permission or networking fault.

Step-by-Step Resolution Guide

Step 1: Identify the Disabled Queue and Its Status

  • Open SQL Server Management Studio (SSMS) and connect to the target instance.
  • Run the following query to confirm the queue’s current state:
  SELECT name, is_receive_enabled, is_enqueue_enabled 
  FROM sys.service_queues 
  WHERE name = 'YourQueueName';
  • Check the SQL Server Error Log (via xp_readerrorlog or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for prior Error 9617 entries indicating when and why the queue was disabled.

Step 2: Investigate for Poison Message Handling

  • Determine if the queue was disabled due to 5 consecutive failed transaction rollbacks (the default poison message threshold).
  • Review the sys.transmission_queue system view for stuck or error-laden messages:
  SELECT * FROM sys.transmission_queue;
  • If a poison message is confirmed, identify and remove or correct the problematic message payload before re-enabling the queue to prevent an immediate recurrence.

Step 3: Re-Enable the Service Queue

  • Execute the ALTER QUEUE command to manually restore functionality:
  ALTER QUEUE YourQueueName WITH STATUS = ON;
  • If both sending and receiving were affected, ensure you explicitly re-enable both properties:
  ALTER QUEUE YourQueueName WITH STATUS = ON, RETENTION = OFF;

Step 4: Adjust Poison Message Threshold (Optional Fix)

  • If the queue disables frequently due to transient errors, disable the poison message detection feature using trace flag 1222 or by setting it at the queue level in SQL Server 2025’s updated Service Broker configuration panel.
  • Navigate to SSMS > Databases > Service Broker > Queues, right-click the queue, and verify the “Poison Message Handling” checkbox under properties.

Alternative or Verification Steps

  • Run SELECT is_receive_enabled, is_enqueue_enabled FROM sys.service_queues WHERE name = 'YourQueueName'; again to confirm both values return 1 (enabled).
  • If the queue immediately disables again after re-enabling, check for application-level logic errors in the stored procedure activation associated with the queue, as this usually indicates an unresolved poison message rather than a server configuration fault.

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

Troubleshooting Guide: SQL Server Error 9615 — Message Failed XML Validation on Target Service

Why This Error Happens

Error 9615 occurs when Service Broker validates an incoming message against the XML schema collection bound to the contract’s message type, and the message body does not conform to that schema. This is typically caused by a mismatch between the sender’s message format and the receiver’s expected schema, a schema that was altered or dropped after the contract was created, or a malformed/corrupted message payload generated by the application. It can also happen if the message type was defined with VALIDATION = WELL_FORMED_XML or VALID_XML WITH SCHEMA COLLECTION, but the application sends plain text, NULL, or improperly escaped XML.

Step-by-Step Resolution Guide

Step 1: Identify the Failing Message Type and Conversation

  • Query the error log or use the Conversation ID from the error message to trace the exact dialog:
  SELECT * FROM sys.conversation_endpoints WHERE conversation_id = '<ConversationID>';
  • Check sys.service_message_types to confirm the validation column value (X for XML, W for well-formed, N for none) for the message type in question.
  • Identify which XML Schema Collection is bound, if any:
  SELECT name, validation, xml_collection_id FROM sys.service_message_types;

Step 2: Validate the Message Payload Against the Schema Collection

  • Extract the raw message body from the queue before it errors out (if still accessible) using:
  SELECT message_body, message_type_name FROM dbo.YourQueueName;
  • Manually cast the body to XML using the bound schema collection to reproduce the validation failure:
  DECLARE @x XML(YourSchemaCollectionName);
  SET @x = CAST(@MessageBody AS XML);
  • Compare the structure against the actual .xsd definitions in sys.xml_schema_collections to pinpoint missing elements, namespace mismatches, or incorrect data types.

Step 3: Correct the Schema or Application Payload

  • If the schema collection is outdated, update it using ALTER XML SCHEMA COLLECTION to add the missing complex types or elements.
  • If the application is sending malformed XML, correct the serialization logic (check for unescaped characters, missing namespace declarations, or incorrect root elements) in the client code or SSIS/Service Broker producer.
  • Ensure the application explicitly sets the correct XML namespace matching the schema collection’s target namespace, as namespace mismatches are the most common root cause.

Step 4: Rebuild and Test the Service Broker Contract

  • If the message type or contract definitions are suspected to be corrupted, drop and recreate the message type with the correct validation setting:
  ALTER MESSAGE TYPE [YourMessageType] VALIDATION = VALID_XML WITH SCHEMA COLLECTION [YourSchemaCollection];
  • Restart the Service Broker queue processing (disable/enable) to clear any cached validation state:
  ALTER QUEUE [YourQueueName] WITH STATUS = OFF;
  ALTER QUEUE [YourQueueName] WITH STATUS = ON;

Alternative or Verification Steps

  • Send a test message through the conversation and confirm it reaches the target queue without generating Error 9615 in the SQL Server Error Log or sys.transmission_queue.
  • If validation continues to fail intermittently, consider temporarily relaxing validation to WELL_FORMED_XML on a non-production copy of the message type to isolate whether the issue is schema-specific or payload-specific, then revert once the root cause is confirmed.

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

Troubleshooting Guide: Error 9613 – Queue Activation Failure in SQL Server 2025

Why This Error Happens

This error occurs when Service Broker attempts to activate an internal or external queue, but the ACTIVATION clause was configured without a valid EXECUTE AS user. SQL Server requires a security context to run the activation stored procedure, and without a specified user (or if the specified user was dropped or renamed), the activation engine refuses to start the procedure. This is commonly seen after a database migration, a restore from backup, or when a queue is created/altered using a template script that omits the EXECUTE AS clause.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Queue and Current Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run the following query to locate the queue and check its activation settings:
SELECT name, is_activation_enabled, activation_procedure, execute_as_principal_id 
FROM sys.service_queues 
WHERE name = 'YourQueueName';
  • Confirm that execute_as_principal_id is NULL — this confirms the missing activation user.

Step 2: Alter the Queue to Specify a Valid Activation User

  • Choose a database user (not a login) that has appropriate permissions on the queue and associated objects.
  • Run the ALTER QUEUE statement with a valid EXECUTE AS user, for example:
ALTER QUEUE YourQueueName 
WITH ACTIVATION (
    STATUS = ON,
    PROCEDURE_NAME = YourActivationProcedure,
    MAX_QUEUE_READERS = 5,
    EXECUTE AS 'YourDatabaseUser'
);
  • Ensure YourDatabaseUser exists in the database via sys.database_principals before running this command.

Step 3: Grant Required Permissions to the Activation User

  • Verify the user has EXECUTE permission on the activation stored procedure:
GRANT EXECUTE ON YourActivationProcedure TO YourDatabaseUser;
  • Confirm the user also has RECEIVE permission on the queue itself:
GRANT RECEIVE ON YourQueueName TO YourDatabaseUser;

Step 4: Restart Service Broker for the Database (If Needed)

  • If activation still fails after reconfiguration, toggle Service Broker off and on to force re-registration:
ALTER DATABASE YourDatabaseName SET DISABLE_BROKER;
ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
  • On Windows Server 2025 / Windows 11, ensure the SQL Server service account has not changed, as this can invalidate cached broker security contexts.

Alternative or Verification Steps

  • Verify the fix by sending a test message to the queue and confirming the activation procedure executes without generating Error 9613 in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If the error persists, check for orphaned users using sp_change_users_login 'Report' and re-map the activation user’s login-to-user association, as a broken SID mapping can also trigger this error.

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

Troubleshooting Guide: SQL Server Error 9614 – Queue Activation Procedure Invalid

Why This Error Happens

Error 9614 occurs when a Service Broker queue is configured with ACTIVATION enabled, but the PROCEDURE_NAME specified either does not exist, has been dropped, or was never properly set during queue creation. This commonly happens after a database migration, restore, or schema deployment where the stored procedure was not recreated in the correct schema. It can also occur if the procedure exists but the Service Broker internal activation engine cannot resolve it due to a naming mismatch, incorrect schema binding, or insufficient permissions on the procedure object.

Step-by-Step Resolution Guide

Step 1: Verify the Current Queue Activation Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run the following query to inspect the queue’s activation settings:
  SELECT name, is_activation_enabled, activation_procedure 
  FROM sys.service_queues 
  WHERE name = 'YourQueueName';
  • Confirm whether activation_procedure is NULL or points to a non-existent object.

Step 2: Recreate or Repoint the Activation Stored Procedure

  • Ensure the stored procedure exists in the same schema referenced by the queue (commonly dbo).
  • If the procedure is missing, recreate it using the original deployment script, ensuring it matches the expected signature (no parameters, returns void).
  • Update the queue to point to the correct, fully qualified procedure name:
  ALTER QUEUE YourQueueName 
  WITH ACTIVATION (
      STATUS = ON,
      PROCEDURE_NAME = dbo.YourActivationProc,
      MAX_QUEUE_READERS = 5,
      EXECUTE AS OWNER
  );

Step 3: Validate Permissions and Execution Context

  • Check that the account specified in EXECUTE AS (e.g., OWNER or a specific user) has EXECUTE permission on the stored procedure.
  • Grant permissions if needed:
  GRANT EXECUTE ON dbo.YourActivationProc TO [DatabaseUserOrRole];
  • On Windows Server 2025, confirm the SQL Server service account has not been altered in Services.msc, as a broken service identity can also block activation execution.

Step 4: Restart Service Broker for the Database

  • Disable and re-enable Service Broker to force the activation engine to re-read queue metadata:
  ALTER DATABASE YourDatabase SET DISABLE_BROKER;
  ALTER DATABASE YourDatabase SET ENABLE_BROKER;
  • This clears any cached invalid references to the old procedure.

Alternative or Verification Steps

  • Send a test message into the queue and monitor SQL Server Error Log (via SSMS > Management > SQL Server Logs) to confirm no further 9614 errors are logged upon activation.
  • If the issue persists, drop and fully recreate the queue and its associated service/contract from scratch, as metadata corruption on the queue object itself can sometimes survive a simple ALTER QUEUE command.

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

Troubleshooting Guide: SQL Server Error 9611 – “Cannot find the specified user ‘%.*ls'”

Why This Error Happens

This error typically occurs when a database principal (user) referenced in a stored procedure, permission grant, or role membership assignment no longer exists in the target database, often due to an orphaned SID after a database restore or migration. It can also arise when a login exists at the server level but was never properly mapped to a database user via CREATE USER, or when case sensitivity/collation mismatches prevent SQL Server from resolving the username string. Corrupted system catalog views (sys.database_principals) or incomplete transactional replication metadata can also trigger this error during administrative operations.

Step-by-Step Resolution Guide

Step 1: Identify the Missing or Orphaned User

  • Run the following query against the affected database to check for orphaned users:
EXEC sp_change_users_login 'Report';
  • Cross-reference the username from the error message against sys.database_principals:
SELECT name, sid, type_desc FROM sys.database_principals WHERE name = 'ProblemUserName';
  • Note whether the user exists at the server login level but not at the database level (orphaned SID).

Step 2: Re-map or Recreate the User

  • If the login exists on the server but the database mapping is broken, re-link it:
ALTER USER [ProblemUserName] WITH LOGIN = [ProblemUserName];
  • If the user does not exist at all, create it explicitly before re-running the failing script or job:
CREATE USER [ProblemUserName] FOR LOGIN [ProblemUserName];
  • For contained databases, ensure the user was created with WITH PASSWORD rather than relying on a server login.

Step 3: Validate Permissions and Ownership Chains

  • Check for stored procedures, views, or jobs that explicitly reference the broken username (common in GRANT, DENY, or EXECUTE AS statements):
SELECT OBJECT_NAME(major_id), permission_name FROM sys.database_permissions WHERE grantee_principal_id = USER_ID('ProblemUserName');
  • Update any hardcoded EXECUTE AS USER = 'ProblemUserName' statements in SQL Agent jobs or stored procedures to reference the corrected username.
  • Restart the SQL Server Agent service on Windows Server 2025 to clear any cached job execution contexts:
Restart-Service -Name SQLSERVERAGENT -Force

Step 4: Rebuild System Metadata (If Corruption Suspected)

  • Run DBCC CHECKDB on the affected database to rule out catalog corruption:
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is found in system tables, restore the database from the last known good backup rather than attempting manual catalog edits.

Alternative or Verification Steps

  • Re-run the original failing query, job, or script and confirm Error 9611 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • If the issue persists, use sp_helpuser to generate a full list of valid database users and compare it against your application’s expected user list to catch any remaining naming mismatches.

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

Troubleshooting Guide: SQL Server Error 9609

Why This Error Happens

Error 9609 occurs when a multi-part identifier (such as a server, database, schema, or object name) exceeds the maximum number of allowed naming prefixes recognized by the SQL Server parser. This typically results from a malformed four-part name in a linked server query, a scripting error where delimiters (brackets or periods) are nested incorrectly, or dynamically generated SQL that concatenates object names without proper validation. It can also surface after migration scripts carry over legacy naming conventions that are no longer compatible with the parser rules in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Object Name

  • Capture the exact T-SQL statement from the error message, specifically the value in ‘%.*ls’.
  • Use SQL Server Profiler or Extended Events (QueryCompleted, ErrorReported) to trace which session or stored procedure triggered the error.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for correlating timestamps on Windows Server 2025.

Step 2: Correct the Multi-Part Naming Syntax

  • Verify the object reference follows the standard four-part naming convention: Server.Database.Schema.Object.
  • Remove any extra periods, brackets, or nested prefixes such as Server.Database.Schema.dbo.Object.
  • Example of a broken reference to fix:
  • Incorrect: [LinkedServer].[DB].[dbo].[Schema].[Table]
  • Corrected: [LinkedServer].[DB].[dbo].[Table]

Step 3: Audit Dynamic SQL and Linked Server Definitions

  • Open SQL Server Management Studio (SSMS) and navigate to Server Objects > Linked Servers.
  • Right-click each linked server, select Properties, and confirm the catalog and provider settings are not injecting extra naming layers.
  • Review any sp_executesql or string-concatenated dynamic SQL in stored procedures for improperly built identifiers, especially where variables are inserted into object paths.

Step 4: Rebuild and Test the Query in Isolation

  • Copy the corrected query into a new query window in SSMS.
  • Execute it against a test database first to confirm the parser accepts the identifier structure.
  • If using ORM tools or ETL packages (SSIS), regenerate the connection mapping to ensure it is not auto-appending schema prefixes incorrectly.

Alternative or Verification Steps

  • Run the corrected query during low-traffic hours and confirm no Error 9609 appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • If the error persists in a third-party application, temporarily enable SQL trace flag 3604 with DBCC TRACEON to output additional parser diagnostics to the console for deeper inspection.

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

Troubleshooting Guide: SQL Server Error 9610

Why This Error Happens

This error occurs in Service Broker when the FROM SERVICE clause in a BEGIN DIALOG CONVERSATION statement specifies a service name that does not match the service referenced by the contract or TO SERVICE binding, often due to a mismatch between the service name and the one registered in sys.services. This typically happens after a service is renamed, dropped and recreated with different casing, or when message routing configurations are manually edited and become out of sync with the broker’s internal metadata. Corrupted or stale routing entries in sys.routes can also cause the service name resolution to fail, triggering this validation error.

Step-by-Step Resolution Guide

Step 1: Verify the Service Name in sys.services

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run SELECT name, service_id FROM sys.services; to confirm the exact registered name, including case sensitivity.
  • Compare this output directly against the string used in your FROM SERVICE clause in the application code or T-SQL script.

Step 2: Inspect and Correct the BEGIN DIALOG Statement

  • Open the stored procedure or script that issues the BEGIN DIALOG CONVERSATION command.
  • Ensure the FROM SERVICE name matches character-for-character with the service name tied to the contract in the TO SERVICE clause.
  • Update the script, for example: BEGIN DIALOG @handle FROM SERVICE [CorrectServiceName] TO SERVICE 'TargetServiceName' ON CONTRACT [YourContract];

Step 3: Audit and Refresh Service Broker Routes

  • Navigate to the Query Editor and execute SELECT * FROM sys.routes; to check for outdated or conflicting route definitions.
  • If a route points to an incorrect or renamed service, drop it using DROP ROUTE [OldRouteName]; and recreate it with the correct SERVICE_NAME parameter.
  • Restart the SQL Server service via services.msc on Windows Server 2025 to clear any cached broker metadata.

Step 4: Validate Contract and Message Type Bindings

  • Confirm the contract referenced in your dialog matches the one bound to the service during creation using sys.service_contract_usages.
  • Re-create the service binding if necessary with CREATE SERVICE [ServiceName] ON QUEUE [QueueName] ([ContractName]); to ensure consistency.

Alternative or Verification Steps

  • Re-run the original BEGIN DIALOG CONVERSATION statement after corrections; if it executes without Error 9610, the service names are now properly aligned.
  • As an alternative, enable Service Broker trace flags (such as 9988) temporarily to log detailed conversation diagnostics in the SQL Server Error Log for deeper analysis if the issue persists.

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

Troubleshooting Guide: SQL Server Error 9608

Error Message: The conversation priority with ID %d is referencing the missing service contract with ID %d.

Why This Error Happens

This error occurs when a Service Broker conversation priority object references a service contract that has been dropped from the database while the priority definition still points to its internal ID. This typically happens after an incomplete schema migration, a manual DROP CONTRACT statement executed without first cleaning up dependent priorities, or metadata corruption within the Service Broker catalog views. SQL Server 2025 validates these cross-references during conversation setup, and a broken link prevents the Broker from resolving the correct priority level for message delivery.

Step-by-Step Resolution Guide

Step 1: Identify the Orphaned Conversation Priority

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance on Windows Server 2025 / Windows 11.
  • Run the following query to locate the broken reference:
  SELECT cp.conversation_priority_id, cp.name, cp.contract_id
  FROM sys.conversation_priorities cp
  LEFT JOIN sys.service_contracts sc ON cp.contract_id = sc.service_contract_id
  WHERE cp.contract_id IS NOT NULL AND sc.service_contract_id IS NULL;
  • Note the conversation_priority_id and contract_id values returned, matching the IDs in the error message.

Step 2: Drop and Recreate the Broken Priority

  • Script out the existing priority settings before removal, including LOCAL_SERVICE_NAME, REMOTE_SERVICE_NAME, and PRIORITY_LEVEL.
  • Drop the orphaned priority using:
  DROP BROKER PRIORITY [PriorityName];
  • Recreate it pointing to a valid, existing contract:
  CREATE BROKER PRIORITY [PriorityName]
  FOR CONVERSATION
  SET (CONTRACT_NAME = [ValidContractName],
       LOCAL_SERVICE_NAME = [ServiceName],
       PRIORITY_LEVEL = 5);

Step 3: Recreate the Missing Service Contract (If Required)

  • If the referenced contract was dropped in error, restore it using the original message types:
  CREATE CONTRACT [ContractName]
  ([MessageTypeName] SENT BY INITIATOR);
  • Re-link any dependent services using ALTER SERVICE if the contract is still used elsewhere in the Broker topology.

Step 4: Validate Service Broker Catalog Consistency

  • Run DBCC CHECKDB (YourDatabaseName) WITH DATA_PURITY; to rule out underlying metadata corruption.
  • Check the SQL Server error log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for related Broker warnings around the same timestamp.

Alternative or Verification Steps

  • Re-run the query from Step 1 — if it returns zero rows, the orphaned reference has been successfully resolved.
  • If the issue persists after recreating objects, restore the Service Broker configuration from a known-good database backup taken prior to the contract deletion, then reapply any schema changes incrementally.

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

Troubleshooting Guide: Error 9606 – Conversation Priority Dropped

Why This Error Happens

This error occurs when SQL Server’s Service Broker attempts to clean up a conversation priority object that is still referenced by an invalid or orphaned metadata entry in the sys.conversation_priorities system catalog. It is typically caused by corruption in the Service Broker metadata tables, an interrupted ALTER/DROP operation on a priority object, or a mismatch between the broker’s internal priority cache and the on-disk catalog after an unexpected server shutdown. In some cases, this is also triggered when third-party backup or replication tools interact with Service Broker queues during a priority reassignment, leaving a dangling reference ID.

Step-by-Step Resolution Guide

Step 1: Verify the Scope of the Corrupted Priority Object

  • Query the system catalog to identify the dropped priority ID referenced in the error: SELECT * FROM sys.conversation_priorities WHERE conversation_priority_id = %d;
  • Check the SQL Server error log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for repeated occurrences of Error 9606.
  • Cross-reference the timestamp of the error with any recent ALTER BROKER PRIORITY or DROP BROKER PRIORITY statements in your query history.

Step 2: Run Database Consistency Checks

  • Open SQL Server Management Studio (SSMS) and execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to detect catalog-level corruption.
  • If corruption is found specifically in Service Broker objects, run DBCC CHECKCATALOG ('YourDatabaseName'); to isolate catalog consistency issues.
  • Review the output for any sys.conversation_priorities or sys.service_broker related inconsistency flags.

Step 3: Rebuild or Reset the Broker Priority Configuration

  • Disable Service Broker temporarily on the affected database: ALTER DATABASE YourDatabaseName SET DISABLE_BROKER;
  • Drop and recreate the specific conversation priority object using a clean definition: DROP BROKER PRIORITY IF EXISTS YourPriorityName; CREATE BROKER PRIORITY YourPriorityName FOR CONVERSATION SET (CONTRACT_NAME = YourContractName, LOCAL_SERVICE_NAME = YourServiceName, REMOTE_SERVICE_NAME = N'ANY', PRIORITY_LEVEL = 5);
  • Re-enable Service Broker: ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025, as this issue has known fixes in Service Broker metadata handling.
  • Install via an elevated PowerShell session: Start-Process -FilePath "SQLServer2025-KB*.exe" -ArgumentList "/quiet /IAcceptSQLServerLicenseTerms" -Wait
  • Restart the SQL Server service through services.msc or Restart-Service -Name 'MSSQLSERVER' in PowerShell after installation.

Alternative or Verification Steps

  • To verify the fix, monitor the SQL Server error log for 24–48 hours and confirm Error 9606 no longer appears; additionally, run SELECT * FROM sys.conversation_priorities; to ensure the priority list is clean and consistent.
  • If the error persists after these steps, restore the affected database from a known-good backup taken prior to the corruption event, then re-apply only the Service Broker configuration changes manually rather than through automated scripts.

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

Troubleshooting Guide: SQL Server Error 9607

Why This Error Happens

Error 9607 occurs in Service Broker when a conversation priority object references a service ID that no longer exists in the sys.services catalog view. This typically happens because the referenced service was dropped while conversation priorities still pointed to it, or metadata became inconsistent due to an incomplete DDL transaction, replication/sync issue, or database restore from an inconsistent backup state. The Service Broker internal catalog tables are left with an orphaned reference, causing validation failures whenever the broker engine attempts to resolve priority-to-service mappings.

Step-by-Step Resolution Guide

Step 1: Identify the Orphaned Conversation Priority

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to list conversation priorities and their linked service IDs:
SELECT conversation_priority_id, name, service_id, service_contract_id 
FROM sys.conversation_priorities;
  • Cross-reference service_id against sys.services to confirm which IDs are missing:
SELECT service_id, name FROM sys.services;

Step 2: Drop the Invalid Conversation Priority

  • Once you’ve confirmed which priority is referencing a nonexistent service, remove it using:
DROP BROKER PRIORITY [PriorityName];
  • If the priority name is unknown due to corruption, use the conversation_priority_id to look it up via sys.conversation_priorities before dropping.
  • Ensure no active applications depend on this priority before removal to avoid disrupting message routing.

Step 3: Recreate the Service and Priority (If Needed)

  • If the missing service was dropped unintentionally, recreate it with the original name and queue association:
CREATE SERVICE [ServiceName] ON QUEUE [SchemaName].[QueueName]
([ContractName]);
  • Re-create the conversation priority pointing to the restored service:
CREATE BROKER PRIORITY [PriorityName]
FOR CONVERSATION
SET (LOCAL_SERVICE_NAME = [ServiceName]);

Step 4: Run Database Consistency Checks

  • Execute DBCC CHECKDB on the affected database to rule out broader catalog corruption:
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output for additional Service Broker metadata inconsistencies and repair as directed.

Step 5: Validate Service Broker Configuration

  • Confirm Service Broker is enabled on the database:
SELECT is_broker_enabled FROM sys.databases WHERE name = 'YourDatabaseName';
  • If disabled unexpectedly, re-enable it using:
ALTER DATABASE [YourDatabaseName] SET ENABLE_BROKER;

Alternative or Verification Steps

  • Re-run the sys.conversation_priorities and sys.services join query to confirm no orphaned references remain, and check the SQL Server Error Log for recurrence of Event ID 9607.
  • If the issue persists after cleanup, restore the database from a known-good backup taken prior to the service deletion, then reapply any transactional changes via log shipping or point-in-time recovery.

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

Troubleshooting Guide: SQL Server Error 9605 — “Conversation Priorities analyzed: %d”

Why This Error Happens

Error 9605 is an informational/diagnostic message raised by the Service Broker priority conductor during conversation priority analysis, typically surfacing when the internal priority cache is rebuilt or recalculated. This occurs when conversation priority rules are added, modified, or dropped, or when the Service Broker engine performs a priority evaluation pass on a large number of active conversations. In most cases, this message is benign and simply reports the count of priorities analyzed, but it can be accompanied by performance degradation if the underlying sys.conversation_priorities metadata is corrupted or if the queue monitor is under heavy contention.

Step-by-Step Resolution Guide

Step 1: Confirm the Severity and Context of the Message

  • Check the SQL Server Error Log and Windows Event Viewer (Application log, source: MSSQLSERVER) to confirm Error 9605 is informational rather than paired with a failure code (e.g., 9603 or 9617).
  • Run the following query to inspect active conversation priority definitions:
  SELECT * FROM sys.conversation_priorities;
  • Note the timestamp and correlate it with any recent ALTER BROKER PRIORITY or CREATE BROKER PRIORITY statements executed against the database.

Step 2: Validate Service Broker Configuration Integrity

  • Ensure Service Broker is enabled on the affected database:
  SELECT name, is_broker_enabled FROM sys.databases WHERE name = 'YourDatabaseName';
  • If is_broker_enabled returns 0, enable it:
  ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
  • Verify there are no orphaned or duplicate priority entries causing the analyzer to re-scan excessively:
  DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 3: Rebuild or Reset Conversation Priority Cache

  • Drop and recreate any suspect broker priorities to force a clean recalculation:
  DROP BROKER PRIORITY IF EXISTS YourPriorityName;
  CREATE BROKER PRIORITY YourPriorityName
      FOR CONVERSATION
      SET (CONTRACT_NAME = YourContractName, LOCAL_SERVICE_NAME = YourServiceName, PRIORITY_LEVEL = 5);
  • Restart the SQL Server service via Services.msc (services.msc) or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • On Windows Server 2025 / Windows 11, ensure the SQL Server service account has proper read/write access to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\ to avoid metadata write failures during cache rebuild.

Step 4: Apply Latest Cumulative Update

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as early builds may log 9605 more verbosely due to a known diagnostic logging bug.
  • Download and install the update from the Microsoft Update Catalog, then verify via:
  SELECT @@VERSION;

Alternative or Verification Steps

  • Re-run a load test that generates Service Broker conversations and monitor the Error Log to confirm Error 9605 only appears as an informational count without accompanying warnings or timeouts.
  • If the message persists with performance impact, enable Trace Flag 9604 (contact Microsoft Support for guidance) or disable verbose Service Broker diagnostic logging via sp_configure 'Service Broker diagnostics', 0; followed by RECONFIGURE;.

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

Troubleshooting Guide: SQL Server Error 9601

Why This Error Happens

Error 9601 occurs when SQL Server’s query processor attempts to relate two objects (typically during a SELECT INTO, Service Broker conversation, or internal metadata operation) but one of the referenced objects is in an invalid, disabled, or incompatible state for that relationship. This commonly stems from a corrupted or orphaned schema reference, a mismatch between Service Broker conversation handles and dialog states, or stale metadata left behind after an interrupted DDL operation or failed upgrade. In many Windows Server 2025 / SQL Server 2025 environments, this surfaces after an in-place upgrade where system catalog views retain references to objects that no longer match their expected state.

Step-by-Step Resolution Guide

Step 1: Identify the Specific Object and State Referenced in the Error

  • Capture the full error text from SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Note the %.*ls substitution values in the message — this identifies the exact object name and the conflicting state (e.g., “disabled,” “offline,” or “dropped”).
  • Run SELECT * FROM sys.messages WHERE message_id = 9601 AND language_id = 1033; to confirm the exact message template for your build.

Step 2: Check Service Broker and Conversation Endpoints (If Applicable)

  • Run SELECT * FROM sys.conversation_endpoints WHERE state_desc <> 'CONVERSING'; to find endpoints stuck in an invalid state.
  • If broken endpoints are found, end them manually with END CONVERSATION 'conversation_handle' WITH CLEANUP;
  • Disable and re-enable the Service Broker on the affected database using ALTER DATABASE [YourDB] SET DISABLE_BROKER; followed by ALTER DATABASE [YourDB] SET ENABLE_BROKER;

Step 3: Run Consistency and Catalog Validation Checks

  • Execute DBCC CHECKDB('YourDB') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption.
  • Run DBCC CHECKCATALOG('YourDB'); to validate consistency between system tables and catalog views.
  • Review output for orphaned schema bindings or mismatched object_id references tied to the error.

Step 4: Rebuild or Drop/Recreate the Affected Object

  • If a specific table, view, or constraint is flagged, script it out using SQL Server Management Studio (SSMS) 21 before making changes.
  • Drop and recreate the object using DROP OBJECT_NAME followed by the original CREATE script.
  • For constraint-related conflicts, verify foreign key and check constraint states using SELECT name, is_disabled FROM sys.foreign_keys; and re-enable with ALTER TABLE ... WITH CHECK CHECK CONSTRAINT ALL;

Step 5: Apply the Latest Cumulative Update

  • Confirm your current build via SELECT @@VERSION; in SSMS or sqlcmd.
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in an elevated PowerShell session after installation.

Alternative or Verification Steps

  • Re-run the original query or operation that triggered Error 9601 and confirm it completes without exception; check the ERRORLOG for recurrence over a 24-hour monitoring window.
  • If the issue persists, restore a known-good backup of the affected database to a test instance and compare catalog states using DBCC CHECKCATALOG, isolating whether the corruption originated from the production environment or a specific transaction.

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

Troubleshooting Guide: SQL Server Error 9602 – “Failed to start a system task with error code %d”

Why This Error Happens

This error typically occurs when SQL Server’s internal scheduler is unable to allocate a worker thread for a background system task, often due to resource exhaustion or a misconfigured max worker threads setting. It can also result from insufficient memory reserved for the SQLOS scheduler pool, corrupted system database files (such as tempdb or model), or a Windows-level permission restriction preventing the SQL Server service account from spawning new threads. In some cases, this is triggered by antivirus or endpoint protection software interfering with SQL Server’s process-level thread creation on Windows Server 2025 / Windows 11.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Open Services.msc and locate the SQL Server (MSSQLSERVER) service.
  • Confirm the service account has “Log on as a service” rights under Local Security Policy > User Rights Assignment.
  • Ensure the account is not restricted by Group Policy on Windows Server 2025 domain controllers.
  • Restart the SQL Server service after confirming permissions.

Step 2: Check and Adjust Max Worker Threads Configuration

  • Open SQL Server Management Studio (SSMS) and run:
  EXEC sp_configure 'max worker threads';
  • If the value is non-zero and too low for your workload, reset it to default (0 = auto-configure) using:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max worker threads', 0;
  RECONFIGURE;
  • Restart the SQL Server instance for changes to take effect.

Step 3: Rebuild or Repair TempDB

  • Check the health of tempdb files located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Stop the SQL Server service, verify the drive has sufficient free space (minimum 20% recommended), and restart the service.
  • If corruption is suspected, run:
  DBCC CHECKDB (tempdb) WITH NO_INFOMSGS;

Step 4: Exclude SQL Server Processes from Antivirus/EDR Scanning

  • Add exclusions for sqlservr.exe and the data/log directories in Windows Defender or third-party antivirus software.
  • Navigate to Windows Security > Virus & threat protection > Exclusions and add the SQL Server installation path.
  • Restart the SQL Server service and monitor the SQL Server Error Log for recurrence of Error 9602.

Alternative or Verification Steps

  • Check the SQL Server Error Log (ERRORLOG file in the MSSQL\LOG directory) after restarting the service to confirm Error 9602 no longer appears during startup or task execution.
  • If the issue persists, run sp_configure 'max worker threads' again to confirm the value reset correctly, and review Windows Event Viewer > System Log for related resource-exhaustion warnings (e.g., thread pool starvation or memory pressure alerts).

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

Troubleshooting Guide: Error 9539 – Selective XML Index Not Supported for Current Database Version

Why This Error Happens

Error 9539 occurs when a database attempting to use Selective XML Indexes (SXI) is still operating at a compatibility level below the minimum required for this feature, typically because the database was migrated or restored from an older SQL Server instance without updating its compatibility level. This can also occur if the database is still in the process of being upgraded internally, leaving catalog metadata inconsistent with SQL Server 2025 engine expectations. Additionally, corrupted system catalog views related to XML schema collections can trigger this error even on databases that appear to be at the correct version.

Step-by-Step Resolution Guide

Step 1: Verify the Current Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the current compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm the value is below 170 (SQL Server 2025 baseline), which indicates the database has not been upgraded.

Step 2: Upgrade the Database Compatibility Level

  • Execute the following T-SQL command to raise the compatibility level:
  ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;
  • Ensure no active transactions or blocking sessions are running against the database during this change.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if the setting does not apply immediately.

Step 3: Rebuild XML Schema Collection Metadata

  • Navigate to the affected database in SSMS and locate the XML Schema Collections under Programmability > Types > XML Schema Collections.
  • Drop and recreate any XML Schema Collections tied to the Selective XML Index using:
  DROP XML SCHEMA COLLECTION [SchemaName];
  CREATE XML SCHEMA COLLECTION [SchemaName] AS N'<schema definition>';
  • Re-run the CREATE SELECTIVE XML INDEX statement to confirm the feature is now recognized.

Step 4: Validate SQL Server Instance Patch Level

  • Open a PowerShell terminal as Administrator and check the installed SQL Server build:
  SELECT @@VERSION;
  • Confirm the build number matches the latest Cumulative Update (CU) for SQL Server 2025, as early RTM builds may have incomplete SXI feature support.
  • Apply the latest CU from the Microsoft Update Catalog if the build is outdated, then restart the SQL Server (MSSQLSERVER) service.

Alternative or Verification Steps

  • After completing the steps above, re-run your original CREATE SELECTIVE XML INDEX statement; if it executes without Error 9539, the compatibility level and schema metadata are correctly aligned.
  • As an alternative, if upgrading compatibility level is not immediately feasible, consider using standard XML indexes (CREATE PRIMARY XML INDEX) as a temporary workaround until the full database upgrade can be scheduled.

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

Troubleshooting Guide: SQL Server Error 9537 – Selective XML Index Path Collation Conflict

Why This Error Happens

This error occurs when a database or column-level collation change causes two previously distinct XML paths within a Selective XML Index (SXI) to resolve to identical path names. Because SQL Server 2025 enforces unique path name resolution for indexed XML nodes, a new collation—typically one with different case-sensitivity or accent-sensitivity rules—can cause two paths that were once considered different (e.g., “Node” vs. “node”) to now collapse into a single match. This conflict prevents the index metadata from being rebuilt safely under the new collation setting.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting XML Paths

  • Query sys.selective_xml_index_paths and sys.xml_indexes to list all paths currently indexed on the affected table.
  • Cross-reference the path names against the new target collation (e.g., SQL_Latin1_General_CP1_CI_AS vs. a case-sensitive collation like Latin1_General_100_CS_AS) to find which two paths would now match.
  • Run SELECT name, path, collation_name FROM sys.selective_xml_index_paths WHERE object_id = OBJECT_ID('YourTable'); to pinpoint duplicates.

Step 2: Drop the Affected Selective XML Index

  • Before altering the database or column collation, drop the existing SXI to avoid blocking the collation change.
  • Execute DROP SELECTIVE XML INDEX [YourIndexName] ON [YourSchema].[YourTable];
  • Confirm the index is removed by re-checking sys.xml_indexes for the table.

Step 3: Apply the Collation Change

  • Proceed with the intended collation change at the database or column level using ALTER DATABASE or ALTER TABLE ... ALTER COLUMN with the COLLATE clause.
  • On Windows Server 2025/Windows 11 hosts, ensure the OS locale and regional settings align with the new SQL collation to prevent downstream sorting mismatches.
  • Restart the SQL Server service only if the instance-level collation was modified (not required for column-level changes).

Step 4: Recreate the Selective XML Index with Disambiguated Paths

  • Rewrite the XML path definitions to be explicitly unique under the new collation (e.g., rename conflicting node promotions or use fully qualified XPath expressions).
  • Recreate the index using CREATE SELECTIVE XML INDEX [YourIndexName] ON [YourSchema].[YourTable]([XmlColumn]) FOR ([PathName1] = 'path/to/node1', [PathName2] = 'path/to/node2');
  • Validate successful creation by checking sys.selective_xml_index_paths again.

Alternative or Verification Steps

  • Run DBCC CHECKCONSTRAINTS and query the index metadata views post-recreation to confirm no duplicate path names remain under the new collation.
  • If recreating the index with unique paths is not feasible, consider reverting to the original collation or isolating the XML column in a separate table with its own collation setting to avoid conflicts with the rest of the schema.

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

Troubleshooting Guide: SQL Server Error 9538 – Selective XML Index SINGLETON Option Conflict

Why This Error Happens

This error occurs when you attempt to create a Selective XML Index (SXI) on an XML column where multiple path expressions point to the same underlying XML path, but the SINGLETON option is inconsistently applied across them. SQL Server requires that if one path entry for a given path expression specifies SINGLETON ON (or OFF), every other path entry sharing that identical path expression within the same selective XML index must use the exact same setting. This typically happens due to a copy-paste error in a multi-path CREATE SELECTIVE XML INDEX statement or when a script was migrated from an older schema without validating the SINGLETON clauses for duplicate paths.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Path Definitions

  • Open the CREATE SELECTIVE XML INDEX or ALTER script that triggered Error 9538 in SQL Server Management Studio (SSMS).
  • Locate the specific selective XML index name referenced in the error message (the %.*ls placeholder will show the actual index name in your error log).
  • Manually scan the FOR clause of the statement to find every path expression that repeats, as these are the entries causing the conflict.

Step 2: Audit Existing Path Nodes in System Views

  • Run a query against the system catalog views to see how the paths are currently registered (if the index partially exists or if you are modifying an existing one):
SELECT path_id, path_expression, is_singleton 
FROM sys.xml_index_nodes 
WHERE object_id = OBJECT_ID('YourTableName');
  • Cross-reference the is_singleton column for duplicate path_expression values to confirm the mismatch (e.g., one row shows 1 and a duplicate row shows 0).

Step 3: Correct the SINGLETON Syntax

  • Edit the T-SQL script to ensure uniformity. If a path /Root/Customer/Name appears twice, both instances must explicitly declare SINGLETON ON or SINGLETON OFF—never a mix of the two.
  • Standardize the syntax as follows:
CREATE SELECTIVE XML INDEX SXI_Index ON dbo.YourTable(XmlColumn)
FOR ('/Root/Customer/Name' AS XQUERY 'xs:string' SINGLETON ON, 
     '/Root/Customer/Name' AS XQUERY 'xs:string' SINGLETON ON)
  • Save the script and re-execute it in a test environment first to confirm the CREATE INDEX command processes without throwing Error 9538.

Step 4: Rebuild the Selective XML Index

  • Once the script is corrected, drop the faulty index definition if it was partially created:
DROP SELECTIVE XML INDEX SXI_Index ON dbo.YourTable;
  • Re-run the corrected CREATE SELECTIVE XML INDEX statement to apply the fixed configuration to the production database.

Alternative or Verification Steps

  • Verification: After the index rebuild, run DBCC CHECKDB or query sys.selective_xml_index_paths to ensure the is_singleton flag is consistent (either all 1s or all 0s) for every duplicate path_expression in the new index.
  • Alternative: If standardizing on SINGLETON ON causes application errors due to non-singleton XML nodes, default to SINGLETON OFF for the ambiguous paths, as this is the safer, more permissive setting for XML structures where a node might repeat under the same parent.

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

Troubleshooting Guide: Error 9536 in Microsoft SQL Server 2025

Why This Error Happens

This error occurs when an ALTER SELECTIVE XML INDEX statement contains duplicate REMOVE clauses referencing the identical XML pathname within the same batch. SQL Server’s XML indexing engine validates that each path modification is unique during the parse phase, and it rejects the statement outright when it detects redundant removal instructions for a single path. This is typically caused by poorly generated or copy-pasted T-SQL scripts, automated schema migration tools duplicating path entries, or manual errors when consolidating multiple ALTER statements into one.

Step-by-Step Resolution Guide

Step 1: Review the Full ALTER Statement Syntax

  • Open the exact T-SQL script that triggered Error 9536 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate every instance of the REMOVE keyword within the ALTER SELECTIVE XML INDEX statement.
  • Note the pathname (e.g., '/root/element/@attribute') listed after each REMOVE clause.

Step 2: Identify and Eliminate Duplicate Pathnames

  • Cross-reference each REMOVE '%.*ls' entry against the others in the same statement.
  • Delete the redundant line(s) so that each unique pathname appears only once in the REMOVE list.
  • If you intended to remove multiple distinct paths, ensure they are formatted as a comma-separated list rather than repeated identical entries.

Step 3: Validate the Current Index Path Definitions

  • Run the following query to inspect existing paths on the selective XML index before re-running the ALTER command:
SELECT path_id, path_expression, is_primitive_path 
FROM sys.selective_xml_index_paths 
WHERE xml_index_id = (SELECT index_id FROM sys.indexes WHERE name = 'YourXMLIndexName');
  • Confirm the pathname you intend to remove actually exists and matches the exact casing and syntax (including namespace prefixes) stored in the system view.

Step 4: Re-execute the Corrected ALTER Statement

  • Submit the cleaned-up script with a single REMOVE entry per unique path:
ALTER SELECTIVE XML INDEX YourIndexName ON YourSchema.YourTable
REMOVE ('/root/element/@attribute');
  • Monitor the Messages tab in SSMS for a successful “Command(s) completed successfully” confirmation instead of Error 9536.

Step 5: Check for Automated Script Generators

  • If the script was generated by a third-party ORM, migration tool, or deployment pipeline (e.g., Redgate, Liquibase, or custom PowerShell DacFx scripts), inspect the generator’s template logic.
  • Update the generator configuration to deduplicate path entries before the script reaches the SQL Server 2025 engine.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths again after the ALTER statement completes to confirm the path was successfully removed and no duplicates remain in the index metadata.
  • If the error persists despite a visually clean script, drop and recreate the selective XML index entirely using DROP INDEX followed by a fresh CREATE SELECTIVE XML INDEX statement with the correct, de-duplicated path set.

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

Troubleshooting Guide: SQL Server Error 9534 — Sparse Column Set Operation Failure

Why This Error Happens

Error 9534 occurs when a query or DML operation attempts to directly interact with a column set (the XML representation of sparse columns) in a way the SQL Server engine cannot resolve, typically because the underlying sparse column schema has become inconsistent or corrupted. This can happen when sparse columns were altered, dropped, or added without properly updating the associated column set metadata, or when replication/CDC processes reference a stale schema snapshot. It may also surface after an in-place upgrade to SQL Server 2025 if legacy sparse column definitions are incompatible with the new column store validation engine.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Table and Column Set

  • Run SELECT name, is_column_set FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName'); to locate the column set.
  • Check sys.sparse_column_set_properties (or equivalent DMV) to confirm metadata consistency.
  • Note the exact column set name reported in the error message (the %.*ls placeholder).

Step 2: Validate and Repair Schema Consistency

  • Run DBCC CHECKTABLE('YourTableName') WITH DATA_PURITY; to detect structural corruption.
  • If corruption is found, restore from the latest clean backup using RESTORE DATABASE YourDB FROM DISK = 'E:\Backups\YourDB.bak' WITH REPLACE;.
  • If no backup is available, script out the table, drop the column set, and recreate sparse columns manually using ALTER TABLE ... ADD COLUMN_SET FOR ALL_SPARSE_COLUMNS.

Step 3: Rebuild the Column Set Definition

  • Drop the existing column set: ALTER TABLE YourTableName DROP COLUMN YourColumnSetName;.
  • Recreate it: ALTER TABLE YourTableName ADD YourColumnSetName XML COLUMN_SET FOR ALL_SPARSE_COLUMNS;.
  • Ensure all sparse columns referenced still exist and have matching data types post-recreation.

Step 4: Update Statistics and Rebuild Indexes

  • Execute UPDATE STATISTICS YourTableName WITH FULLSCAN;.
  • Rebuild any indexes referencing sparse columns: ALTER INDEX ALL ON YourTableName REBUILD;.
  • Restart the SQL Server service via Services.msc on Windows Server 2025 if metadata caching issues persist.

Step 5: Check for Replication/CDC Conflicts

  • If the table is used in replication, run sp_helparticle to confirm sparse column mappings are current.
  • Re-initialize the replication snapshot if schema drift is detected.
  • Disable and re-enable Change Data Capture (CDC) using sys.sp_cdc_disable_table and sys.sp_cdc_enable_table if applicable.

Alternative or Verification Steps

  • Re-run the original failing query against the table; confirm Error 9534 no longer appears and the column set returns expected XML output.
  • As an alternative, query the sparse columns individually (bypassing the column set) using explicit column names to confirm underlying data integrity before re-enabling the column set feature.

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

Troubleshooting Guide: SQL Server Error 9535

Why This Error Happens

This error occurs when creating or altering a Selective XML Index (SXI) on an untyped XML column, where a path node definition specifies the MAXLENGTH or SINGLETON option without first declaring an XSD (XML Schema Definition) type for that same path. SQL Server requires an explicit schema type to be bound to a path before it can apply length constraints or enforce singleton cardinality rules, because without a defined type, the engine has no schema context to validate against. This typically results from a manually scripted CREATE SELECTIVE XML INDEX statement where the PATHS clause is malformed or copied from a typed-XML template without the corresponding XMLSCHEMA association.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path Definition

  • Locate the exact T-SQL script used to create or modify the Selective XML Index.
  • Review the error message text closely—it specifies the exact path (%.*ls) and index name (%.*ls) causing the conflict.
  • Open SQL Server Management Studio (SSMS) and run the script in a query window to isolate the specific PATH clause triggering Error 9535.

Step 2: Remove Invalid Options or Add an XSD Type

  • If the column is genuinely meant to be untyped XML, edit the CREATE SELECTIVE XML INDEX statement and strip out the MAXLENGTH and SINGLETON keywords from the path node definition.
  • Example of a corrected syntax for untyped XML:
  CREATE SELECTIVE XML INDEX SXI_Orders 
  ON dbo.OrderData (XmlColumn)
  FOR (PATH1 = '/Root/Order/@ID');
  • Alternatively, if type enforcement is required, bind an XML Schema Collection to the column first using ALTER TABLE ... ALTER COLUMN XmlColumn XML (SchemaCollectionName).
  • Once the schema is bound, update the path definition to include the XSD type reference, which then permits the use of MAXLENGTH or SINGLETON.

Step 3: Drop and Recreate the Index

  • Since Selective XML Indexes cannot usually be altered in-place to change path definitions, run DROP INDEX SXI_Orders ON dbo.OrderData first.
  • Re-run the corrected CREATE SELECTIVE XML INDEX script from Step 2.
  • Check the “Messages” tab in SSMS to confirm the command completed successfully without raising Error 9535 or related schema-binding errors (like Error 9536).

Step 4: Clear Compilation Cache (If Error Persists)

  • If the error strangely persists despite a corrected script, there may be a stale execution plan or metadata cache issue specific to the Windows Server 2025 environment.
  • Run DBCC FREEPROCCACHE to clear the cached query plans.
  • Restart the SQL Server service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Alternative or Verification Steps

  • Verify the fix by querying the system view sys.selective_xml_index_paths for your specific table to confirm the path types and options are now registered correctly without constraint flags on null-typed paths.
  • If you need SINGLETON behavior but do not want to enforce a full XSD schema, consider promoting the path to a “primary XML index” instead, as these do not carry the same typed-schema prerequisites for cardinality hints.

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

Troubleshooting Guide: SQL Server Error 9524 – Invalid XML Format for Sparse Column Sets

Why This Error Happens

Error 9524 occurs when SQL Server 2025 attempts to parse XML data intended for a sparse column set, but the XML does not match the implicit schema expected (i.e., element names must correspond exactly to sparse column names, and the structure must be a single level of child elements under the row). This typically happens due to malformed XML generated by application code, manual edits to XML payloads, or encoding mismatches introduced during ETL/import processes. It can also occur if a column was renamed or dropped after the sparse column set was defined, causing the XML schema inference to fail during INSERT or UPDATE operations.

Step-by-Step Resolution Guide

Step 1: Validate the XML Structure Against the Sparse Column Set Schema

  • Open SQL Server Management Studio (SSMS) 21 and run SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName') AND is_sparse = 1; to confirm current sparse column names.
  • Compare these column names exactly against the XML element names in your INSERT/UPDATE statement — case sensitivity and whitespace matter.
  • Ensure the XML follows a flat structure: <row><ColumnName>Value</ColumnName></row> with no nested elements beyond one level.

Step 2: Rebuild or Regenerate the XML Payload

  • If the XML is generated by an application (e.g., .NET, Java, or Power Automate flow), regenerate it using FOR XML RAW or FOR XML AUTO queries against the sparse column set for a known-good template.
  • Example: SELECT * FROM YourTable FOR XML AUTO, ELEMENTS; and compare the output format to your problematic payload.
  • Check for encoding issues (UTF-8 vs UTF-16) in the source file using Notepad++ or Get-Content -Encoding UTF8 in PowerShell on Windows Server 2025.

Step 3: Check for Schema Drift on the Sparse Column Set

  • Run sp_help 'YourTableName' to confirm no columns referenced in the XML have been renamed, dropped, or excluded from the column set since the XML was authored.
  • If a column was renamed, use sp_rename to correct it back, or update the XML generation logic to reference the new column name.
  • Re-deploy any stored procedures or SSIS packages that reference the old schema.

Step 4: Re-run the Operation and Capture Detailed Error Output

  • Enable XML validation logging by wrapping the operation in a TRY...CATCH block and capturing ERROR_MESSAGE(), ERROR_LINE(), and ERROR_PROCEDURE().
  • Example:
BEGIN TRY
    UPDATE YourTable SET SparseColumnSet = @XmlData WHERE Id = 1;
END TRY
BEGIN CATCH
    PRINT ERROR_MESSAGE();
END CATCH
  • Use the line number and procedure name output to pinpoint the exact malformed XML fragment.

Alternative or Verification Steps

  • After applying fixes, run the original INSERT/UPDATE statement again and confirm no Error 9524 is raised; then query the table with SELECT SparseColumnSet FROM YourTable to verify the XML round-trips correctly.
  • If the issue persists, bypass the column set temporarily by inserting values directly into individual sparse columns (rather than via the XML column set) to isolate whether the problem is XML-specific or related to the underlying sparse column definitions.

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

Troubleshooting Guide: SQL Server Error 9522 – XQuery Modify Method Not Allowed on Sparse Column Sets

Why This Error Happens

This error occurs when a Transact-SQL statement attempts to use the XML .modify() method directly against an XML column that is part of a sparse column set, which SQL Server 2025 does not support due to how sparse column sets virtualize underlying XML data storage. The engine blocks in-place XQuery mutation operations on these columns because the sparse column set representation conflicts with the internal mechanics required for XML DML (Data Manipulation Language) updates. This typically surfaces after a schema migration, a column set redefinition, or when developers port legacy T-SQL scripts that assume standard XML column behavior without accounting for sparse column set restrictions.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Column and Table

  • Run sp_help 'YourTableName' in SQL Server Management Studio (SSMS) to confirm whether the XML column is part of a sparse column set.
  • Check the sys.columns catalog view and look for the is_sparse and is_column_set flags set to 1 on the target column.
  • Note the exact column name and table schema (e.g., dbo.Orders.XmlData) for reference in later steps.

Step 2: Rewrite the Update Logic to Avoid Direct XQuery Modify Calls

  • Instead of calling .modify('insert ...') directly on the sparse-set XML column, retrieve the XML value into a local XML type variable first.
  • Example: DECLARE @TempXml XML; SELECT @TempXml = XmlData FROM dbo.Orders WHERE Id = 1;
  • Apply the .modify() method on the @TempXml variable instead of the table column directly.
  • Write the modified value back using a standard UPDATE statement: UPDATE dbo.Orders SET XmlData = @TempXml WHERE Id = 1;

Step 3: Reconfigure the Column Set (If Direct Modification Is Required)

  • Open SSMS and navigate to Database > Tables > YourTable > Columns.
  • Right-click the sparse column set and select Modify to review its current configuration.
  • If direct XQuery support is a hard requirement, remove the column from the sparse column set definition using: ALTER TABLE dbo.Orders ALTER COLUMN XmlData DROP SPARSE;
  • Re-test the .modify() operation on the now-standard XML column outside the column set.

Step 4: Apply the Latest Cumulative Update for SQL Server 2025

  • Go to Start > Microsoft SQL Server 2025 > SQL Server Installation Center.
  • Check for pending cumulative updates (CUs) via Windows Update or the official Microsoft Download Center, since early builds of SQL Server 2025 on Windows Server 2025 / Windows 11 have had sparse column set handling patched in later CUs.
  • Install the update and restart the SQL Server (MSSQLSERVER) service via services.msc.

Alternative or Verification Steps

  • Verify the fix by re-running the original .modify() query against the restructured column or the temporary variable approach; confirm no Error 9522 is raised and the XML data updates correctly in the table.
  • As an alternative, if dropping the sparse attribute is not feasible for storage reasons, create a computed non-sparse shadow column that mirrors the XML data for modification purposes, then sync changes back programmatically via a trigger or stored procedure.

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

Troubleshooting Guide: SQL Server Error 9523 – Sparse Column Set XML Mismatch

Why This Error Happens

This error occurs when the XML data submitted to update a sparse column set includes an element name that references a non-sparse column instead of one of the sparse columns actually belonging to that column set. SQL Server 2025 strictly validates that every XML node tag maps to a valid sparse column member defined in the table schema, and any mismatch—often caused by outdated application code, incorrect XML generation logic, or a recent schema change that removed/renamed a sparse column—triggers this validation failure. It can also happen after a table alteration where a column was converted from sparse to non-sparse (or vice versa) without updating the corresponding XML mapping logic in the application layer.

Step-by-Step Resolution Guide

Step 1: Verify the Column Set Definition in SQL Server

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to inspect the sparse column set and its member columns:
  SELECT c.name AS ColumnName, c.is_sparse, c.is_column_set
  FROM sys.columns c
  WHERE c.object_id = OBJECT_ID('YourSchema.YourTable');
  • Confirm which columns are flagged is_sparse = 1 and which one is is_column_set = 1.

Step 2: Audit the XML Payload Being Submitted

  • Extract the exact XML fragment your application is sending to the column set (via application logs, SQL Profiler, or Extended Events).
  • Compare every XML element name against the sparse column names retrieved in Step 1.
  • Remove or correct any XML node that references a column marked is_sparse = 0, since only sparse columns belonging to the set are valid XML tags.

Step 3: Correct the Application Mapping Logic

  • Open the data access layer (e.g., C#/.NET Entity Framework model, stored procedure, or ETL mapping file) responsible for generating the XML.
  • Update the field-to-XML-tag mapping so it dynamically pulls only from sys.columns where is_sparse = 1 for that table, rather than a hardcoded list.
  • Redeploy the updated application binary or stored procedure to your Windows Server 2025 / Windows 11 environment.

Step 4: Rebuild or Alter the Column Set (If Schema Drifted)

  • If a column was recently changed from sparse to non-sparse, drop and recreate the column set to force SQL Server to resync metadata:
  ALTER TABLE YourSchema.YourTable DROP COLUMN YourColumnSetName;
  ALTER TABLE YourSchema.YourTable ADD YourColumnSetName XML COLUMN_SET FOR ALL_SPARSE_COLUMNS;
  • Confirm no application-level caching (e.g., EF model cache, connection pooling metadata) is still referencing the old schema.

Step 5: Test the Update Statement Directly

  • Run a manual UPDATE statement using a minimal, known-good XML fragment that only references confirmed sparse columns.
  • Confirm the statement executes without raising Error 9523 before re-enabling the full application workflow.

Alternative or Verification Steps

  • Re-run the original failing transaction/query after applying the fixes; check Windows Event Viewer (Application log) and SQL Server error logs to confirm Error 9523 no longer appears.
  • If the issue persists, as a quick workaround, bypass the column set entirely and update each sparse column individually using standard UPDATE ... SET ColumnName = value syntax instead of XML-based column set updates.

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

Troubleshooting Guide: SQL Server Error 9521 – Negative XML Date Value

Why This Error Happens

This error occurs when SQL Server 2025 attempts to parse or process an XML data type instance containing a date or dateTime value with a negative year component (e.g., a BCE date like -0001-01-01). The SQL Server XML parser strictly adheres to the W3C XML Schema specification for xs:date and xs:dateTime, but internally it cannot map negative year values to the standard SQL Server datetime range. This typically surfaces when data is imported from external systems (like legacy ERP exports or third-party XML feeds) that allow historical or placeholder dates outside the SQL-supported range, or when a corrupted XML column value was inserted via bulk insert without validation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data

  • Run a query against the suspect table using TRY_CAST or OPENXML to isolate rows causing the failure.
  • Example: SELECT id, xml_column FROM YourTable WHERE xml_column.exist('//*[contains(., "-")]') = 1
  • Check staging tables, SSIS packages, or ETL logs for the specific source file that introduced the negative date.

Step 2: Sanitize the Source XML Data

  • Open the source XML file or export stream using a text editor (Notepad++ or VS Code) and search for patterns matching -\d{4}-\d{2}-\d{2}.
  • Replace negative year prefixes with a valid minimum SQL Server date equivalent (e.g., 0001-01-01) or flag the record for manual review.
  • If the data originates from an automated feed, update the source application’s export logic to clamp dates to the valid range (0001–9999) before transmission.

Step 3: Update Import/ETL Validation Logic

  • In SSIS packages or Azure Data Factory pipelines, add a Derived Column transformation to validate date strings using a regex check (^-) before the XML Source component.
  • For T-SQL based imports, wrap the insert statement in a BEGIN TRY...END CATCH block to catch Error 9521 and redirect bad rows to an error logging table instead of failing the batch.
  • Restart the SQL Server Agent job or ETL job to re-run the import with the corrected validation layer in place.

Step 4: Patch and Restart SQL Server Service

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as early builds may have stricter (or buggy) XML schema validation.
  • Open Services.msc on Windows Server 2025, locate SQL Server (MSSQLSERVER), and restart the service after applying any pending patches.
  • Verify via SQL Server Configuration Manager that the instance is running the updated binary version (SELECT @@VERSION).

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT or SELECT statement against the XML column; Error 9521 should no longer appear in the SQL Server Error Log (viewable via SSMS > Management > SQL Server Logs).
  • If sanitization isn’t feasible, as a workaround, store the problematic value as NVARCHAR(MAX) instead of native XML type, and perform date validation at the application layer prior to casting back to XML.

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

Troubleshooting Guide: SQL Server Error 9519 (Invalid sql:variable Name in XQuery)

Why This Error Happens

This error occurs when an XQuery expression using the sql:variable() function references a variable name that is malformed, misspelled, or missing the required @ prefix. SQL Server’s XML/XQuery parser strictly validates that the string passed into sql:variable('...') matches an actual declared Transact-SQL variable, including the leading @ symbol. This commonly happens due to typos in dynamically generated XQuery strings, incorrect string concatenation when building queries programmatically, or copy-paste errors where the @ character was accidentally stripped during string formatting or encoding.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Open SQL Server Management Studio (SSMS) and check the SQL Server error log via Management > SQL Server Logs or query sys.messages for Error 9519 context.
  • Identify the exact T-SQL statement using .query(), .value(), or .exist() methods with an embedded sql:variable() call.
  • Use SQL Server Profiler or Extended Events (xml_deadlock_report won’t help here—use a generic SQL statement trace) to capture the exact failing batch text in real time.

Step 2: Inspect and Correct the Variable Reference

  • Confirm the variable passed to sql:variable() starts with @, for example: sql:variable("@EmployeeID") not sql:variable("EmployeeID").
  • Verify the variable is actually declared earlier in the same batch or stored procedure using DECLARE @EmployeeID INT;.
  • Check for accidental double-quote or escape character issues if the query is being built dynamically in an application layer (C#, PowerShell, Python) before being sent to SQL Server.

Step 3: Fix Dynamic SQL Generation Logic

  • If the XQuery is constructed via string concatenation in application code, add explicit validation to ensure the @ symbol is never stripped during encoding or parameterization.
  • Example correction in T-SQL:
  DECLARE @EmpID INT = 101;
  SELECT XmlCol.value('(/Employee/@id)[1]', 'INT') 
  FROM dbo.EmployeeXml
  WHERE XmlCol.exist('/Employee[@id = sql:variable("@EmpID")]') = 1;
  • Rebuild and redeploy any stored procedures or SSIS packages on Windows Server 2025 that generate this XQuery dynamically, ensuring the variable name string is hardcoded correctly rather than injected via untrusted input.

Step 4: Restart the Affected Session or Service

  • Close and reopen the SSMS query window to clear any cached execution plans tied to the malformed batch.
  • If the error persists in a production job, restart the SQL Server (MSSQLSERVER) service via Services.msc on Windows Server 2025, or run:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm it executes without Error 9519; check the Messages tab for a clean “Command(s) completed successfully” result.
  • If the issue persists in dynamically generated code, temporarily hardcode the sql:variable("@YourVar") string directly in a test query to isolate whether the root cause is in the T-SQL syntax or the upstream application logic generating the query text.

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

Why This Error Happens

This error occurs when a T-SQL query uses the sql:variable() function within an XQuery expression (typically inside .value(), .query(), or .nodes() methods) but the referenced name does not match a properly declared local variable in the current scope. It is frequently caused by a typo in the function name itself (e.g., sql:variables() or sql:Variable() instead of the case-sensitive sql:variable()), or by attempting to reference a column name rather than a declared DECLARE @variable statement. Because XQuery parses this as a system function call, SQL Server throws Error 9520 when it cannot resolve the identifier against its internal list of valid XQuery system functions.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Syntax and Casing

  • Open the query in SQL Server Management Studio (SSMS) and locate the .value() or .query() call throwing the error.
  • Confirm the function is typed exactly as sql:variable("@VariableName") — XQuery function names are case-sensitive, so sql:Variable or SQL:VARIABLE will fail.
  • Check for extra spaces or missing quotation marks around the variable name parameter.

Step 2: Confirm the Variable Is Declared and In Scope

  • Ensure the referenced variable (e.g., @UserID) is declared with DECLARE @UserID INT; earlier in the same batch or stored procedure.
  • Verify the variable has not gone out of scope due to a GO batch separator placed between the DECLARE statement and the XQuery call.
  • If the value is meant to come from a table column, replace sql:variable() with sql:column() instead, as these two functions are not interchangeable.

Step 3: Rebuild the XQuery Expression

  • Isolate the XQuery expression into a simplified test script to confirm it runs independently of the larger stored procedure or application code.
  • Example corrected syntax:
  DECLARE @SearchID INT = 5;
  SELECT XmlColumn.value('(/Root/Item[@id=sql:variable("@SearchID")])[1]', 'INT')
  FROM dbo.YourTable;
  • Save and re-execute the corrected query to confirm the 9520 error no longer appears.

Step 4: Update Application or ORM-Generated Queries

  • If the query is generated by an ORM (Entity Framework, Dapper, etc.) or a reporting tool on Windows Server 2025/Windows 11, check the generated SQL via SQL Server Profiler or Extended Events.
  • Patch the application’s parameterized XML query template to use the correct sql:variable() syntax rather than relying on auto-generated string concatenation.

Alternative or Verification Steps

  • Run the corrected script in SSMS and confirm it returns results without raising Error 9520; check sys.messages (SELECT * FROM sys.messages WHERE message_id = 9520) to confirm the error description matches your scenario.
  • If the issue persists, use sql:column() as an alternative when referencing table data instead of a session variable, since this is the most common root cause of misuse.

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

Troubleshooting Guide: SQL Server Error 9518 (XQuery Invalid Identifier)

Why This Error Happens

This error occurs when an XQuery expression references an element, attribute, or namespace name containing characters that violate SQL Server’s identifier naming rules, such as spaces, special symbols, or names beginning with a digit. It commonly arises when XML data imported from external sources (APIs, legacy systems, or malformed documents) contains tag names that do not conform to standard XML/SQL naming conventions. Additionally, this can surface after upgrading to SQL Server 2025 on Windows Server 2025 or Windows 11 if the XML schema collection was validated under a more permissive legacy parser and is now being strictly re-evaluated.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Node or Attribute

  • Run the failing query in isolation and capture the exact multi-part name referenced in the error message (e.g., %.*ls).
  • Use SELECT CAST(XmlColumn AS XML) on a sample row to manually inspect the raw XML structure for hyphens, spaces, or leading numerals in tag names.
  • Check the application or ETL source logs to confirm whether the XML payload format changed recently.

Step 2: Sanitize the XML Input Before Querying

  • Pre-process incoming XML using REPLACE() or a staging transformation step to strip or rename invalid characters (e.g., replace spaces with underscores).
  • If using OPENXML or .nodes(), ensure namespace prefixes are properly declared using WITH XMLNAMESPACES to avoid ambiguous parsing.
  • Validate the XML Schema Collection (XSD) bound to the column, if applicable, via:
  SELECT name, xml_collection_id FROM sys.xml_schema_collections;

Step 3: Correct the XQuery Syntax

  • Rewrite the query to wrap suspicious node names in square brackets if they are reserved words or contain special characters (e.g., /root/*:[node-name]).
  • Avoid dynamic string concatenation when building XQuery paths, as this is a common source of malformed multi-part names.
  • Test the corrected query on SQL Server Management Studio (SSMS) 2025 connected to the instance to confirm the parser no longer throws Error 9518.

Step 4: Apply Cumulative Updates and Restart Services

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as XQuery parser edge-case bugs are periodically patched.
  • Navigate to SQL Server Configuration Manager on Windows Server 2025 / Windows 11 and restart the SQL Server (MSSQLSERVER) service after applying updates.
  • Clear the plan cache to ensure no stale execution plans reference the old invalid schema: DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Verify the fix by re-running the original query against a full production-like dataset; confirm Error 9518 no longer appears in SQL Server Logs or Windows Event Viewer (Event ID 9518).
  • As an alternative, if the source system cannot be modified, create a view that casts the XML to NVARCHAR(MAX), performs string replacement on invalid characters, and casts back to XML before applying XQuery methods.

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

Troubleshooting Guide: SQL Server Error 9516 — “XQuery: The name or one of the parts of a multi-part name… is empty”

Why This Error Happens

This error occurs when an XQuery or XML DML statement (such as .query(), .value(), .nodes(), or .modify()) is executed against an xml data type column with a malformed or incomplete XPath expression, typically containing an empty node name (e.g., // followed immediately by another / or a missing namespace prefix resolution). It frequently arises after a schema change, a bad dynamic SQL concatenation that builds XPath strings, or a copy-pasted query where a namespace alias was dropped. In rarer cases, this surfaces in SQL Server 2025 when XML indexes become out of sync with underlying XML schema collections after an in-place upgrade from an older instance.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and XPath Expression

  • Use SQL Server Profiler or Extended Events (sqlserver.error_reported filtered on Error Number = 9516) to capture the exact T-SQL batch triggering the fault.
  • Check the application or stored procedure code for any .query('...'), .value('...'), .exist('...'), or .modify('...') calls.
  • Pay close attention to dynamically built XPath strings where a variable concatenation may have produced // or /[] with no node name.

Step 2: Correct the Malformed XPath/XQuery Syntax

  • Open the stored procedure or query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Validate that every path step has a non-empty node name, for example change:
    SELECT XmlCol.value('(/Root//Child)[1]', 'varchar(50)')
    to a fully qualified, non-empty path such as:
    SELECT XmlCol.value('(/Root/Parent/Child)[1]', 'varchar(50)')
  • If namespaces are involved, ensure WITH XMLNAMESPACES is declared before the query and that every prefix used in the XPath matches a registered namespace:
    WITH XMLNAMESPACES ('http://example.com/ns' AS ns) SELECT XmlCol.value('(/ns:Root/ns:Child)[1]', 'varchar(50)') FROM dbo.YourTable;

Step 3: Rebuild or Validate XML Indexes and Schema Collections

  • Navigate to Object Explorer > Databases > [YourDB] > Tables > [YourTable] > Indexes in SSMS and locate any Primary/Secondary XML Indexes on the affected column.
  • Run the following to rebuild XML indexes if corruption or desynchronization is suspected after upgrade:
    ALTER INDEX ALL ON dbo.YourTable REBUILD;
  • Confirm the XML Schema Collection (if used) is still valid:
    SELECT name, xml_schema_namespace FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';

Step 4: Patch and Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11 and confirm the SQL Server (MSSQLSERVER) service is running the latest Cumulative Update for SQL Server 2025.
  • Download and apply the latest CU from the Microsoft Update Catalog if the build number is outdated, as early 2025 builds had a known XQuery parser edge case with empty namespace prefixes.
  • Restart the service: net stop MSSQLSERVER && net start MSSQLSERVER

Alternative or Verification Steps

  • Re-run the original query or application transaction that threw Error 9516 and confirm it completes without exception; check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for recurrence.
  • As a quick alternative, wrap suspect dynamic XPath generation in a validation function that checks for consecutive slashes (//) or empty brackets ([]) before execution, rejecting the query early with a custom error instead of letting it reach the XML engine.

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

Troubleshooting Guide: SQL Server Error 9517 (XQuery Identifier Length Exceeded)

Why This Error Happens

This error occurs when an XQuery expression within a SQL Server xml data type method (such as .query(), .value(), or .nodes()) references an element, attribute, or namespace prefix name that exceeds the maximum allowed identifier length of 128 characters. It is typically triggered by dynamically generated XQuery strings, malformed XML schema collections, or overly verbose namespace URIs being used as part of a multi-part XPath expression. Additionally, corrupted or improperly migrated XML Schema Collections from older SQL Server versions can introduce bloated internal names that violate this constraint when queried in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement throwing Error 9517 using SQL Server Profiler or Extended Events (sqlserver.error_reported filtered to Error Number 9517).
  • Check the application or ORM layer (e.g., Entity Framework, SSIS packages) for dynamically concatenated XQuery paths that may be appending excessive text.
  • Review the full error message text, which will specify the truncated identifier (%.*ls) causing the violation.

Step 2: Shorten the Identifier or Namespace Alias

  • Open the query in SSMS (SQL Server Management Studio 21, compatible with SQL Server 2025) and locate the XPath segment exceeding 128 characters.
  • Replace long namespace URIs with short aliases using WITH XMLNAMESPACES, for example:
  WITH XMLNAMESPACES ('http://very-long-namespace-uri.com/schema' AS ns)
  SELECT XmlColumn.value('(/ns:Root/ns:Element)[1]', 'varchar(100)')
  FROM YourTable;
  • Ensure no single node name, attribute name, or combined multi-part path exceeds the 128-character SQL identifier limit.

Step 3: Validate and Repair XML Schema Collections

  • Run the following to inspect registered schema collections for abnormally long type or element names:
  SELECT name, xml_schema_namespace, xml_schema_namespace_id 
  FROM sys.xml_schema_collections;
  • If a schema collection was migrated from an older SQL Server instance (2016/2019) and contains malformed names, drop and re-import a cleaned version:
  DROP XML SCHEMA COLLECTION YourSchemaCollection;
  • Re-import the corrected .xsd file ensuring all xs:element and xs:complexType names stay within the 128-character limit.

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • Navigate to Windows Update or the Microsoft Update Catalog on your Windows Server 2025 / Windows 11 host and check for the latest SQL Server 2025 Cumulative Update (CU).
  • Install via: Setup.exe /Action=Patch /IAcceptSQLServerLicenseTerms /Quiet from an elevated Command Prompt if deploying silently across servers.
  • This resolves known XQuery parser edge cases related to multi-part name validation introduced in early 2025 builds.

Alternative or Verification Steps

  • Re-run the original query after shortening the identifiers; confirm Error 9517 no longer appears in sys.dm_exec_requests or the SQL Server Error Log (EXEC sp_readerrorlog).
  • As an alternative, cast the XML column to a shorter intermediate variable and apply the XQuery method in two steps to isolate and simplify the identifier parsing logic.

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

Troubleshooting Guide: SQL Server Error 9515 — “An XML Schema Has Been Altered or Dropped”

Why This Error Happens

This error typically occurs when a SQL Server session attempts to validate or bind XML data against an XML schema collection that has been concurrently modified, dropped, or is in an inconsistent state within the same transaction. It can also arise from metadata corruption in system catalog views (sys.xml_schema_collections) or from conflicting DDL operations (ALTER/DROP) running against the schema collection while other sessions are actively using it. In some cases, this is triggered by improper transaction isolation levels combined with concurrent schema modification during XML validation operations.

Step-by-Step Resolution Guide

Step 1: Identify the Affected XML Schema Collection

  • Run the following query to locate schema collections and their current state:
  SELECT * FROM sys.xml_schema_collections;
  • Check SQL Server Error Log (via SSMS > Management > SQL Server Logs, or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for the exact object and session ID referenced alongside Error 9515.
  • Note the database name and schema collection name from the error context.

Step 2: Check for Concurrent DDL Operations and Locking Conflicts

  • Query active sessions to identify concurrent ALTER/DROP operations:
  SELECT session_id, status, command, blocking_session_id 
  FROM sys.dm_exec_requests 
  WHERE command LIKE '%XML SCHEMA%';
  • Kill or isolate any session that is modifying the schema collection concurrently using KILL <session_id> if safe to do so.
  • Ensure no other application or scheduled job (check Windows Task Scheduler and SQL Agent Jobs in SSMS) is modifying the schema collection during peak usage hours.

Step 3: Rebuild or Recreate the XML Schema Collection

  • Script out the existing schema collection definition before making changes:
  SELECT xml_schema_namespace('dbo', 'YourSchemaCollectionName');
  • Drop and recreate the collection cleanly to clear any corrupted internal state:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  GO
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'<schema XML here>';
  • Restart the SQL Server service via services.msc or PowerShell:
  Restart-Service -Name MSSQLSERVER -Force

Step 4: Run Database Consistency Checks

  • Execute DBCC CHECKDB against the affected database to rule out underlying corruption:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review output for any catalog-level errors tied to system metadata tables.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 9515 to confirm it now binds to the XML schema without interruption.
  • If the error persists, restore the affected database from a known-good backup taken prior to the schema modification, then reapply only validated schema changes in a single isolated transaction.

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

Troubleshooting Guide: SQL Server Error 9513

Why This Error Happens

Error 9513 occurs when a session attempts to invoke an XML data type method (such as .query(), .value(), .nodes(), or .exist()) without the required session-level SET options enabled. SQL Server mandates specific ANSI and quoting behaviors—namely ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER, and NUMERIC_ROUNDABORT—to guarantee deterministic results when processing XML. This typically happens because the connecting client driver, application connection string, or stored procedure context did not explicitly set these options before the XML method call was executed.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Missing SET Options

  • Reproduce the error in SQL Server Management Studio (SSMS) or Azure Data Studio and copy the full error text.
  • Note the specific option names listed in the message (e.g., ANSI_NULLS, QUOTED_IDENTIFIER), as this varies by query.
  • Check which object (stored procedure, function, or ad-hoc batch) triggered the XML method call.

Step 2: Explicitly Set Required Session Options in the Script

  • At the top of the stored procedure, script, or batch, add the following before any XML method calls:
  SET ANSI_NULLS ON;
  SET ANSI_PADDING ON;
  SET ANSI_WARNINGS ON;
  SET ARITHABORT ON;
  SET CONCAT_NULL_YIELDS_NULL ON;
  SET QUOTED_IDENTIFIER ON;
  SET NUMERIC_ROUNDABORT OFF;
  • If this is inside a stored procedure, these SET statements must appear before the CREATE PROCEDURE statement is compiled (i.e., set them, then re-create the procedure) since QUOTED_IDENTIFIER is baked in at creation time.

Step 3: Fix Connection-Level Defaults in the Application or Driver

  • For ODBC/OLE DB connections, verify that QUOTED_IDENTIFIER and ANSI_NULLS are not being overridden to OFF by a legacy connection string parameter.
  • In Windows Server 2025 / Windows 11 environments using the ODBC Data Source Administrator (odbcad32.exe), open the relevant DSN and confirm “Use ANSI Quoted Identifiers” and “Use ANSI Null, Paddings and Warnings” checkboxes are enabled under the advanced configuration tab.
  • For .NET/ADO.NET apps, ensure the connection string does not disable these via Set Quoted Identifier=false or similar legacy flags.

Step 4: Rebuild Affected Stored Procedures and Indexes

  • If the procedure was originally created with QUOTED_IDENTIFIER OFF, drop and recreate it after setting QUOTED_IDENTIFIER ON in the session.
  • Rebuild any XML indexes on the affected tables to ensure consistency:
  ALTER INDEX ALL ON YourTableName REBUILD;

Step 5: Restart the Service and Re-Test

  • Restart the SQL Server 2025 service via SQL Server Configuration Manager to clear any cached execution plans tied to incorrect SET option contexts.
  • Re-run the original query or application transaction that triggered Error 9513.

Alternative or Verification Steps

  • Verify the fix by running DBCC USEROPTIONS; in the same session right before the XML method call to confirm all seven required options show their correct ON/OFF state.
  • If the error persists in a specific stored procedure, use sp_helptext 'YourProcedureName' to inspect the compiled definition and confirm no legacy SET QUOTED_IDENTIFIER OFF statement is embedded within it.

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

Troubleshooting Guide: Error 9514 – XML Data Type Not Supported in Distributed Queries

Why This Error Happens

This error occurs because SQL Server’s distributed query engine (via linked servers or OPENQUERY/OPENROWSET) cannot process tables containing XML columns when accessed remotely, as the XML data type cannot be marshaled across OLE DB providers in a distributed query context. This is a fundamental engine limitation rather than a configuration defect, meaning no permission change or service restart will resolve it directly. The error typically surfaces when a query references a remote table or view that includes one or more XML-typed columns, either directly in the SELECT list or implicitly through a SELECT * statement.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Table and Column

  • Run the failing query and note the exact table name returned in the error message (the %.*ls placeholder will show the remote object name).
  • Connect directly to the remote SQL Server 2025 instance using SSMS and run sp_help 'SchemaName.TableName' to confirm which column(s) use the xml data type.
  • Check both base tables and any views involved, since views built on XML columns will also trigger this error.

Step 2: Rewrite the Query to Exclude or Cast XML Columns

  • Avoid SELECT * against the remote object; explicitly list only the non-XML columns you need.
  • If the XML data is required, cast it to NVARCHAR(MAX) on the remote side before retrieval, for example:
  SELECT ID, CAST(XmlColumn AS NVARCHAR(MAX)) AS XmlAsText
  FROM OPENQUERY(LinkedServerName, 'SELECT ID, XmlColumn FROM dbo.YourTable')
  • Ensure the CAST happens inside the OPENQUERY string (executed on the remote server) rather than after the data crosses the linked server boundary, since casting after the fact still triggers the error.

Step 3: Use OPENQUERY Instead of Four-Part Naming

  • Replace any four-part linked server references (LinkedServer.Database.Schema.Table) with OPENQUERY() syntax, since four-part names force SQL Server to pull the full row definition, including unsupported XML columns, before filtering.
  • Confirm the linked server provider (e.g., MSOLEDBSQL for SQL Server 2025) is up to date in SQL Server Configuration Manager, as outdated providers can compound type-marshaling issues.
  • Test the rewritten query in SSMS Query Editor to confirm it no longer calls the full table definition.

Step 4: Create a View on the Remote Server to Pre-Filter XML Columns

  • On the remote SQL Server 2025 instance, create a view that excludes or casts the XML column(s):
  CREATE VIEW dbo.vw_SafeForLinkedQuery AS
  SELECT ID, OtherColumn, CAST(XmlColumn AS NVARCHAR(MAX)) AS XmlAsText
  FROM dbo.YourTable;
  • Point your distributed query at vw_SafeForLinkedQuery instead of the base table, since this keeps the XML type confined to the remote server’s local execution context.

Alternative or Verification Steps

  • Verify the fix: Re-run the original distributed query (now modified) in SSMS on Windows Server 2025 / Windows 11 and confirm Error 9514 no longer appears, and that the NVARCHAR(MAX) column returns the expected XML content as text.
  • Alternative approach: If query rewriting isn’t feasible, use SSIS or a linked server with OPENROWSET(BULK...) to stage the data into a local temp table first, performing the XML-to-text conversion during the extract-transform step rather than inline in a distributed query.

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

Troubleshooting Guide: SQL Server Error 9512 — “Xml data type is not supported as a parameter to remote calls”

Why This Error Happens

This error occurs because SQL Server does not permit the xml data type to be passed as a parameter in remote procedure calls (RPC) between linked servers. When a client or application driver (such as OLE DB or ODBC) attempts to execute a remote stored procedure using RPC-style execution with an XML parameter, SQL Server rejects the call since RPC serialization does not natively support the XML schema format across server boundaries. This is typically triggered by application code, linked server queries, or drivers configured to use RPC execution instead of standard T-SQL batch execution.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Remote Call

  • Check the application or job that triggered the error, often found in SQL Server Error Logs or Event Viewer under Windows Logs > Application.
  • Look for the specific linked server query or stored procedure call that includes an XML parameter.
  • Run the following to review recent linked server activity:
  SELECT * FROM sys.servers WHERE is_linked = 1;

Step 2: Disable RPC Execution Style for the Linked Server

  • Open SQL Server Management Studio (SSMS) and navigate to Server Objects > Linked Servers.
  • Right-click the problematic linked server, select Properties > Server Options.
  • Set RPC and RPC Out options to False to force the connection to use standard SQL batch execution instead of RPC.
  • Alternatively, run this script:
  EXEC sp_serveroption 'YourLinkedServerName', 'rpc', 'false';
  EXEC sp_serveroption 'YourLinkedServerName', 'rpc out', 'false';

Step 3: Convert XML Parameters to NVARCHAR(MAX) Before Transmission

  • Modify the stored procedure or application code to cast the XML parameter to NVARCHAR(MAX) prior to sending it to the remote server.
  • Example conversion:
  DECLARE @xmlAsString NVARCHAR(MAX) = CAST(@xmlParam AS NVARCHAR(MAX));
  EXEC RemoteServer.DatabaseName.dbo.RemoteProcedure @xmlAsString;
  • On the receiving end, cast the string back to XML using CAST(@param AS XML) if XML processing is required.

Step 4: Update Linked Server Provider and Driver Configuration

  • Ensure the OLE DB provider (e.g., MSOLEDBSQL) is updated to the latest version compatible with SQL Server 2025 on Windows Server 2025 / Windows 11.
  • Navigate to Control Panel > Programs > Programs and Features to verify the installed provider version.
  • Reconfigure the linked server connection string to explicitly disable RPC-style execution if the provider defaults to it.

Alternative or Verification Steps

  • Verify the fix by re-running the original query or stored procedure call that previously failed; confirm no Error 9512 appears in the SQL Server Error Log.
  • As an alternative, encapsulate the remote call inside a local stored procedure that accepts NVARCHAR(MAX), performs the XML-to-string conversion internally, and then forwards the sanitized parameter to the linked server, avoiding native XML transmission entirely.

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

Troubleshooting Guide: Error 9509 – XMLUNNEST Method Requires Typed XML Column with Single Global Element

Why This Error Happens

This error occurs because the XMLUNNEST() method in SQL Server 2025 requires the target XML column to be strongly typed against an XML schema collection (XSCD) that defines exactly one global element. If the column is untyped, or if the associated schema collection contains zero or multiple global elements, SQL Server cannot deterministically shred the XML into a rowset. This is typically a schema design issue rather than a permissions or networking problem, often introduced after migrating legacy untyped XML columns to the new XMLUNNEST-compatible syntax in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the XML Column’s Typing Status

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the following query to inspect the column definition:
SELECT c.name AS ColumnName, t.name AS DataType, c.xml_collection_id
FROM sys.columns c
JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE t.name = 'xml' AND c.object_id = OBJECT_ID('YourTableName');
  • If xml_collection_id is 0 or NULL, the column is untyped and must be bound to a schema collection.

Step 2: Inspect the XML Schema Collection for Multiple Global Elements

  • Run this query to count global elements in the bound schema collection:
SELECT xsc.name, COUNT(*) AS GlobalElementCount
FROM sys.xml_schema_collections xsc
JOIN sys.xml_schema_components xc ON xsc.xml_collection_id = xc.xml_collection_id
WHERE xc.component_type = 1 -- Element declarations
GROUP BY xsc.name;
  • If the count is greater than 1, XMLUNNEST will fail because it cannot determine which root element to unnest.

Step 3: Recreate the Schema Collection with a Single Root Element

  • Export the existing schema using sp_help_xml_schema_collection 'YourSchemaCollectionName'.
  • Edit the XSD definition in a text editor (e.g., Visual Studio Code) to consolidate multiple global elements into one wrapper element.
  • Drop and recreate the collection:
DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
GO
CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS N'<xsd:schema>...single root element...</xsd:schema>';

Step 4: Re-type the Target Column

  • Alter the table to bind the column to the corrected, single-element schema collection:
ALTER TABLE YourTableName
ALTER COLUMN YourXmlColumn XML(DOCUMENT YourSchemaCollectionName);
  • Note: Use DOCUMENT (not CONTENT) since XMLUNNEST requires a single top-level element per document.

Step 5: Restart the Query and Validate Syntax

  • Re-run the original XMLUNNEST() query against the now-typed column.
  • Ensure your FROM clause syntax matches the new SQL Server 2025 requirement:
SELECT * FROM YourTableName
CROSS APPLY XMLUNNEST(YourXmlColumn) AS Unnested;

Alternative or Verification Steps

  • Verify the fix: Run SELECT xml_collection_id FROM sys.columns WHERE name = 'YourXmlColumn' — a non-zero value confirms proper typing, then re-execute the XMLUNNEST query to confirm Error 9509 no longer appears.
  • Alternative workaround: If schema redesign isn’t feasible immediately, use the legacy nodes() method with CROSS APPLY on the untyped XML column as a temporary substitute until the schema collection can be corrected.

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

Troubleshooting Guide: Error 9510 – XMLNODEREFS Cannot Use References Exposed by Views

Why This Error Happens

This error occurs because SQL Server’s XML node reference comparison methods (sys.fn_xe_... internals aside—specifically the nodes() and node-identity comparison functionality) require a direct binding to a base table’s XML schema collection, and this binding cannot be resolved when the XML column is accessed indirectly through a view. SQL Server 2025 has not implemented support for tracking node reference lineage across the view’s query plan, so the underlying node pointers become “unexposed” once abstracted by a CREATE VIEW definition. This is a documented engine limitation rather than a configuration error, meaning no amount of permission or index tuning will resolve it—the query itself must be rewritten to reference the base table directly.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement throwing Error 9510 using SQL Server Profiler or Extended Events (xml_deprecated_feature or errorlog session).
  • Check the query plan (Ctrl+L in SSMS) to confirm sql:column() or node-identity comparisons (e.g., nodes1.col.exist('...') compared against nodes2.col) are being executed against a view object rather than a table.
  • Run the following to confirm the object type:
  SELECT type_desc FROM sys.objects WHERE name = 'YourViewName';

Step 2: Rewrite the Query to Bypass the View

  • Modify the query to reference the base table(s) directly instead of the view that exposes the XML column.
  • If the view performs joins or filters, replicate that logic inline using a CTE (Common Table Expression) or derived subquery instead of a persisted view:
  WITH BaseData AS (
      SELECT XmlColumn FROM dbo.ActualBaseTable WHERE <filter_conditions>
  )
  SELECT T.c.query('.') 
  FROM BaseData CROSS APPLY XmlColumn.nodes('/root/node') AS T(c);
  • Ensure any XML_SCHEMA_COLLECTION binding is referenced on the base table column, not an aliased column in the view.

Step 3: Update Application/ORM Layer Dependencies

  • Locate any Entity Framework, Dapper, or stored procedure calls pointing to the view (check sys.sql_expression_dependencies).
  • Update connection strings or data access layers to point to the new base-table query or a Table-Valued Function (TVF) wrapper instead of the restricted view.
  • Example TVF workaround:
  CREATE FUNCTION dbo.fn_GetNodeRefs()
  RETURNS TABLE
  AS
  RETURN (SELECT XmlColumn FROM dbo.ActualBaseTable);

Step 4: Rebuild and Validate Schema Collections

  • If the XML schema collection was altered recently, verify it is still valid and attached correctly to the base table column.
  • Run DBCC CHECKCONSTRAINTS and sp_help 'dbo.ActualBaseTable' to confirm the XML column retains its (XML_SCHEMA_COLLECTION) binding post-migration.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator) if schema metadata appears stale.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query against the base table (not the view) and confirm Error 9510 no longer appears in the SSMS results pane or Windows Event Viewer (Application Log, Source: MSSQLSERVER).
  • Alternative Workaround: If refactoring the view is not feasible, materialize the XML data into a temporary table (SELECT XmlColumn INTO #TempXml FROM YourView) before performing node-reference operations, as temporary tables support full node identity resolution.

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

Troubleshooting Guide: SQL Server Error 9508 – XMLDT Method Reference Parameter Mismatch

Why This Error Happens

This error occurs when an application or stored procedure passes a node reference (obtained via the nodes() method or a variable holding an XML node pointer) that was generated from one XML instance to a method call being executed against a different, unrelated XML instance. This typically happens due to improper variable reuse in T-SQL scripts, where a developer caches a node pointer and then reassigns the underlying xml typed variable without refreshing the reference. It can also surface after application-level connection pooling issues on Windows Server 2025, where stale session variables from a previous XML parsing operation bleed into a new batch execution.

Step-by-Step Resolution Guide

Step 1: Audit the T-SQL Script for Variable Reuse

  • Locate the specific stored procedure or query referenced in the SQL Server error log that triggered Error 9508.
  • Check for instances where an xml variable is declared once, queried using .nodes(), and then overwritten later in the same batch without re-querying the new instance.
  • Ensure that every call to .query(), .value(), or .modify() uses a reference variable (e.g., T.c.query('.')) that was generated in the same CROSS APPLY or OUTER APPLY statement as the current row context.

Step 2: Isolate and Rebuild the XML Instance Logic

  • Rewrite the logic to avoid reusing a single sql:variable() or node reference across multiple distinct XML column instances.
  • If using a loop (e.g., WHILE loop) to process multiple XML documents, ensure the reference variable is reset to NULL at the start of every iteration:
  SET @xmlNodeRef = NULL;
  SET @xmlDoc = (SELECT XmlColumn FROM YourTable WHERE ID = @CurrentID);
  • Avoid passing node pointers as parameters into user-defined functions (UDFs) if the UDF might execute against a different table row’s XML data.

Step 3: Update SQL Server 2025 and Verify Compatibility Level

  • Navigate to Microsoft Update Catalog or use SQL Server Setup to confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as this resolves specific parser bugs related to XQuery execution plans.
  • Check the database compatibility level via SQL Server Management Studio (SSMS):
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is set to an older version (e.g., 120 or 130), update it to 170 (SQL Server 2025) to ensure the XML engine handles reference pointers using the newest internal memory management logic:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 4: Clear the Execution Plan Cache

  • Sometimes a corrupted or stale execution plan retains an old reference to the XML schema collection, causing this mismatch even after code fixes.
  • Flush the specific plan from memory using the plan handle, or clear the entire cache for the database (use with caution in production):
  DBCC FREEPROCCACHE;
  • Re-run the specific query or application transaction to force SQL Server to generate a new, clean execution plan.

Alternative or Verification Steps

  • Verification: Run the specific failing query in isolation within SSMS using SET STATISTICS XML ON to visually inspect which XML instance is being passed at each step of the execution plan.
  • Alternative Fix: If the error persists in a complex application (e.g., .NET Core app running on Windows 11), update the System.Data.SqlClient or Microsoft.Data.SqlClient NuGet package to the latest version, as older client-side XML serializers are known to mismanage node pointers when sending data to SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 9506 – XMLDT Method Invocation Error

Why This Error Happens

Error 9506 occurs when a Transact-SQL query attempts to invoke an XML data type method (such as .value(), .query(), .nodes(), .exist(), or .modify()) on a column or variable that is not explicitly typed as xml. This commonly happens when a column was implicitly cast as varchar, nvarchar, or text during a SELECT statement, or when a stored procedure parameter was declared with the wrong data type. It can also surface after a schema change or migration where an XML column was inadvertently converted to a string type, causing the SQL Server 2025 parser to reject the method call at compile time.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column or Variable

  • Review the query text referenced in the error message to locate the exact column or variable name invoking the XMLDT method.
  • Run sp_help 'YourTableName' or query INFORMATION_SCHEMA.COLUMNS to confirm the actual data type of the column in question.
  • Check if the method is being called on a derived column (e.g., from a CAST, CONVERT, or a joined subquery) rather than the base table column.

Step 2: Correct the Data Type Declaration

  • If the column is a variable, ensure it is declared as DECLARE @XmlVar XML rather than VARCHAR(MAX) or NVARCHAR(MAX).
  • If the column is a table column, verify its definition using sp_columns YourTableName and, if necessary, alter the table using:
  ALTER TABLE YourTableName ALTER COLUMN YourColumn XML;
  • If the value is being passed from an application layer (via ODBC/OLEDB on Windows Server 2025), confirm the client-side parameter type matches SqlDbType.Xml and is not being serialized as a string.

Step 3: Explicitly Cast the Value Before Method Invocation

  • If altering the schema is not feasible, wrap the column in an explicit CAST or CONVERT to the xml type before calling the method:
  SELECT CAST(YourColumn AS XML).value('(/Root/Node)[1]', 'VARCHAR(50)')
  FROM YourTableName;
  • Ensure the underlying string data is well-formed XML; malformed XML will throw a separate parsing error (Error 9400-series) even after casting.

Step 4: Validate Stored Procedures and Functions

  • Search any stored procedures, views, or functions that reference this column for implicit type coercion in JOIN or UNION clauses, as mismatched types in a UNION can silently convert xml to nvarchar.
  • Recompile the affected object using EXEC sp_recompile 'YourProcedureName'; after making type corrections.

Alternative or Verification Steps

  • Verify the fix by re-running the original query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance; the query should execute without Error 9506 and return the expected XML node data.
  • As an alternative, if frequent type mismatches occur due to external application inserts, consider adding a CHECK constraint or a computed column that enforces explicit XML casting at the schema level to prevent future implicit conversions.

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

Troubleshooting Guide: Error 9507 in Microsoft SQL Server 2025

Why This Error Happens

Error 9507 occurs when a query attempts to invoke an XML data type method (such as .value(), .query(), or .nodes()) on a column that resides on a remote server through a linked server connection. SQL Server’s query optimizer cannot push the execution of XML methods to the remote server, nor can it pull the raw XML data locally to process it, because doing so would require shredding large object (LOB) data across the network in a way the engine does not support for distributed queries. This is a query design limitation rather than a configuration or permissions error, and it typically surfaces when joining or filtering against linked server tables containing XML-typed columns.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Linked Server Reference

  • Review the query execution plan or error message to locate the specific linked server and remote table containing the XML column.
  • Check sys.servers on the local instance to confirm the linked server configuration: SELECT name, product, provider FROM sys.servers WHERE is_linked = 1;
  • Note the exact XML method (.value(), .exist(), .nodes(), etc.) being called in the SELECT, WHERE, or JOIN clause.

Step 2: Rewrite the Query to Pull Raw XML Locally First

  • Use OPENQUERY to retrieve the raw XML column from the remote server without applying any XML methods remotely.
  • Example: SELECT * INTO #TempXML FROM OPENQUERY(LinkedServerName, 'SELECT ID, XmlColumn FROM RemoteTable');
  • Apply the XML data type methods (.value(), .query()) against the local temporary table #TempXML instead of the remote reference.
  • Drop and recreate the temp table in a stored procedure wrapper if this query runs on a schedule, ensuring tempdb has sufficient space.

Step 3: Convert the Linked Server Query to Use a Staging Table

  • For recurring reports or ETL jobs, create a persistent staging table in a local database rather than relying on live linked server calls.
  • Use SQL Server Agent or an SSIS package to copy the remote XML column into the staging table on a schedule, for example: INSERT INTO LocalStaging.dbo.XmlCache SELECT ID, XmlColumn FROM OPENQUERY(LinkedServerName, 'SELECT ID, XmlColumn FROM RemoteTable');
  • Point all downstream queries using XML methods to this local staging table instead of the live linked server path.

Step 4: Validate Linked Server Provider Settings

  • Open SQL Server Management Studio (SSMS), navigate to Server Objects > Linked Servers > [Your Linked Server] > Properties.
  • Confirm “Collation Compatible” and “RPC Out” options are enabled under the Server Options tab, as misconfigured provider options can compound XML handling issues in distributed queries.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if provider option changes do not take effect immediately.

Alternative or Verification Steps

  • Run the rewritten query against the local temp table or staging table and confirm no Error 9507 is raised, then check the actual execution plan in SSMS to verify no remote XML method calls remain.
  • If rewriting is not feasible, consider using sp_executesql with a four-part name query against a linked server that fully materializes the XML column into a local variable before any method invocation.

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

Troubleshooting Guide: SQL Server Error 9503 — XQuery Statement Processing Error

Why This Error Happens

Error 9503 occurs when SQL Server’s XQuery engine encounters malformed, invalid, or improperly structured XML data while executing a method such as .query(), .value(), .exist(), or .nodes() on an xml data type column. This typically stems from invalid XML syntax (unclosed tags, bad namespace declarations), an incompatible or malformed XPath/XQuery expression being passed into the method, or data corruption in the stored XML instance. In some cases, it is also triggered by schema collection validation conflicts when the XML column is bound to an XML Schema Collection that no longer matches the data.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Query and Preceding Error Messages

  • Check SQL Server Management Studio (SSMS) “Messages” tab for the full error chain — Error 9503 is a wrapper error, and the real cause is listed immediately above it (e.g., Error 9311, 9312, or 2282).
  • Run the query in isolation to capture the specific XML column and XQuery method call (.query(), .value(), .nodes()) causing the failure.
  • Use SELECT @@VERSION; to confirm you’re on a supported SQL Server 2025 build, as older CUs sometimes mishandle newer XQuery functions.

Step 2: Validate the XML Data for Corruption or Malformed Content

  • Run a basic validation check: SELECT TRY_CAST(XmlColumn AS XML) FROM YourTable WHERE ID = <RowID>; — a NULL result confirms malformed XML.
  • Inspect for common issues: unescaped special characters (&, <, >), missing closing tags, or incorrect namespace prefixes (xmlns:).
  • If using an XML Schema Collection, verify compatibility: SELECT xml_collection_id, name FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; and cross-check it against the actual XML structure.

Step 3: Correct the XQuery/XPath Expression Syntax

  • Review the XQuery expression passed into the method for syntax errors, such as incorrect axis steps (//, ./), unbound namespace prefixes, or invalid predicate logic ([1] vs [position()=1]).
  • Explicitly declare namespaces at the top of your query if the XML uses them:
  WITH XMLNAMESPACES ('http://example.com/ns' AS ns)
  SELECT XmlColumn.value('(/ns:Root/ns:Element)[1]', 'nvarchar(100)')
  FROM YourTable;
  • Simplify the expression temporarily (e.g., test with .exist('/Root')) to isolate whether the failure is in the XML structure or the query logic itself.

Step 4: Rebuild or Re-Import Corrupted XML Data

  • If a specific row’s XML is found to be corrupted and unrecoverable, re-import the source data from the original system of record.
  • For bulk corruption, use OPENROWSET(BULK...) with SQLXML or re-run the ETL/ingestion job that populated the XML column after fixing the upstream data format.
  • Apply the latest Cumulative Update (CU) for SQL Server 2025 via Windows Update or the Microsoft Download Center, as XQuery engine bug fixes are frequently included.

Alternative or Verification Steps

  • Verify the fix: Re-run the original failing query — if it returns results (or NULL for safely handled bad rows) without throwing Error 9503, the XML and XQuery expression are now compatible.
  • Alternative workaround: If the issue is isolated to a few rows, wrap the method call in TRY_CAST/TRY_CONVERT logic within a CASE statement, or use OPENXML as a fallback on legacy data until the underlying XML source is cleaned.

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

Troubleshooting Guide: SQL Server Error 9504 – XQuery Statement Processing Errors

Why This Error Happens

Error 9504 occurs when SQL Server’s XQuery engine encounters malformed, invalid, or unexpected XML content while executing an XML data type method such as .query(), .value(), .nodes(), .exist(), or .modify(). This is typically caused by XML data that doesn’t conform to the expected schema (if a schema collection is bound), invalid XPath/XQuery syntax in the method call, or data type casting issues within the XQuery expression (e.g., attempting to cast non-numeric text to a numeric type). It can also surface due to corrupted XML data in the column itself, often introduced by faulty application-layer serialization or an interrupted write operation.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XQuery Statement

  • Capture the exact query via SQL Server Profiler or Extended Events (sqlserver.error_reported filtered on Error = 9504).
  • Review the %.*ls placeholder in the error message—it names the specific XML method (e.g., value(), query()) that failed.
  • Run the query in isolation against a single row to narrow down which XML column/value is triggering the fault.

Step 2: Validate the XML Data and Schema Binding

  • Check if the column has a bound XML Schema Collection:
  SELECT xml_schema_namespace(sys.schemas.name, object_name)
  FROM sys.xml_schema_collections;
  • Attempt to cast the raw value manually to confirm validity:
  SELECT TRY_CAST(YourXmlColumn AS XML) FROM YourTable WHERE PrimaryKey = @id;
  • If TRY_CAST returns NULL, the underlying XML is malformed and needs correction or re-import from source.

Step 3: Correct the XQuery Syntax and Type Casting

  • Verify namespace prefixes are declared correctly using WITH XMLNAMESPACES before the query.
  • Ensure .value() calls explicitly cast to a compatible SQL type:
  SELECT XmlCol.value('(/Root/Item/@id)[1]', 'INT')
  FROM YourTable;
  • Replace ambiguous XPath expressions with fully qualified, indexed paths (e.g., (/Root/Item)[1] instead of /Root/Item) to avoid sequence errors.

Step 4: Rebuild XML Indexes and Update Statistics

  • If the column uses a Primary XML Index, corruption or stale structures can cause processing errors:
  ALTER INDEX ALL ON YourTable REBUILD;
  • Run DBCC CHECKTABLE('YourTable') to confirm there is no underlying page-level corruption affecting the XML BLOB storage.

Step 5: Patch and Restart the SQL Server Service

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as XQuery parser bugs are occasionally patched.
  • Apply the update, then restart the service via PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Verify the fix: Re-run the original query from Step 1 against the full dataset; monitor Extended Events to confirm Error 9504 no longer fires during the batch load or application transaction.
  • Alternative solution: If the XML schema collection is overly strict and causing legitimate data to fail, temporarily unbind it (ALTER TABLE ... ALTER COLUMN XmlCol XML(DOCUMENT NULL)) to isolate whether the schema itself—rather than the query syntax—is the root cause.

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

Troubleshooting Guide: SQL Server Error 9502

Why This Error Happens

Error 9502 occurs when a string literal passed as an argument to a system method (such as JSON_MODIFY, JSON_QUERY, or similar T-SQL functions) exceeds the maximum byte length permitted for that parameter. This is typically triggered by applications dynamically constructing large JSON paths, XML strings, or query fragments that inadvertently surpass internal buffer limits. It can also surface after data migrations or ETL processes that concatenate unusually large text values without validating length constraints beforehand.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Method

  • Review the SQL Server error log or Extended Events session to capture the exact query text triggering Error 9502.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full error context, including the method name (%.*ls) and argument index (%d).
  • Run DBCC INPUTBUFFER(<session_id>) to retrieve the exact statement from an active session if the error is reproducible in real time.

Step 2: Measure and Trim the String Literal Length

  • Use DATALENGTH() in a test query to confirm the byte size of the problematic string argument (e.g., SELECT DATALENGTH(@your_string);).
  • Compare this against the documented limit for the method in question (commonly 4,000 bytes for NVARCHAR expressions in JSON/XML functions).
  • Refactor the application or stored procedure code to split large strings into smaller segments or use NVARCHAR(MAX) variables with staged processing instead of inline literals.

Step 3: Update Application Logic or Stored Procedures

  • Open SQL Server Management Studio (SSMS) and locate the stored procedure or function referenced in the error.
  • Replace direct inline string concatenation with parameterized variables declared as NVARCHAR(MAX) to avoid literal size restrictions.
  • Deploy the corrected procedure using ALTER PROCEDURE and recompile with sp_recompile '<procedure_name>'.

Step 4: Apply Latest Cumulative Update

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 to confirm your current SQL Server 2025 build number.
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as known string-handling bugs in JSON/XML methods are periodically patched.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after installation completes.

Alternative or Verification Steps

  • Re-run the original query or application transaction that previously failed; confirm no Error 9502 appears in the SQL Server error log (EXEC sp_readerrorlog).
  • As an alternative, if refactoring isn’t immediately feasible, temporarily cast the string argument using CAST(@value AS NVARCHAR(MAX)) combined with chunked processing logic to bypass the byte-length ceiling.

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

Troubleshooting Guide: SQL Server Error 9501 – XQuery sql:variable() Resolution Failure

Why This Error Happens

This error occurs when an XQuery expression inside an XML data type method (such as .query(), .value(), or .nodes()) references a variable via sql:variable() that either does not exist in the current scope, is misspelled, or is declared with a non-scalar or incompatible data type. SQL Server’s XQuery parser requires the referenced variable to be a simple, scalar T-SQL variable (e.g., INT, NVARCHAR, VARCHAR) declared earlier in the batch or stored procedure with a matching DECLARE statement. This commonly surfaces after migrating scripts to SQL Server 2025, where stricter parsing of XML schema collections and XQuery scoping rules can expose previously tolerated syntax issues.

Step-by-Step Resolution Guide

Step 1: Verify the Variable Declaration and Scope

  • Open the stored procedure or script in SQL Server Management Studio (SSMS) and locate the exact line referenced in the error message.
  • Confirm the variable is declared using a standard DECLARE @VariableName DATATYPE statement before the sql:variable('@VariableName') call.
  • Check that the variable name inside the quotes exactly matches the declared name, including case sensitivity and the @ prefix.

Step 2: Confirm the Variable Is a Scalar Type

  • Ensure the variable is not a table variable, XML type, or cursor — only scalar types like INT, BIGINT, NVARCHAR(n), VARCHAR(n), DATETIME, etc., are supported.
  • If the variable currently holds a complex or XML type, convert the required value into a scalar variable first:
  DECLARE @ScalarVar NVARCHAR(100);
  SET @ScalarVar = (SELECT TOP 1 SomeColumn FROM dbo.SomeTable);
  • Use this @ScalarVar inside the sql:variable() call instead of the original complex type.

Step 3: Check for Scope Mismatches in Nested Procedures or Functions

  • If the XQuery expression lives inside a user-defined function or nested stored procedure, confirm the variable was passed in as a parameter rather than relying on an outer batch’s variable.
  • Re-declare or pass the variable explicitly:
  CREATE FUNCTION dbo.GetXmlValue(@InputVar INT)
  RETURNS NVARCHAR(100)
  AS
  BEGIN
      DECLARE @Result NVARCHAR(100);
      SELECT @Result = XmlColumn.value('sql:variable("@InputVar")', 'INT')
      FROM dbo.XmlTable;
      RETURN @Result;
  END;

Step 4: Rebuild and Validate the XML Schema Collection (If Applicable)

  • If the XML column is bound to an XML Schema Collection, validate it hasn’t become corrupted or mismatched after an upgrade to SQL Server 2025.
  • Run:
  SELECT xml_collection_id, name FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • If inconsistencies are found, drop and recreate the schema collection, then re-link it to the affected table/column.

Step 5: Apply Latest Cumulative Update for SQL Server 2025

  • Navigate to Microsoft Update Catalog or use SQL Server Setup to check for the latest Cumulative Update (CU) for SQL Server 2025, as early XQuery parser bugs have been patched in subsequent builds.
  • Install via:
  C:\SQLServer2025\Setup.exe /Action=Patch /AllInstances /IAcceptSQLServerLicenseTerms /Quiet
  • Restart the SQL Server service via SQL Server Configuration Manager after patching.

Alternative or Verification Steps

  • Run the corrected query in isolation using sqlcmd or SSMS to confirm Error 9501 no longer appears, and validate the expected XML node/value is returned correctly.
  • As an alternative, bypass sql:variable() entirely by concatenating the value directly into a dynamic SQL string (with proper parameterization to avoid injection), then execute via sp_executesql.

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

Troubleshooting Guide: SQL Server Error 9480 – XML Parsing Error

Why This Error Happens

Error 9480 occurs when SQL Server’s native XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within a column, variable, or imported file. This is frequently caused by corrupted XML source files, mismatched or unclosed tags, invalid character encoding (such as BOM markers or non-UTF-8 characters), or truncated data during an import/export operation (e.g., via OPENROWSET, FOR XML, or a bulk insert). In some cases, this also surfaces when an application writes to an XML-typed column using a string that violates XML 1.0 well-formedness rules.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Review the full error message to note the exact line number and column referenced (e.g., “XML parsing: line 42, unexpected end of input”).
  • If the XML originates from a file, open it in a text editor (VS Code or Notepad++) with “Show All Characters” enabled to detect hidden control characters or BOM issues.
  • If the XML is generated by an application, capture the raw payload using SQL Server Profiler or Extended Events (sqlserver.error_reported) to inspect the exact string being inserted.

Step 2: Validate and Repair the XML Structure

  • Run the problematic string through an XML validator (e.g., xmllint --noout file.xml on Windows via WSL, or an online XSD validator) to confirm well-formedness.
  • Check for common issues: unescaped special characters (&, <, >), unclosed tags, or mismatched namespaces.
  • If importing from a file, re-save it with UTF-8 encoding without BOM using a text editor, since SQL Server’s XML parser is strict about encoding declarations matching the actual byte stream.
  • For programmatic inserts, ensure the application layer uses proper XML serialization libraries (e.g., System.Xml.Linq in .NET) rather than manual string concatenation.

Step 3: Correct the Import/Query Logic and Re-Test

  • If using OPENROWSET(BULK...) to load XML, confirm the file path is correct and accessible from the SQL Server service account:
  SELECT * FROM OPENROWSET(BULK 'C:\Data\sample.xml', SINGLE_BLOB) AS x;
  • If the error stems from a stored procedure or CAST/CONVERT to XML type, isolate the exact variable value using PRINT or SELECT before the conversion step to confirm it is clean.
  • Re-run the insert, import, or query after remediation to confirm the parser no longer throws Error 9480.

Alternative or Verification Steps

  • Run SELECT CAST(@xmlVariable AS XML); in a test query window — if it executes without error, the XML is now well-formed and the fix is confirmed.
  • As an alternative, if the source system cannot guarantee clean XML, wrap the insert logic in a TRY...CATCH block and log failed records to a staging table for manual review instead of allowing the entire batch to fail.

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

Troubleshooting Guide: SQL Server Error 9500 — Invalid Data Type in VALUE Method

Why This Error Happens

Error 9500 occurs when a computed column or query uses the VALUE() method against a CLR user-defined type (UDT) or XML schema collection with a data type that isn’t supported for serialization, such as nvarchar(max), varchar(max), or an incompatible precision/scale definition. This typically happens after a schema migration, a CLR assembly update, or when a UDT method signature was altered without updating dependent objects. Corrupted or mismatched metadata between the CLR assembly and the SQL Server catalog can also trigger this error, especially after an in-place upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object and Data Type

  • Run SELECT * FROM sys.assembly_types WHERE is_user_defined = 1; to list all CLR UDTs in the affected database.
  • Cross-reference the error message’s reported data type against the method signatures in sys.assembly_methods.
  • Use sp_helptext or OBJECT_DEFINITION() on the computed column or view calling the VALUE() method to pinpoint the exact query.

Step 2: Validate and Correct the Data Type Definition

  • Open the CLR UDT source project (typically a .sln file previously deployed via CREATE ASSEMBLY).
  • Ensure the VALUE() method does not return unsupported types like nvarchar(max), varchar(max), text, or image — replace these with fixed-length equivalents such as nvarchar(4000).
  • Rebuild the assembly DLL and redeploy it using:
  ALTER ASSEMBLY YourAssemblyName FROM 'C:\Deployments\YourAssembly.dll';
  • If using Windows Server 2025, confirm the DLL is unblocked (right-click → Properties → Unblock) before deployment, as enhanced file reputation checks can interfere with assembly loading.

Step 3: Refresh Dependent Computed Columns and Views

  • Drop and recreate any computed columns referencing the corrected VALUE() method:
  ALTER TABLE YourTable DROP COLUMN ComputedCol;
  ALTER TABLE YourTable ADD ComputedCol AS dbo.YourUDT::VALUE(CorrectedParams);
  • Run sp_refreshsqlmodule on any views or stored procedures that reference the UDT to clear cached invalid metadata.

Step 4: Clear Metadata Cache and Restart the Service

  • Execute DBCC FREEPROCCACHE; and DBCC FREESYSTEMCACHE('ALL'); to purge stale plan and metadata caches.
  • Restart the SQL Server service via services.msc or:
  net stop MSSQLSERVER && net start MSSQLSERVER

Alternative or Verification Steps

  • Verify the fix by re-running the original failing query or SELECT statement against the computed column — it should return data without raising Error 9500.
  • If the error persists, drop and fully re-register the CLR assembly using DROP ASSEMBLY followed by a fresh CREATE ASSEMBLY, ensuring CLR STRICT SECURITY settings in SQL Server 2025 permit the assembly’s trust level.

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

Troubleshooting Guide: SQL Server Error 9466 — XML Parsing Error

Why This Error Happens

Error 9466 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line and character position within a column, variable, or input file. This is typically caused by truncated XML documents (often from interrupted data transfers or improperly concatenated strings exceeding NVARCHAR(MAX) limits), mismatched or unescaped special characters (such as &, <, or > not converted to entities), or an incorrect encoding declaration (e.g., a file declared as UTF-16 but saved as UTF-8). In rare cases, this can also stem from a corrupted source file or a network interruption during a bulk insert operation that cut off the XML payload mid-stream.

Step-by-Step Resolution Guide

Step 1: Isolate and Inspect the Malformed XML Source

  • Locate the exact line number referenced in the error (e.g., “line 42”) within the source file or variable.
  • If importing via OPENROWSET(BULK...), open the source .xml file in a text editor (like VS Code or Notepad++) and navigate to that specific line.
  • Check for unescaped ampersands (&), unclosed tags, or abrupt file termination (missing closing root tag).

Step 2: Validate Character Encoding and Special Characters

  • Verify the file’s encoding matches the declared XML header (e.g., <?xml version="1.0" encoding="UTF-8"?>).
  • In Windows 11/Server 2025, use PowerShell to check the Byte Order Mark (BOM):
 Get-Content -Path "C:\Data\source.xml" -TotalCount 1 -Encoding Byte
  • Replace any raw special characters with proper XML entities (e.g., replace & with &amp;).

Step 3: Verify Data Type Length and Truncation

  • If generating XML via a FOR XML query or concatenating strings in T-SQL, ensure the receiving variable is cast as NVARCHAR(MAX) rather than a fixed length (like NVARCHAR(4000)), which can silently truncate the XML and break the closing tags.
  • Run SELECT DATALENGTH(YourXmlColumn) to confirm the data wasn’t cut off during a VARCHAR conversion.

Step 4: Test the Repaired XML Snippet in Isolation

  • Copy just the problematic line segment into a new query window.
  • Attempt to cast it directly:
 DECLARE @test XML;
 SET @test = '<root><node>Test &amp; Data</node></root>';
 SELECT @test;
  • If this isolated test succeeds, the issue is confirmed to be specific to the original file’s content, not a SQL Server configuration setting.

Alternative or Verification Steps

  • Verification: Re-run the original query or import job; if successful, query the resulting XML column using .nodes() or .value() to ensure the structure is fully queryable and not just superficially valid.
  • Alternative: If the source file is generated by a third-party application and cannot be easily edited, use an XSD schema validation step via sp_xml_schema or a pre-processing PowerShell script to sanitize/validate the file before it reaches the INSERT or OPENROWSET statement.

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

Troubleshooting Guide: SQL Server Error 9467 — XML Parsing Error

Why This Error Happens

Error 9467 occurs when SQL Server’s XML parser encounters malformed, incomplete, or invalid XML data at a specific line number during a parsing operation (such as OPENXML, FOR XML, or XML data type validation). This typically results from corrupted XML input, improperly escaped special characters, encoding mismatches (UTF-8 vs UTF-16), or truncated XML data caused by application-layer transmission issues or buffer size limitations. It can also surface when a schema collection validation fails due to mismatched namespaces or malformed tags within the XML document being processed.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Capture the full error message, including the line number referenced (e.g., “XML parsing: line 12, unclosed tag”).
  • Run the query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML ON disabled temporarily to isolate the raw XML payload.
  • Export the problematic XML variable or column value using SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to inspect it manually in a text editor like VS Code.

Step 2: Validate and Repair the XML Structure

  • Check for unclosed tags, mismatched opening/closing elements, or invalid characters (such as unescaped &, <, or >) near the reported line.
  • Confirm the XML declaration header matches the actual encoding: <?xml version="1.0" encoding="UTF-8"?>.
  • If the XML originates from an external application or ETL pipeline, verify the source system isn’t truncating data due to a VARCHAR length limit instead of NVARCHAR(MAX).

Step 3: Adjust SQL Server Configuration and Data Types

  • Ensure the column or variable receiving the XML is defined as the native XML data type, not VARCHAR, to allow SQL Server to validate it properly on insert.
  • If using a schema collection, verify it is up to date: run SELECT * FROM sys.xml_schema_collections; to confirm the correct namespace is registered.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator) if the issue persists after a configuration change.

Step 4: Re-test the Query or Stored Procedure

  • Re-run the original query or stored procedure call that triggered Error 9467.
  • Use PRINT statements or SELECT @XMLVariable checkpoints before the parsing operation to confirm the XML is well-formed prior to execution.

Alternative or Verification Steps

  • Verify the fix by running SELECT 1 FROM sys.dm_exec_requests WHERE command LIKE '%XML%' to confirm no XML-related session is hung, then re-execute the original failing query to confirm it completes without Error 9467.
  • If the error persists, bypass native XML validation temporarily by casting the data as NVARCHAR(MAX) for inspection only (not production use), and use an external XML validator tool (like xmllint on Windows Subsystem for Linux) to pinpoint the malformed section before reinserting into SQL Server.

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

Troubleshooting Guide: SQL Server Error 9465 – XML Parsing Error

Why This Error Happens

Error 9465 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within an XML document, column, or variable. This typically results from corrupted data during insertion, truncated XML strings due to column size limitations, invalid character encoding (such as mismatched UTF-8/UTF-16 byte order marks), or unescaped special characters (like &, <, >) embedded directly in the XML content. In SQL Server 2025 running on Windows Server 2025 or Windows 11, this can also surface after in-place upgrades if legacy XML schema collections were not validated against the newer XML parsing engine.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Run the failing query in SSMS and note the exact line number referenced in the error message.
  • Use SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to extract the raw string and visually inspect the specified line for broken tags or invalid characters.
  • Check for unescaped ampersands (&), unclosed tags, or missing closing </tag> elements near the reported line.

Step 2: Validate Character Encoding and Special Characters

  • Confirm the source application is sending XML encoded in UTF-8 or UTF-16 and not mixing encodings mid-string.
  • Replace raw special characters with their XML entity equivalents (e.g., &amp; for &, &lt; for <, &gt; for >) before insertion.
  • If data originates from an external file, open it in a hex editor to check for a stray Byte Order Mark (BOM) at the beginning of the file, which often causes line 1 parsing failures.

Step 3: Check Column Size and Data Truncation

  • Verify the source column or variable (e.g., NVARCHAR(MAX) vs NVARCHAR(4000)) is large enough to hold the entire XML payload without truncation.
  • Run sp_help 'YourTableName' to confirm the data type definitions match the expected XML payload size.
  • If truncation is suspected, increase the column size to NVARCHAR(MAX) or XML data type to prevent mid-tag cutoffs.

Step 4: Rebuild or Refresh XML Schema Collections (If Applicable)

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Types > XML Schema Collections in SSMS.
  • Drop and re-import the XML Schema Collection using CREATE XML SCHEMA COLLECTION if the collection was migrated from an older SQL Server version and is incompatible with the 2025 parsing engine.
  • Restart the SQL Server service via services.msc on Windows Server 2025 after the schema refresh to clear any cached parsing contexts.

Alternative or Verification Steps

  • To verify the fix, re-run the original INSERT or SELECT statement; if successful, validate the data integrity by querying the XML column with .exist() or .value() XQuery methods to ensure the structure is now parsable.
  • As an alternative, if the error persists on bulk imports, use OPENROWSET(BULK...) with the SINGLE_CLOB option instead of SINGLE_BLOB to force text-based encoding detection, which often resolves hidden encoding mismatches.

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

SQL Server Error 9464: XML Parsing Failure Troubleshooting Guide

Why This Error Happens

Error 9464 occurs when the SQL Server XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during a parsing operation (such as OPENXML, .nodes(), or XML data type validation against a schema collection). This is typically caused by invalid characters, mismatched tags, truncated data from an application feed, or an encoding mismatch (e.g., UTF-16 data being interpreted as UTF-8). It can also surface when a stored procedure passes XML parameters that exceed expected formatting rules defined in an associated XML Schema Collection (XSD).

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML

  • Capture the full error message, noting the specific line number referenced (e.g., “XML parsing: line 12, unclosed tag”).
  • Use SQL Server Management Studio (SSMS) 21 on Windows 11 to re-run the failing query in isolation to capture the raw XML variable being passed.
  • Run SELECT CAST(@YourXMLVariable AS NVARCHAR(MAX)); to visually inspect the string for truncation or invalid characters.

Step 2: Validate Encoding and Special Characters

  • Check if the source data contains unescaped special characters (e.g., &, <, >) that need to be converted to XML entities (&amp;, &lt;, &gt;).
  • If the data originates from an external file, verify the encoding in Windows Server 2025 using Notepad++ or PowerShell: Get-Content -Path "C:\Data\file.xml" -Encoding UTF8.
  • Ensure the <?xml version="1.0" encoding="UTF-8"?> declaration matches the actual byte-order-mark (BOM) of the file.

Step 3: Repair or Reconfigure the XML Schema Collection

  • Navigate to the Database in SSMS: Databases > [YourDB] > Programmability > Types > XML Schema Collections.
  • If the schema collection is outdated, drop and recreate it to match the current XML structure using DROP XML SCHEMA COLLECTION followed by CREATE XML SCHEMA COLLECTION.
  • Verify the application layer (e.g., .NET or Java service) is serializing the object into XML correctly before sending it to the stored procedure.

Step 4: Increase Timeout or Buffer Limits (If applicable)

  • If the error happens on massive XML blobs, check the network packet size in SQL Server Configuration Manager.
  • Right-click SQL Server Services > Protocols for MSSQLSERVER and ensure no size restrictions are causing the XML string to be cut off mid-transfer, which often triggers a “line X” parsing error because the tag closes prematurely.

Alternative or Verification Steps

  • Verification: Run the query again using SELECT 1 FROM sys.messages WHERE message_id = 9464; to confirm the error definition, then re-execute the original transaction to ensure it processes without throwing the exception.
  • Alternative: If the XML is generated by a third-party tool, bypass the strict XML parser by importing the data as NVARCHAR(MAX) first and using TRY_CAST to convert it to XML, allowing you to filter out NULL (invalid) results without crashing the batch job.

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

Troubleshooting Guide: SQL Server Error 9462 — XML Parsing Failure

Why This Error Happens

Error 9462 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within the document. This typically results from truncated XML strings (often due to exceeding variable length limits), invalid character encoding (such as non-UTF-8 characters in a UTF-8 context), mismatched or unclosed tags, or corruption introduced during data transfer, import, or application-layer serialization. It can also surface when XML schema collections reject content that violates defined structural rules.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the specific line number reported in the error message (e.g., “XML parsing: line 12, unclosed tag”).
  • Run the failing query in SQL Server Management Studio (SSMS) and isolate the exact XML variable or column causing the failure.
  • Use SELECT LEN(@YourXmlVariable) to confirm the string isn’t being truncated before parsing.

Step 2: Validate and Repair the XML Structure

  • Extract the raw XML payload and validate it using an external tool (e.g., Visual Studio XML Editor, Notepad++ with XML plugin, or an online XML validator) to pinpoint syntax errors like unclosed tags or invalid nesting.
  • Check for unescaped special characters (&, <, >) that must be replaced with entities (&amp;, &lt;, &gt;).
  • If the XML originates from an application, verify the source code isn’t concatenating strings manually without proper XML serialization (use FOR XML clauses or .NET XmlWriter instead).

Step 3: Check Data Type Length and Encoding Settings

  • Confirm the variable or column is declared as XML or a sufficiently large NVARCHAR(MAX) rather than a length-limited type like VARCHAR(8000), which can silently truncate data and break XML structure.
  • Verify the encoding declaration in the XML prolog (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the source file or stream.
  • On Windows Server 2025/Windows 11, check Regional Settings (Control Panel > Region > Administrative > Change system locale) to ensure no unexpected Unicode conversions are occurring during data import.

Step 4: Re-import or Re-generate the XML Source

  • If the XML comes from a flat file or external system, re-export or re-generate it to rule out corruption during file transfer (FTP in ASCII mode instead of binary is a common culprit).
  • Re-run the import process using OPENROWSET(BULK...) with the SINGLE_CLOB option to load the file as raw text first, then attempt CAST(... AS XML) separately for better error isolation.

Alternative or Verification Steps

  • After applying fixes, re-run the original query or stored procedure and confirm it executes without throwing Error 9462; also validate the output using SELECT CAST(@YourXmlVariable AS XML) to ensure SQL Server accepts it as well-formed.
  • As a fallback, if the XML source cannot be modified, wrap the parsing logic in a TRY...CATCH block to log the raw offending string to a staging table for manual inspection without halting the entire batch process.

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

Troubleshooting Guide: SQL Server Error 9463 – XML Parsing Failure

Why This Error Happens

Error 9463 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within a column, variable, or stored procedure input. This is typically caused by corrupted XML data being inserted into an xml-typed column, mismatched or unclosed tags, invalid character encoding (such as non-UTF-8 byte sequences), or truncation of the XML string due to a datatype length mismatch (e.g., casting to varchar instead of nvarchar(max)). It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schema collections were not validated against the newer parser engine.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XML Data

  • Identify the exact line and column number referenced in the error message (e.g., “line 4, character 12”).
  • Run a validation query against the source table: SELECT TRY_CAST(XmlColumn AS XML) FROM YourTable WHERE TRY_CAST(XmlColumn AS XML) IS NULL AND XmlColumn IS NOT NULL;
  • Export the problematic row’s raw data to a text file to inspect for unclosed tags or invalid characters.

Step 2: Correct Data Type and Encoding Issues

  • Verify the source application is not casting XML data as varchar when it should be nvarchar(max), which causes silent truncation of Unicode characters.
  • Check connection string encoding settings in your application (ensure Collation and Charset match UTF-8/UTF-16 as required).
  • In SQL Server Management Studio (SSMS) 21, open Tools > Options > Query Execution and confirm “SET XML Datatype Compatibility” settings align with 2025 defaults.

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

  • If the error originates from a typed XML column bound to an XML Schema Collection, run: SELECT xsc.name, xs.definition FROM sys.xml_schema_collections xsc CROSS APPLY sys.xml_schema_namespaces xs WHERE xsc.xml_collection_id = xs.xml_collection_id;
  • Drop and recreate the schema collection using CREATE XML SCHEMA COLLECTION with a verified, well-formed .xsd file.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear cached execution plans referencing the old schema.

Step 4: Validate Application-Side XML Generation

  • On Windows Server 2025/Windows 11, check the Event Viewer (eventvwr.msc) under Applications and Services Logs > Microsoft > SQL Server for correlating client-side serialization errors.
  • Ensure any .NET application generating the XML uses XmlWriter with explicit encoding (Encoding.UTF8) rather than manual string concatenation.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 9463; confirm it completes without exception and returns expected row counts.
  • If the issue persists, use DBCC CHECKDB on the affected database to rule out underlying page-level corruption masquerading as an XML parsing failure.

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

Troubleshooting Guide: SQL Server Error 9461

Why This Error Happens

Error 9461 occurs when SQL Server’s XML parser encounters data that exceeds the maximum allowed size for an XML value during processing, typically because the XML instance surpasses internal node or character length limitations. This commonly happens when applications insert or manipulate XML data that was generated incorrectly, truncated during transmission, or corrupted due to encoding mismatches. It can also surface when the XML data type column receives malformed input from ETL processes, linked server queries, or legacy applications that do not properly validate XML structure before insertion.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source

  • Run a query against the table/column referenced in the error to locate the specific row causing the issue:
  SELECT [ID], DATALENGTH([XMLColumn]) AS XMLSize 
  FROM [YourTable] 
  WHERE DATALENGTH([XMLColumn]) > 2000000000;
  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for timestamp correlation with the failing transaction.
  • Review the application or ETL job that generated the XML payload to confirm whether truncation or duplication occurred upstream.

Step 2: Validate and Repair XML Structure

  • Use SELECT CAST([XMLColumn] AS NVARCHAR(MAX)) on the suspect row to visually inspect the XML for malformed tags or unexpected repetition.
  • If using SSIS or external import tools, verify the XML source file hasn’t been corrupted by checking file integrity (certutil -hashfile <path> SHA256 on Windows Server 2025).
  • Re-generate the XML payload from the source system if corruption is confirmed, ensuring UTF-8/UTF-16 encoding consistency.

Step 3: Adjust Application-Level XML Handling

  • Update application code (C#, Java, or PowerShell scripts) to validate XML size before sending it to SQL Server, using a pre-check against the 2GB XML data type limit.
  • If using OPENXML or .nodes() methods, ensure the query isn’t inadvertently creating a cartesian expansion of nodes, which can simulate oversized XML.
  • Restart the SQL Server service after configuration changes:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Apply Latest Cumulative Update

  • Navigate to Microsoft’s official download center and verify you are running the latest Cumulative Update (CU) for SQL Server 2025, as parser-related bugs are frequently patched.
  • Check current build version:
  SELECT @@VERSION;
  • Apply the update via SQL Server Installation Center on Windows Server 2025, selecting Maintenance > Edition Upgrade/Patch.

Alternative or Verification Steps

  • Re-run the original query or application transaction that triggered Error 9461 and confirm it completes without raising the exception in SQL Server Management Studio (SSMS).
  • If the error persists, isolate the XML payload in a sandbox database using DBCC CHECKDB to rule out underlying page-level corruption affecting the XML data type storage.

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

Why This Error Happens

Error 9459 occurs when SQL Server’s native XML parser encounters malformed or non-well-formed XML data during a query that uses OPENXML, FOR XML, or XML data type methods. This typically stems from invalid characters, unclosed tags, mismatched namespaces, or truncated XML strings being passed into the parser. In SQL Server 2025 running on Windows Server 2025/Windows 11, this can also be triggered by encoding mismatches (UTF-8 vs UTF-16) when XML data is imported from external files or APIs.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Position

  • Run the failing query in SQL Server Management Studio (SSMS) and capture the full error message, including the line number referenced in “XML parsing: line %d”.
  • Use SELECT CAST(@xmlVariable AS NVARCHAR(MAX)) to dump the raw XML content to text for manual inspection.
  • Cross-reference the line number against the dumped text to locate the malformed tag or character.

Step 2: Validate the XML Structure Externally

  • Copy the problematic XML content into a validator tool (e.g., Visual Studio’s XML Editor or an online XML validator) to pinpoint syntax errors such as unclosed elements or invalid entity references.
  • Check for unescaped special characters like &, <, or > that must be encoded as &amp;, &lt;, or &gt;.
  • Verify the XML declaration (<?xml version="1.0" encoding="UTF-8"?>) matches the actual encoding of the source file.

Step 3: Correct Source Data or Import Process

  • If the XML originates from an external file, re-export it ensuring UTF-8 encoding without a BOM (Byte Order Mark), as BOM characters can cause parsing failures in SQL Server 2025.
  • Update the application or ETL process (SSIS package, PowerShell script, etc.) to sanitize XML output before insertion, using SELECT dbo.fn_EscapeXML(@rawInput) or similar custom sanitization functions.
  • If using OPENROWSET(BULK...) to load XML files, confirm the file path is accessible to the SQL Server service account under Windows Server 2025 security policies.

Step 4: Rebuild and Re-test the Query

  • Modify the XML column or variable with the corrected content and re-run the original FOR XML or OPENXML statement.
  • Check SQL Server error logs via EXEC sp_readerrorlog to confirm Error 9459 no longer appears after correction.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(@xmlVariable AS XML) — if no error is thrown, the document is now well-formed.
  • If the error persists intermittently, enable XML schema validation using WITH XMLSCHEMA and bind a known-good XSD schema to catch structural issues before they reach production queries.

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

Troubleshooting Guide: SQL Server Error 9460 — XML Parsing Error

Why This Error Happens

Error 9460 occurs when SQL Server’s native XML parser encounters malformed, incomplete, or invalid XML data that does not conform to well-formed XML syntax rules. This is typically caused by corrupted data during transmission, improperly escaped special characters (such as unescaped ampersands or angle brackets), or truncated XML strings due to column size limitations or application-layer encoding issues. It can also surface when a mismatch exists between the expected XML schema collection and the actual data being inserted or queried.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Run the failing query in SQL Server Management Studio (SSMS) and capture the full error message, noting the specific line number referenced.
  • Use SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to manually inspect the raw XML content near the reported line.
  • Check for unescaped characters like &, <, >, or improperly closed tags.

Step 2: Validate XML Against Schema and Encoding Standards

  • Confirm the XML data uses proper entity encoding (e.g., &amp; instead of &).
  • If using an XML Schema Collection, verify compatibility with SELECT * FROM sys.xml_schema_collections;.
  • Re-validate the source application (e.g., .NET, Java, or ETL tool) to ensure it is generating UTF-8 or UTF-16 compliant XML before insertion.

Step 3: Check for Data Truncation Issues

  • Inspect the source column or variable type; ensure NVARCHAR(MAX) or XML data types are used instead of restrictively sized VARCHAR(n) fields.
  • On Windows Server 2025/Windows 11, check the application’s connection string parameters for Packet Size limitations that might truncate large XML payloads mid-transmission.
  • Increase network packet size temporarily via sp_configure 'network packet size' if large XML documents are involved.

Step 4: Re-Import or Reconstruct the XML Document

  • If the XML originates from an external file, open it in a validator (like an XML editor or Visual Studio) to pinpoint syntax errors.
  • Correct the malformed node, re-save the file in UTF-8 encoding without BOM, and re-attempt the import.

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT, UPDATE, or SELECT statement that triggered Error 9460; a successful execution confirms the XML is now well-formed.
  • As an alternative, use TRY_CAST or TRY_CONVERT in a diagnostic query to isolate specific rows with invalid XML without halting the entire batch operation, allowing you to clean data in bulk before re-importing.

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

Why This Error Happens

Error 9458 occurs when SQL Server’s XML parser encounters malformed or incomplete XML data that violates well-formedness rules, such as unclosed tags, invalid characters, or mismatched namespaces. This typically happens during operations like OPENXML, CAST/CONVERT to XML type, or when importing XML files that were truncated during transfer or corrupted by an upstream application. It can also surface when encoding mismatches (UTF-8 vs UTF-16) cause the parser to misread byte order marks or special characters.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Structure

  • Open the XML file or string in a validator (Visual Studio, Notepad++ with XML plugin, or xmllint on Windows Server 2025 via WSL).
  • Check the exact line and character number referenced in the error message to locate the malformed tag or attribute.
  • Confirm all opening tags have matching closing tags and that special characters (&, <, >) are properly escaped as entities (&amp;, &lt;, &gt;).

Step 2: Check Encoding and BOM Issues

  • Verify the file encoding matches what SQL Server expects (UTF-8 without BOM is generally safest for OPENROWSON or BULK imports).
  • Re-save the file using a text editor set explicitly to “UTF-8” rather than “UTF-8 with BOM.”
  • If importing via OPENROWSET(BULK...), ensure the SINGLE_CLOB or SINGLE_BLOB option matches the actual file encoding.

Step 3: Correct the T-SQL Query Handling XML

  • Review any CAST(@variable AS XML) or CONVERT(XML, @data) statements for truncation, especially if the source column is VARCHAR(MAX) being implicitly converted from a shorter type.
  • Increase buffer/variable sizes where XML strings are being concatenated or passed as parameters, since silent truncation often causes broken closing tags.
  • Run the query in SQL Server Management Studio (SSMS) on Windows 11 or Windows Server 2025 with SET SHOWPLAN_XML disabled temporarily to isolate parser-only errors.

Step 4: Update SQL Server Cumulative Updates

  • Confirm SQL Server 2025 is patched to the latest Cumulative Update (CU) via SELECT @@VERSION;.
  • Download and apply the latest CU from the Microsoft Update Catalog if the build is outdated, as early XML parser builds had known edge-case bugs with nested namespaces.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after patching.

Alternative or Verification Steps

  • Re-run the original query or import job after fixing the XML; a successful execution with no Error 9458 confirms the structure is now well-formed.
  • As an alternative, use TRY_CAST instead of CAST to gracefully handle malformed XML by returning NULL instead of throwing a hard error, allowing you to log and isolate bad records without halting the entire batch process.

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

Troubleshooting Guide: SQL Server Error 9456 – XML Parsing Failure

Why This Error Happens

Error 9456 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line and column within a document being processed via XML data type methods, OPENXML, or FOR XML/sys.xml_readtext operations. This is typically caused by invalid characters (such as unescaped ampersands or illegal Unicode), a mismatched or missing closing tag, or truncated XML data resulting from a failed transfer, corrupted file import, or an application bug that generates non-compliant XML. In some cases, incorrect encoding declarations (e.g., UTF-16 data read as UTF-8) can also trigger this parsing failure.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source and Line of the XML Error

  • Open the full error message in SQL Server Management Studio (SSMS) or the SQL Server Error Log to note the exact line and column number referenced.
  • Run the query that triggered the error in isolation to pinpoint which XML column, variable, or parameter is responsible.
  • Use SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to export the raw XML content for manual inspection.

Step 2: Validate and Repair the XML Structure

  • Paste the extracted XML into a validator tool (such as Visual Studio’s XML Editor, Notepad++ with XML Tools plugin, or an online XML validator) to detect unclosed tags, invalid characters, or encoding mismatches.
  • Check for unescaped special characters like &, <, or > that must be replaced with &amp;, &lt;, or &gt; respectively.
  • If the XML originates from an external application or ETL process (e.g., SSIS package, API call), verify the source system is generating well-formed XML before insertion.

Step 3: Correct the Encoding and Re-Import the Data

  • Confirm the XML’s declared encoding (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file or stream.
  • If importing from a file using OPENROWSET(BULK...), explicitly specify SINGLE_CLOB for UTF-8 or ANSI data, or SINGLE_NCLOB for Unicode (UTF-16) data to avoid misinterpretation.
  • Re-run the import or insert statement after correcting the source file or application output.

Step 4: Patch and Restart SQL Server Services

  • Ensure SQL Server 2025 is updated to the latest Cumulative Update (CU) via Windows Update or the Microsoft Download Center, as parser edge-case bugs are occasionally addressed in patches.
  • On Windows Server 2025 / Windows 11, open Services.msc, locate “SQL Server (MSSQLSERVER)”, and restart the service after applying any updates.
  • Re-test the original query or import process to confirm the XML parses without triggering Error 9456.

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM sys.dm_exec_requests WHERE xml_column IS NOT NULL or re-executing the original stored procedure/query to confirm no XML parsing errors are raised.
  • As an alternative, if the XML source cannot be immediately corrected, wrap the parsing logic in a TRY...CATCH block to log and quarantine malformed records for manual review rather than halting the entire batch process.

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

Troubleshooting Guide: SQL Server Error 9457 – “XML Parsing: Line %d”

Why This Error Happens

Error 9457 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data during an INSERT, CAST, or CONVERT operation involving the XML data type. This is typically caused by a mismatched or missing closing tag, invalid character encoding (such as non-UTF-8 characters embedded in the stream), or truncated data resulting from a corrupted file transfer or an interrupted bulk insert operation. In some cases, this also surfaces when applications generate XML dynamically but fail to escape special characters like &, <, or > properly.

Step-by-Step Resolution Guide

Step 1: Isolate and Inspect the Offending XML Data

  • Identify the exact line number referenced in the error (%d) and locate the source file or variable being parsed.
  • Run the query in SSMS with SET SHOWPLAN_XML OFF to prevent execution plan interference while debugging.
  • Open the XML source in a validator (e.g., Visual Studio’s XML Editor or xmllint on Windows Server 2025 via WSL) to check for unclosed tags or invalid nesting.

Step 2: Validate Character Encoding

  • Confirm the XML declaration matches the actual file encoding (e.g., <?xml version="1.0" encoding="UTF-8"?> for UTF-8 files).
  • Check for a Byte Order Mark (BOM) mismatch—use PowerShell: Get-Content -Encoding Byte -TotalCount 3 .\file.xml to inspect the first bytes.
  • Re-save the file using UTF-8 without BOM if a mismatch is found, using Notepad++ or VS Code’s “Save with Encoding” option.

Step 3: Correct the SQL Insert/Import Logic

  • If using OPENROWSET(BULK...) or BULK INSERT, ensure the SINGLE_BLOB option is used correctly for binary-safe XML ingestion:
  INSERT INTO dbo.XmlStorage (XmlColumn)
  SELECT CAST(BulkColumn AS XML)
  FROM OPENROWSET(BULK 'C:\Data\import.xml', SINGLE_BLOB) AS x;
  • If the application generates XML strings manually, ensure special characters are escaped (e.g., replace & with &amp;) before insertion.

Step 4: Rebuild or Replace the Corrupted Source File

  • If the file was transferred over FTP or a network share, re-transfer it using Binary mode rather than ASCII mode to prevent line-ending corruption.
  • Regenerate the XML export from the source system if corruption persists after re-transfer.

Alternative or Verification Steps

  • Run SELECT CAST(@XmlVariable AS XML); in a test query window—if it returns successfully without Error 9457, the fix is confirmed.
  • If the issue persists only in SSMS but not via application code, check the Tools > Options > Query Results > XML display limit in SSMS, as truncated results can sometimes trigger a false-positive parsing error.

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

Troubleshooting Guide: SQL Server Error 9455 (XML Parsing Error)

Why This Error Happens

Error 9455 occurs when SQL Server’s internal XML parser encounters malformed, truncated, or invalid XML data during a parsing operation, such as a CONVERT, CAST, or OPENXML call. This typically stems from corrupted XML data stored in a column, improperly escaped special characters (like unencoded ampersands or angle brackets), or XML data that exceeds expected schema constraints. In some cases, the issue arises from a mismatch between the XML encoding declaration and the actual byte encoding of the data being passed to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Error

  • Note the specific line number (%d) referenced in the error message to pinpoint the malformed section.
  • Run the failing query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF to isolate the offending statement.
  • Extract the raw XML value using SELECT xml_column FROM your_table WHERE id = 'problem_row' and inspect it in a text editor for broken tags or encoding issues.

Step 2: Validate and Repair the XML Structure

  • Check for unescaped special characters (&, <, >) that need to be converted to &amp;, &lt;, &gt;.
  • Use SELECT CAST(xml_column AS NVARCHAR(MAX)) to convert the XML to plain text for manual inspection before re-casting.
  • If the data originates from an external application, verify the source system is generating well-formed XML before insertion.

Step 3: Update SQL Server 2025 and Verify XML Schema Collections

  • Navigate to SQL Server Configuration Manager on Windows Server 2025 / Windows 11 and confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as XML parser bugs are frequently patched.
  • Check Windows Update (Settings > Windows Update) to ensure the underlying .NET Framework components used by the XML parser are current.
  • If using XML Schema Collections, run SELECT * FROM sys.xml_schema_collections to confirm the schema hasn’t been dropped or corrupted.

Step 4: Re-import or Re-insert Clean Data

  • Delete or update the corrupted row using a verified, well-formed XML payload.
  • If the issue stems from a bulk import (e.g., via BULK INSERT or SSIS), inspect the source file encoding (should be UTF-8 or UTF-16 as expected by the destination column).
  • Re-run the import job and monitor the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for recurrence.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(xml_column AS XML) on the previously failing row; if no error is thrown, the data is now valid.
  • As an alternative, if the error persists on a specific schema-bound XML column, temporarily remove the XML schema collection binding using ALTER TABLE ... ALTER COLUMN xml_column XML(NULL) to isolate whether the schema itself is causing the rejection.

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

Troubleshooting Guide: SQL Server Error 9454 — “XML Parsing: Line %d”

Why This Error Happens

Error 9454 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or non-well-formed XML data during an insert, query, or conversion operation involving the xml data type. This is typically caused by corrupted source data, improperly escaped special characters (such as &, <, or >), truncated XML strings due to buffer limits, or encoding mismatches (e.g., UTF-8 vs. UTF-16) between the source file and the database collation settings. In some cases, this also surfaces when legacy applications pass malformed XML payloads to stored procedures expecting strict schema validation.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the specific line number (%d) referenced in the error message.
  • Run the failing query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF to isolate the exact statement.
  • Extract the raw XML payload using SELECT CAST(YourColumn AS NVARCHAR(MAX)) to visually inspect the string for broken tags or illegal characters.

Step 2: Validate and Sanitize the XML Input

  • Check for unescaped special characters (&, <, >) and replace them with proper XML entities (&amp;, &lt;, &gt;).
  • Use an external validator (like xmllint on Windows Server 2025 via WSL, or Notepad++ XML Tools plugin) to confirm the document is well-formed.
  • If the data originates from an external API or file import, verify the encoding matches UTF-8 and strip any Byte Order Mark (BOM) characters at the start of the file.

Step 3: Adjust SQL Server Connection and Data Type Settings

  • Verify the target column is correctly defined as XML type rather than NVARCHAR, which can cause implicit conversion errors.
  • Check that the client application’s connection string is not truncating the payload (common with MAX_TEXT_SIZE settings in ODBC/OLE DB drivers).
  • Update the SQL Server Native Client or ODBC Driver 18 for SQL Server 2025 to ensure compatibility with the updated XML parsing engine.

Step 4: Rebuild or Restore the Affected Object (If Corruption Persists)

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS to rule out underlying page-level corruption affecting the XML index.
  • If an XML index is corrupted, drop and recreate it using DROP INDEX followed by CREATE PRIMARY XML INDEX.

Alternative or Verification Steps

  • Verify the fix: Re-run the original INSERT/SELECT statement; the query should execute without throwing Error 9454, and SELECT ISJSON() or schema validation checks (if using XSD) should return valid results.
  • Alternative solution: If the issue persists due to a specific driver bug in Windows 11/Server 2025, temporarily store the data as NVARCHAR(MAX) and use TRY_CAST(... AS XML) to gracefully handle malformed rows without halting the entire batch transaction.

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

Troubleshooting Guide: SQL Server Error 9452 – “XML Parsing: Line %d”

Why This Error Happens

Error 9452 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data during an attempt to parse it into the xml data type. This is commonly caused by invalid characters (such as unescaped ampersands or angle brackets), mismatched or unclosed tags, incorrect namespace declarations, or truncated XML data resulting from network interruptions or file corruption during import. It can also surface when application code constructs XML strings dynamically without proper validation before sending them to SQL Server.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Causing the Failure

  • Review the full error message, which typically includes the line number and a more specific sub-error code (e.g., “Unexpected end of file has occurred,” “Tag does not match”).
  • Run the query in SQL Server Management Studio (SSMS) with SET FMTONLY OFF; to capture the raw output before conversion.
  • Use SELECT CAST(YourXmlColumn AS NVARCHAR(MAX)) to view the raw string and manually inspect the problematic line.

Step 2: Validate and Sanitize the XML Source

  • Check for unescaped special characters: &, <, >, ', and " must be represented as &amp;, &lt;, &gt;, &apos;, and &quot; respectively.
  • If the XML is generated by an external application, verify that the source system is using proper XML serialization libraries (e.g., System.Xml in .NET) rather than manual string concatenation.
  • For file-based imports, open the file in a text editor (like VS Code on Windows 11) with encoding detection enabled to confirm it is valid UTF-8 or UTF-16 without a corrupted Byte Order Mark (BOM).

Step 3: Check for Truncation in Data Transmission

  • Verify the column or variable receiving the XML data is of type XML or NVARCHAR(MAX) and not a smaller fixed-length type (e.g., NVARCHAR(4000)), which silently truncates data and breaks the closing tags.
  • If using BCP or BULK INSERT on Windows Server 2025, confirm the -C (code page) and -w (wide character) flags match the source file encoding.
  • Inspect network configurations if XML is streamed over a linked server or API; packet loss during large transfers can cut off closing tags.

Step 4: Rebuild the XML Schema Collection (If Applicable)

  • If you are using an XML Schema Collection (XSD) to validate the column, run sp_help on the schema name to ensure it hasn’t been corrupted.
  • Drop and recreate the schema collection using CREATE XML SCHEMA COLLECTION if the validation rules appear outdated or mismatched with the incoming data structure.

Alternative or Verification Steps

  • To verify the fix, re-run the original INSERT or CAST statement; a successful execution with no Error 9452 confirms the XML is now well-formed.
  • As an alternative, wrap the XML ingestion logic in a TRY_CAST or TRY_CONVERT function (SQL Server 2025 supports enhanced error handling for this) to gracefully handle future malformed data without halting the entire transaction.

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

Troubleshooting Guide: SQL Server Error 9453 – XML Parsing Error

Why This Error Happens

Error 9453 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during a parsing operation. This is typically caused by invalid characters (such as unescaped ampersands or angle brackets), mismatched or unclosed tags, an incorrect encoding declaration (e.g., UTF-16 data declared as UTF-8), or truncated XML data due to a failed transfer or storage column size limitation. In some cases, this also surfaces when importing XML files that were corrupted during disk write operations or interrupted network transfers on Windows Server 2025 environments.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Causing the Failure

  • Run the failing query or import job again and capture the full error message, noting the line number and character position referenced.
  • Open the source XML file in a text editor like Notepad++ or VS Code (avoid default Notepad, as it can mask encoding issues).
  • Navigate directly to the flagged line number to visually inspect for broken tags, stray symbols, or invalid characters.

Step 2: Validate and Correct the XML Structure

  • Use an XML validation tool (such as xmllint --noout yourfile.xml via Windows Subsystem for Linux, or an online XML validator) to confirm well-formed structure.
  • Check for unescaped special characters like &, <, or > that must be replaced with &amp;, &lt;, or &gt; respectively.
  • Verify the XML declaration header (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual file encoding saved on disk.

Step 3: Correct Encoding Mismatches in SQL Server

  • If importing via OPENROWSET(BULK...), ensure the SINGLE_CLOB or SINGLE_BLOB option matches the file’s actual encoding type.
  • For SINGLE_CLOB, the file must be ANSI/UTF-8 without a BOM mismatch; for UTF-16 files, use SINGLE_NCLOB instead.
  • Re-run the import statement in SQL Server Management Studio (SSMS) 21 after adjusting the clause.

Step 4: Check for Data Truncation in the Source Table or Variable

  • Verify that any XML or NVARCHAR(MAX) variables used to hold the data were not inadvertently cast to a smaller type (e.g., NVARCHAR(4000)) earlier in the script, which truncates and breaks the XML structure.
  • Review stored procedures or ETL packages (SSIS) for intermediate steps where XML data passes through fixed-length string variables.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original CAST(... AS XML) or import statement; a successful execution with no Error 9453 confirms the XML is now well-formed.
  • Alternative Solution: If the file originates from a third-party export tool, try regenerating the export file from the source system to rule out a one-time corruption event during the initial file write.

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

Troubleshooting Guide: SQL Server Error 9451 – “XML Parsing: Line %d”

Why This Error Happens

Error 9451 occurs when SQL Server 2025’s XML parser encounters malformed, incomplete, or improperly encoded XML data that violates well-formedness rules during an XML data type operation. This is commonly triggered by truncated data from an ETL process, invalid special characters that aren’t properly escaped, or a mismatch between the declared encoding and the actual byte content of the XML. It can also surface when application code inserts XML fragments that exceed buffer limits or get cut off mid-structure before reaching SQL Server.

Step-by-Step Resolution Guide

Step 1: Isolate and Inspect the Offending XML Data

  • Identify the exact line number referenced in the error message (%d) to narrow down the search.
  • Run a query to extract the raw XML string before casting it to the XML data type:
  SELECT RawXmlColumn FROM StagingTable WHERE ID = <problem_row_id>
  • Paste the extracted content into a validator (like Notepad++ with an XML plugin, or Visual Studio) to visually spot unclosed tags, mismatched brackets, or stray ampersands (&).

Step 2: Correct Encoding and Escaping Issues

  • Check for unescaped special characters (&, <, >) within text nodes; these must be converted to &amp;, &lt;, and &gt; respectively.
  • Verify the XML declaration header matches the actual encoding of the source file (e.g., <?xml version="1.0" encoding="UTF-8"?> should match the file’s actual byte-order mark).
  • If importing from a flat file on Windows Server 2025, use PowerShell to re-encode the source file to UTF-8 without BOM:
  Get-Content -Path "C:\Data\source.xml" -Encoding UTF8 | Set-Content -Path "C:\Data\source_fixed.xml" -Encoding UTF8

Step 3: Adjust Application or Import Buffer Limits

  • If using SSIS or a custom application via ADO.NET, check the connection string or Data Flow component for truncation limits on NVARCHAR(MAX) or XML stream buffers.
  • In SQL Server Management Studio (SSMS) 21, increase the “Maximum Characters Retrieved” limit under Tools > Options > Query Results > SQL Server > Results to Grid if you suspect the display—rather than the actual data—is truncating the view.
  • Re-run the insertion/parsing command using the corrected file or string to confirm the line-ending issue is resolved.

Step 4: Validate Against an XML Schema Collection (XSD)

  • If the table column is bound to an XML SCHEMA COLLECTION, verify the schema itself hasn’t been corrupted or updated to conflict with incoming data.
  • Temporarily cast the data to standard XML (without the schema constraint) to see if the error persists, isolating whether the issue is “well-formedness” or “schema validity.”

Alternative or Verification Steps

  • Verification: Execute SELECT CAST(YourColumn AS XML) on the fixed dataset; if the query returns the hierarchical XML result without a red error message, the parsing issue is resolved.
  • Alternative: If the source file continuously causes encoding issues, pipe the data through OPENROWSET(BULK...) with the SINGLE_CLOB option instead of SINGLE_BLOB, as this forces SQL Server to handle the data as character-based text, often bypassing byte-order corruption issues that trigger Error 9451.

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

Why This Error Happens

Error 9449 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line and position within a document. This is typically caused by invalid characters, mismatched tags, truncated data (often from network interruptions or buffer limits), or an incorrect character encoding declaration in the XML prolog. It can also surface when application code dynamically generates XML strings with unescaped special characters (such as &, <, or >).

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Column of the Error

  • Open the full error message in SQL Server Management Studio (SSMS) or the Windows Event Viewer (Event ID 9449) to capture the exact line/column number referenced.
  • Run the failing query manually in SSMS against a text editor copy of the XML to isolate the problematic segment.
  • Check if the XML source is coming from a file path, a BULK INSERT, or an application-generated string.

Step 2: Validate and Correct the XML Structure

  • Use a dedicated XML validator (or SELECT CAST(@xmlVar AS XML) in a test query) to confirm the document is well-formed.
  • Look for unescaped special characters; replace & with &amp;, < with &lt;, and > with &gt; where they appear as literal data rather than markup.
  • Verify the XML prolog encoding (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file or stream.

Step 3: Check for Truncation or Buffer Limits

  • If importing via OPENROWSET(BULK...) or a .NET/PowerShell script on Windows Server 2025, confirm the source file is not being cut off mid-transfer.
  • Inspect network share permissions and antivirus/EDR software (common on Windows Server 2025 hardened builds) that may be scanning and altering file streams mid-read.
  • Increase any relevant buffer or timeout settings in the client application (ODBC/OLE DB connection string) feeding the XML to SQL Server.

Step 4: Rebuild and Re-Test the XML Column or Variable

  • If the error originates from a corrupted value already stored in an XML-typed column, export the row, repair the XML externally, and re-import it using UPDATE with the cleaned value.
  • Confirm the column schema collection (if using XML(SCHEMA COLLECTION)) isn’t rejecting the data due to a stricter XSD definition — temporarily switch to untyped XML to isolate schema vs. syntax issues.

Alternative or Verification Steps

  • Run SELECT CAST('<test>sample</test>' AS XML); in SSMS to confirm the XML engine itself is functioning correctly, isolating whether the issue is data-specific or server-level.
  • If the error persists only through a specific application, bypass it by testing the same XML payload via sqlcmd or SSMS directly — if it succeeds, the root cause is in the application’s XML generation/encoding layer, not SQL Server itself.

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

Troubleshooting Guide: SQL Server Error 9450 — XML Parsing Error

Why This Error Happens

Error 9450 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within a column, variable, or document being processed. This is typically caused by corrupted XML data being inserted into an xml typed column, truncated data due to a failed transfer or import process, or a mismatch between the declared encoding and the actual byte content of the XML source. It can also surface when an application passes improperly escaped special characters (such as unescaped ampersands or angle brackets) into a query that casts or validates data as XML.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source of the XML Data

  • Locate the query, stored procedure, or ETL job referenced in the error message and note the exact line number provided in “XML parsing: line %d.”
  • Run SELECT [column_name] FROM [table] WHERE [primary_key] = [id] to extract the raw XML string causing the failure.
  • Use SELECT CAST([column_name] AS NVARCHAR(MAX)) to inspect the data as plain text rather than XML, since casting directly to XML will reproduce the error.

Step 2: Validate and Repair the XML Structure

  • Check for common structural issues: unclosed tags, mismatched opening/closing elements, or invalid nesting.
  • Verify that special characters like &, <, and > are properly escaped as &amp;, &lt;, and &gt; respectively.
  • On Windows Server 2025 / Windows 11, open the extracted XML in a validating editor (such as Visual Studio Code with an XML extension) to pinpoint the exact malformed line.
  • If the source is an external file, confirm the file encoding (UTF-8 vs. UTF-16) matches the <?xml version="1.0" encoding="..."?> declaration at the top of the document.

Step 3: Correct the Application or Import Logic

  • If data originates from an application, update the code to properly encode special characters before insertion (e.g., using SecurityElement.Escape() in .NET or equivalent XML-safe encoding functions).
  • For SSIS packages or BCP imports, re-check the data flow task’s XML source component settings and ensure no truncation is occurring mid-transfer.
  • Re-run the import or transaction after correcting the offending XML string to confirm the fix resolves the parsing failure.

Step 4: Rebuild or Re-Cast the Column Data (If Corruption Exists in Storage)

  • If the corrupted XML is already stored in a table, update the row manually using a corrected XML string via UPDATE [table] SET [column_name] = '<CorrectedXML/>' WHERE [primary_key] = [id].
  • Run DBCC CHECKTABLE('[table_name]') WITH NO_INFOMSGS to rule out broader physical corruption on Windows Server 2025 storage volumes.

Alternative or Verification Steps

  • Confirm the fix by re-running the original query or stored procedure that previously threw Error 9450 and verifying it returns results without exception.
  • As an alternative, temporarily store the data as NVARCHAR(MAX) instead of XML type during ingestion, validate the structure using OPENXML or TRY_CAST, and only convert to native XML type once confirmed well-formed.

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

Why This Error Happens

Error 9448 occurs when SQL Server’s internal XML parser encounters a malformed or structurally invalid XML document during an operation such as CAST, CONVERT, or OPENXML. This is typically caused by missing closing tags, invalid character encoding (such as improperly escaped special characters), or truncated XML data being passed into an XML-typed column or variable. In some cases, corrupted data pages or incomplete application-side XML generation can also trigger this parsing failure on Windows Server 2025 environments.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Error

  • Run the failing query again and capture the full error message, noting the specific line number (%d) referenced in the error.
  • Use SELECT CAST(@XMLVariable AS XML) in a test query to isolate which variable or column is causing the parse failure.
  • Check SQL Server Error Logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for additional context around the timestamp of the failure.

Step 2: Validate and Repair the XML Source Data

  • Open the XML content in a validator tool (e.g., Visual Studio Code with an XML extension) to check for unclosed tags, mismatched namespaces, or invalid entity references (e.g., unescaped &, <, or > characters).
  • Ensure the XML declaration header (<?xml version="1.0" encoding="UTF-8"?>) matches the actual encoding of the incoming data stream.
  • If the XML is generated by an external application or API, verify that the application is not truncating the payload due to buffer size limits.

Step 3: Check for Encoding and Collation Mismatches

  • Confirm the database collation using SELECT DATABASEPROPERTYEX('YourDBName', 'Collation'); and ensure it supports the character set used in the XML (especially for multi-byte or Unicode characters).
  • If importing from a file, verify the file is saved as UTF-8 without BOM, as a Byte Order Mark can sometimes cause unexpected parsing offsets in SQL Server 2025.

Step 4: Rebuild the Query or Stored Procedure Logic

  • Modify the T-SQL code to wrap the XML casting operation in a TRY...CATCH block to gracefully handle malformed input and log the raw offending string for review.
  • If using OPENXML, ensure you are calling sp_xml_removedocument after processing to prevent memory corruption in subsequent calls that could lead to intermittent parsing errors.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure with sample XML data; a successful SELECT or INSERT without the 9448 error confirms the structure is now valid.
  • As an alternative, if the error originates from replication or linked server data, try re-exporting the source XML using a different serialization method (e.g., switching from FOR XML AUTO to FOR XML PATH) to rule out generation-side corruption.

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

Troubleshooting Guide: SQL Server Error 9446 — “XML Parsing: Line %d”

Why This Error Happens

Error 9446 occurs when SQL Server’s XML parser encounters malformed, truncated, or incorrectly encoded XML data while attempting to parse a value into the xml data type. This is commonly caused by invalid characters embedded in the XML document, mismatched or unclosed tags, or data truncation that occurs when XML content exceeds buffer limits during insertion or import. It can also arise from corrupted data pages, improperly escaped special characters (such as &, <, >), or encoding mismatches (e.g., UTF-8 vs. UTF-16) between the source application and SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Error

  • Run the failing query with SET SHOWPLAN_XML OFF and capture the full error message, noting the specific line number referenced in the error.
  • Use SELECT CAST(YourXmlColumn AS NVARCHAR(MAX)) on the suspect row to visually inspect the raw XML content for malformed tags or special characters.
  • Check SQL Server Error Logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for additional context around the failure timestamp.

Step 2: Validate and Sanitize the XML Input

  • Open the source XML file or string in a validator (e.g., Visual Studio Code with an XML extension, or xmllint.exe from the Windows 11 / Windows Server 2025 developer tools) to confirm well-formed structure.
  • Ensure special characters are properly escaped: replace raw & with &amp;, < with &lt;, and > with &gt; in the source data.
  • If importing via SSIS or BCP, verify the CodePage and DataFileType settings match the source encoding (UTF-8 vs UTF-16) to prevent truncation mid-parse.

Step 3: Check for Data Truncation in Transit

  • Inspect the source application or ETL pipeline for NVARCHAR(MAX) vs NVARCHAR(n) mismatches that could silently truncate long XML strings before they reach SQL Server.
  • If using a .NET or ODBC driver connection string, confirm Packet Size is set sufficiently high (e.g., Packet Size=32767) in ODBC Data Source Administrator on Windows Server 2025.
  • Re-run the insert/import operation with a known-good, small XML sample to isolate whether the issue is data-specific or configuration-specific.

Step 4: Rebuild or Repair Corrupted XML Indexes

  • If the error persists only on existing stored XML data (not new inserts), run DBCC CHECKTABLE('YourTableName') WITH ALL_ERRORMSGS to check for underlying corruption.
  • Drop and rebuild any primary or secondary XML indexes using DROP INDEX followed by CREATE PRIMARY XML INDEX to eliminate index-level corruption as the cause.

Alternative or Verification Steps

  • Verify the fix by re-running the original failing query or import job and confirming Error 9446 no longer appears in ERRORLOG or SQL Server Management Studio’s Messages pane.
  • As an alternative, stage the XML data as NVARCHAR(MAX) first, run a validation check using YourColumn.exist('/') to confirm well-formedness, and only then cast it to the xml data type during final insertion.

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

Why This Error Happens

Error 9447 occurs when SQL Server’s internal XML parser encounters malformed or invalid XML data at a specific line number within an XML-typed column, variable, or document being processed. This is typically caused by invalid character encoding, unescaped special characters (like &, <, >), truncated XML data from a failed transfer, or a mismatch between the declared XML schema collection and the actual document structure. Corrupted data pages or interrupted write operations during XML insertion can also trigger this error in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source of the Malformed XML

  • Run the failing query and capture the full error message, noting the specific line number referenced in “XML parsing: line %d”.
  • Use SELECT xml_column FROM table_name WHERE id = X to extract the raw XML causing the failure.
  • Open SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and paste the XML into a new XML-type query window to visually inspect for broken tags or invalid characters.

Step 2: Validate and Repair the XML Structure

  • Check for unescaped special characters; replace & with &amp;, < with &lt;, and > with &gt; as needed.
  • Confirm the XML declaration encoding (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual file or stream encoding.
  • If using an XML Schema Collection, run:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';

to confirm the schema still matches the incoming document structure.

Step 3: Check for Data Truncation or Transfer Corruption

  • If XML is imported via SSIS, BCP, or OPENROWSET(BULK...), verify the source file wasn’t truncated mid-transfer.
  • On Windows Server 2025, check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for I/O warnings around the time of the failure.
  • Re-run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out page-level corruption affecting the XML data.

Step 4: Adjust Application or Import Code

  • If the XML originates from an application (e.g., .NET, PowerShell), ensure the XML writer uses XmlWriterSettings.CheckCharacters = true before sending data to SQL Server.
  • Update any ETL jobs to validate XML against an XSD schema before insertion.

Alternative or Verification Steps

  • Re-execute the original query or stored procedure that triggered Error 9447 — if it completes without raising “XML parsing: line %d”, the fix is confirmed.
  • As an alternative, use TRY_CAST(@xmlVariable AS XML) instead of CAST, which returns NULL instead of throwing an error, allowing you to isolate and log bad records without halting the batch.

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

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 .xml file and open it in Visual Studio Code or an XML validator (e.g., xmllint --noout file.xml via 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 Charset or Encoding parameter 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 Python lxml export) 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 of NVARCHAR(MAX)).

Step 4: Re-test Insertion with a Sanitized Payload

  • Replace the problematic XML fragment with a corrected version and re-run the INSERT or UPDATE statement.
  • If using sp_xml_preparedocument, confirm you’re also calling sp_xml_removedocument afterward 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 NULL and confirming the data loads without triggering Error 9445 again.
  • If the error persists intermittently, enable SQL Server Extended Events with the sql_statement_completed event filtered on your database to capture the exact XML payload at the moment of failure for deeper forensic analysis.

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

Troubleshooting Guide: SQL Server Error 9443 — “XML Parsing: Line %d”

Why This Error Happens

Error 9443 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data being inserted into an xml typed column, variable, or passed to functions like OPENXML, sp_xml_preparedocument, or FOR XML/XQuery operations. This is typically caused by invalid XML syntax (unclosed tags, mismatched elements, illegal characters), encoding mismatches between the source file and SQL Server’s expected UTF-8/UTF-16 format, or truncation of XML data during transfer (e.g., via a corrupted import file or a network interruption in SSIS/BCP jobs). It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schema collections are incompatible with the updated XML parser engine.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Run the failing query again and capture the full error message, noting the specific line %d referenced.
  • Extract the raw XML payload separately (e.g., SELECT @XmlData or dump to a .xml file) rather than relying on the SSMS grid, which can mask whitespace/encoding issues.
  • Open the extracted XML in a validator-capable editor (VS Code with XML extension, or Notepad++) to pinpoint unclosed tags, invalid nesting, or illegal characters like unescaped &, <, or >.

Step 2: Validate and Correct Encoding Issues

  • Check the source file encoding — SQL Server’s XML parser strictly expects UTF-8 or UTF-16 with a correct BOM (Byte Order Mark); mismatched encoding is a top cause of this error.
  • If importing via BCP or BULK INSERT, explicitly set the codepage:
  BULK INSERT dbo.YourTable FROM 'C:\Data\import.xml' WITH (CODEPAGE = '65001', DATAFILETYPE = 'char');
  • For SSIS packages on Windows Server 2025, verify the Flat File/XML Source connection manager’s CodePage property matches the source file exactly.

Step 3: Repair or Regenerate the XML Payload

  • If the file is externally generated (e.g., from a third-party application), request a re-export, as partial/truncated writes due to disk I/O interruption are common on network shares.
  • Use a quick validation script before insert to catch errors early:
  DECLARE @x XML = '<root><data>test</data></root>'; -- Replace with real payload
  SELECT @x; -- Will throw 9443 immediately if malformed
  • If using sp_xml_preparedocument, ensure you call sp_xml_removedocument afterward in prior sessions to rule out memory/handle corruption carrying over.

Step 4: Check for XML Schema Collection Conflicts (Post-Upgrade Scenarios)

  • If this started after upgrading to SQL Server 2025 on Windows Server 2025, run sp_help against any associated XML SCHEMA COLLECTION to confirm it still validates against the new parser.
  • Drop and recreate the schema collection if validation rules have changed:
  DROP XML SCHEMA COLLECTION YourSchemaCollection;
  CREATE XML SCHEMA COLLECTION YourSchemaCollection AS N'<xsd:schema>...</xsd:schema>';

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT/UPDATE/import job and confirming no Error 9443 is raised, then spot-check the stored XML column using value() or nodes() XQuery methods to confirm structural integrity.
  • As an alternative, if the source system cannot guarantee valid XML, wrap the insert logic in a TRY_CONVERT(XML, @data) check (SQL Server 2025 compatible) to gracefully null out invalid payloads instead of failing the entire transaction.

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

Troubleshooting Guide: SQL Server Error 9444 – XML Parsing Failure

Why This Error Happens

Error 9444 occurs when SQL Server’s XML parser encounters malformed, incomplete, or invalid XML data at a specific line number during an XML data type operation, such as an INSERT, CAST, or schema validation call. This is typically caused by corrupted source data, improperly escaped special characters (like unescaped ampersands or angle brackets), mismatched or unclosed tags, or an encoding mismatch between the source file and the expected UTF-8/UTF-16 format. It can also surface when a third-party application generates XML payloads that do not conform to a bound XML Schema Collection on the target column.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Note the exact line number reported in the error message (XML parsing: line %d).
  • Isolate the specific INSERT, UPDATE, or import job that triggered the error using SQL Server Profiler or Extended Events.
  • Extract the raw XML payload being processed and open it in a text editor like Notepad++ or VS Code to inspect the referenced line.

Step 2: Validate and Correct the XML Structure

  • Check for unescaped special characters (&, <, >) that must be replaced with entities (&amp;, &lt;, &gt;).
  • Verify all opening tags have matching closing tags and that nesting is correctly ordered.
  • Use an online or local XML validator (or xmllint --noout file.xml via WSL on Windows Server 2025) to confirm well-formedness before resubmitting.
  • If the column uses a bound XML Schema Collection, run SELECT * FROM sys.xml_schema_collections to confirm the schema requirements match the incoming data structure.

Step 3: Check Encoding and Data Truncation Issues

  • Confirm the source file encoding matches what SQL Server expects (UTF-8 without BOM or UTF-16), since mismatched encodings often cause parsing to fail mid-document.
  • If importing via OPENROWSET(BULK...) or BULK INSERT, verify the SINGLE_CLOB or SINGLE_BLOB option is correctly set to avoid truncating large XML payloads.
  • Inspect application-layer code (e.g., C#, PowerShell) for buffer limits that might be cutting off XML strings before they reach SQL Server.

Step 4: Rebuild and Retest the Query

  • Correct the identified malformed XML either at the source system or within a staging table using string manipulation functions (REPLACE, STUFF) as a temporary fix.
  • Re-run the original query or import job against the corrected XML payload in a non-production environment first.
  • Enable XML schema validation only after confirming the raw structure parses cleanly, to isolate whether the issue is structural or schema-based.

Alternative or Verification Steps

  • Verify the fix by re-executing SELECT CAST(@xmlVariable AS XML) against the corrected payload in SSMS; a successful return with no error confirms the parsing issue is resolved.
  • If the error persists intermittently, use a try-catch block with TRY_CAST and log failing payloads to a dedicated error table for pattern analysis before escalating to the data source owner.

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

Troubleshooting Guide: SQL Server Error 9442 – XML Parsing Error

Why This Error Happens

Error 9442 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within an XML data type column, variable, or document being processed. This is commonly caused by corrupted XML input (truncated tags, mismatched elements, or invalid characters), incorrect encoding declarations (e.g., UTF-16 data marked as UTF-8), or data truncation during transmission from an application or ETL process. In some cases, this surfaces after upgrading to SQL Server 2025 due to stricter XML schema validation introduced in the new query engine.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Run the failing query in SQL Server Management Studio (SSMS) and note the exact line number reported in the error message.
  • Use SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to extract the raw XML and inspect it manually for malformed tags or truncation.
  • Check if the XML is being generated by an external application (e.g., a .NET service or PowerShell script) — inspect that application’s serialization logic.

Step 2: Validate and Repair the XML Structure

  • Open the extracted XML in a validator (Visual Studio, Notepad++ with XML plugin, or xmllint on Windows Server 2025 via WSL).
  • Look for common issues: unclosed tags, invalid special characters (&, <, > not escaped), or an incorrect <?xml version="1.0" encoding="UTF-8"?> declaration that doesn’t match the actual byte encoding.
  • If the data is stored in a file, re-save it explicitly as UTF-8 without BOM using Notepad++ or VS Code, since mismatched BOM headers are a frequent cause of Error 9442 in SQL Server 2025.

Step 3: Correct the Application or Import Process

  • If data is imported via OPENROWSET(BULK...) or BULK INSERT, verify the SINGLE_CLOB or SINGLE_NCLOB option matches the actual file encoding.
  • For application-side XML generation, ensure the XML writer (e.g., System.Xml.XmlWriter in .NET 9) is not truncating output due to buffer size limits or premature stream closure.
  • Re-run the insert/update statement with the corrected XML payload.

Step 4: Apply SQL Server 2025 Compatibility Fixes

  • Check Windows Update and SQL Server Cumulative Updates (Help > About in SSMS) to confirm you’re on the latest CU, as early SQL Server 2025 builds had stricter XSD validation that flagged previously “tolerated” XML.
  • If necessary, temporarily lower the database compatibility level using:
    ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 160;
    to confirm whether the issue is tied to new parser behavior, then re-enable after fixing source XML.

Alternative or Verification Steps

  • Verify the fix by re-running the original INSERT, UPDATE, or SELECT statement that triggered Error 9442 — it should now execute without the XML parsing error.
  • As an alternative, use TRY_CAST or TRY_CONVERT instead of CAST/CONVERT to gracefully handle any remaining malformed XML rows without halting the entire batch, allowing you to isolate and log problem records for further cleanup.

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

Troubleshooting Guide: SQL Server Error 9440 – XML Parsing Error

Why This Error Happens

Error 9440 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during a parsing operation (such as XML data type validation, SSIS package execution, or XML schema collection processing). This is typically caused by invalid characters, mismatched tags, incorrect namespace declarations, or truncated XML content being passed into an XML column, variable, or stored procedure. It can also surface due to encoding mismatches (e.g., UTF-8 vs UTF-16) between the source file and SQL Server’s expected XML format.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Note the exact line number reported in the error message (e.g., “XML parsing: line 42”).
  • Locate the source of the XML — this could be a stored procedure parameter, an imported file, an SSIS data flow, or an application payload.
  • Extract the raw XML content and open it in a text editor like Notepad++ or VS Code to inspect line 42 (or the reported line) directly.

Step 2: Validate and Correct the XML Structure

  • Run the XML through an online or local XML validator (e.g., xmllint --noout file.xml on Windows Server 2025 via WSL, or use Visual Studio’s built-in XML schema validation).
  • Check for common issues: unclosed tags, unescaped special characters (&, <, >), or invalid attribute values.
  • If using an XML schema collection in SQL Server, verify the schema with:
SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Correct any malformed tags or re-encode the file as UTF-8 without BOM if encoding issues are suspected.

Step 3: Check Encoding and Collation Settings

  • Confirm the source application or file is saving XML in a SQL Server–compatible encoding (UTF-8 or UTF-16).
  • In SSIS packages, open the Flat File Connection Manager or XML Source component and verify the CodePage property matches the source file’s actual encoding.
  • For data imported via OPENROWSET or BULK INSERT, explicitly specify encoding:
SELECT CONVERT(XML, BulkColumn) 
FROM OPENROWSET(BULK 'C:\Data\file.xml', SINGLE_BLOB) AS x;

Step 4: Re-test the XML Import or Query

  • Re-run the original query, stored procedure, or SSIS package after correcting the XML source.
  • Monitor SQL Server Logs (via SQL Server Management Studio > Management > SQL Server Logs) or Event Viewer on Windows Server 2025 for recurrence of Event ID 9440.

Alternative or Verification Steps

  • Verify the fix by successfully casting the corrected XML using SELECT CAST(@xmlVariable AS XML); — if no error is returned, the structure is valid.
  • If the issue persists, isolate the problem by testing with a minimal, known-good XML sample to confirm whether the issue lies in the data itself or in the SQL Server XML schema collection/configuration.

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

Troubleshooting Guide: SQL Server Error 9441 – “XML Parsing: Line %d”

Why This Error Happens

Error 9441 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data during a parsing operation (such as CAST/CONVERT to XML, OPENXML, or XML column insertion). This is typically caused by invalid XML syntax (unclosed tags, mismatched elements, illegal characters), an incorrect encoding declaration that doesn’t match the actual byte content, or data truncation that occurs when XML content is transferred between applications, files, or network layers. In some cases, corrupted data pages or truncated BLOB/CLOB data being passed into an XML data type column can also trigger this error on SQL Server 2025 running under Windows Server 2025 or Windows 11.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the line number (%d) referenced in the error message — this points to the exact location in the XML document causing the parse failure.
  • Extract the raw XML source (from the application log, input file, or stored procedure parameter) and open it in a text editor or XML validator (e.g., Visual Studio, Notepad++ with XML plugin, or an online XML validator).
  • Run the following query to isolate the problematic value if it originates from a table:
  SELECT * FROM YourTable WHERE TRY_CAST(XmlColumn AS XML) IS NULL;

Step 2: Validate and Correct the XML Structure

  • Check for common structural issues: unclosed tags (<tag> without </tag>), mismatched nesting, or missing root elements.
  • Verify special characters (&, <, >, ", ') are properly escaped using XML entities (e.g., &amp; instead of &).
  • Confirm the XML declaration encoding (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual file or stream encoding — mismatches commonly occur when files are saved with UTF-8 BOM but declared as UTF-16, or vice versa.
  • If the XML is generated by an application, inspect the serialization logic (e.g., .NET XmlWriter settings) for incorrect encoding configuration.

Step 3: Check for Data Truncation in Transit

  • Verify that the column or variable receiving the XML data is large enough; XML stored in VARCHAR/NVARCHAR variables with insufficient length (e.g., VARCHAR(100) instead of VARCHAR(MAX)) silently truncates and breaks structure.
  • On Windows Server 2025, check network packet size settings in SQL Server Configuration Manager (TCP/IP properties) if XML is transmitted over linked servers or remote connections, as packet fragmentation can corrupt large XML payloads.
  • Re-run the import or insert operation after increasing variable/column sizes to MAX where applicable.

Step 4: Rebuild or Re-Import the Source File

  • If the XML originates from an external file (e.g., exported from an ETL tool or application), regenerate the file from the original source rather than attempting manual repair.
  • Use bcp or BULK INSERT with SINGLE_CLOB option to re-import as text first, allowing inspection before casting to XML:
  BULK INSERT #TempXML FROM 'C:\Data\source.xml' WITH (DATAFILETYPE = 'char', CODEPAGE = 'ACP');

Alternative or Verification Steps

  • Verify the fix: Run SELECT CAST(XmlColumn AS XML) against the corrected data — if no error is returned and the result displays properly formatted XML, the issue is resolved.
  • Alternative: If the XML source cannot be modified, use TRY_CAST or TRY_CONVERT in your queries to gracefully handle malformed XML rows without halting the entire batch, then log failures separately for manual review.

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

Troubleshooting Guide: SQL Server Error 9439 – XML Parsing Error

Why This Error Happens

Error 9439 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or non-well-formed XML data at a specific line number during a parsing operation (such as CONVERT, OPENXML, or inserting into an xml-typed column). This is typically caused by invalid characters, mismatched or unclosed tags, improper encoding declarations, or truncated XML content being passed into the database layer. It can also surface when an application generates XML dynamically and fails to escape special characters (like &, <, or >) correctly before submission.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML

  • Capture the full error message, which includes the specific line number (line %d) where parsing failed.
  • Run the failing query manually in SQL Server Management Studio (SSMS) on SQL Server 2025 to isolate the exact XML payload being processed.
  • Export the problematic XML string to a .xml file and open it in a validator (like Visual Studio Code with an XML extension) to visually inspect the flagged line.

Step 2: Validate and Correct the XML Structure

  • Check for common structural issues: unclosed tags, mismatched opening/closing tags, or multiple root elements.
  • Verify that special characters are properly escaped (e.g., & should be &amp;, < should be &lt;).
  • Confirm the XML declaration (<?xml version="1.0" encoding="UTF-8"?>) matches the actual encoding of the data stream, especially if data is coming from a Windows 11 client application using a different default codepage.
  • If the XML is generated by an application, review the source code or ETL job responsible for serialization (common with FOR XML AUTO/PATH queries or third-party APIs).

Step 3: Check for Data Truncation Issues

  • Error 9439 can appear if a varchar or nvarchar variable holding the XML string is too short, cutting off the data mid-tag before it reaches the xml data type conversion.
  • Increase the variable size to NVARCHAR(MAX) in your T-SQL script or stored procedure rather than using a fixed length like NVARCHAR(4000).
  • Re-run the import or conversion process to confirm the full XML string is passed without truncation.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Ensure Windows Server 2025 has the latest SQL Server 2025 Cumulative Update (CU) installed, as parser bugs are occasionally patched in maintenance releases.
  • Navigate to Microsoft Update Catalog or use SQL Server Setup to check the current build via:
  SELECT @@VERSION;
  • Apply any pending updates and restart the SQL Server (MSSQLSERVER) service via services.msc.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query or application transaction that triggered the error; successfully converting the string to the xml data type without a server-side exception confirms resolution.
  • Alternative Approach: If the XML source cannot be fixed immediately, use TRY_CONVERT(xml, @YourString) instead of CONVERT to handle malformed data gracefully (returning NULL instead of halting the batch), allowing you to log and filter bad records separately.

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

Troubleshooting Guide: SQL Server Error 9437 – XML Parsing Failure

Why This Error Happens

Error 9437 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or non-well-formed XML data at a specific line number during a parsing operation, such as an OPENXML, XML.query(), or CAST/CONVERT to the XML data type. This is typically caused by invalid characters, unclosed tags, improper encoding (e.g., mismatched UTF-8/UTF-16 declarations), or truncated XML data being passed into the column or variable. In some cases, this can also stem from corrupted data pages or an application layer that is incorrectly serializing XML before submission to the database.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Capture the full error message, noting the specific line number referenced in the XML parsing error.
  • Run the failing query in SQL Server Management Studio (SSMS) on Windows 11/Server 2025 to isolate the exact variable or column causing the fault.
  • Use SELECT LEN(YourXMLColumn) and SELECT YourXMLColumn to manually inspect the raw string for obvious truncation or hanging tags.

Step 2: Validate and Repair the XML Encoding

  • Check for a mismatched encoding declaration (e.g., the XML header states encoding="UTF-16" but the data was inserted as a varchar rather than nvarchar).
  • Ensure the XML prolog (<?xml version="1.0"?>) does not contain hidden whitespace or a Byte Order Mark (BOM) before the first tag.
  • If ingesting from a file via OPENROWSET(BULK...), verify the file path is correct: C:\SQLData\ImportFiles\source.xml and confirm the file uses a single root node.

Step 3: Correct the Application-Side Serialization

  • Review the client-side code (C#, Java, or PowerShell) generating the XML string to ensure all special characters (like &, <, >) are being escaped to their HTML entity equivalents (&amp;, &lt;, &gt;) before being sent to SQL Server 2025.
  • Check Event Viewer on Windows Server 2025 (Windows Logs > Application) for Event ID 9437 to correlate the exact timestamp with specific application logs.

Step 4: Increase Resource Limits for Large XML Payloads

  • If the XML is valid but extremely large, verify that the XML data type limitations (2GB) have not been exceeded.
  • Check the SQL Server Configuration Manager to ensure the Max Server Memory setting is not causing the parser to truncate data mid-stream due to memory pressure.

Alternative or Verification Steps

  • Verification: Run SELECT CAST(YourColumn AS XML) manually; if the query executes without throwing Error 9437, the XML structure has been successfully repaired.
  • Alternative: If the XML source is un-fixable at the origin, use a TRY_CAST or TRY_CONVERT wrapper in your T-SQL query to bypass the hard error and handle NULL results gracefully in the application logic instead.

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

Troubleshooting Guide: SQL Server Error 9438 — “XML Parsing: Line %d”

Why This Error Happens

Error 9438 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data being inserted into or processed through an xml data type column. This is typically caused by truncated XML strings, mismatched or unclosed tags, invalid character encoding (such as non-UTF-8 characters in a UTF-8 expected stream), or corruption introduced during data transfer from an external application, ETL process, or client driver. It can also surface when application code concatenates XML fragments incorrectly before passing them to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the specific line number (%d) referenced in the error message.
  • Run the failing INSERT, UPDATE, or CAST/CONVERT statement in isolation using SQL Server Management Studio (SSMS) to capture the raw XML payload.
  • Use SELECT LEN(@xmlVariable) and SELECT @xmlVariable to inspect the string length and content for truncation or unexpected characters before casting to xml.

Step 2: Validate and Repair the XML Structure

  • Check for unclosed tags, mismatched namespaces, or missing closing brackets near the reported line number.
  • Verify the encoding declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the source file or stream.
  • If the XML originates from an external file, open it in a validator (e.g., Visual Studio Code with an XML extension, or xmllint.exe on Windows Server 2025) to confirm well-formedness before re-importing.
  • On Windows 11/Server 2025, use PowerShell to quickly validate: [xml](Get-Content "C:\Data\input.xml").

Step 3: Correct the Application or Import Process

  • If data is coming from an ETL pipeline (SSIS, Azure Data Factory, or custom .NET code), ensure the XML fragment is fully assembled (no mid-stream truncation) before being passed to the xml parameter.
  • Check connection string and driver settings (ODBC/OLE DB) on the Windows client for correct text encoding (Use Encryption for Data = No conflicts or MARS settings can sometimes truncate large XML payloads).
  • Increase MAX XML DOCUMENT SIZE limits if applicable, and confirm the column/parameter isn’t being truncated by an upstream varchar(n) cast with insufficient length.

Step 4: Re-test with a Minimal Reproduction

  • Isolate a small, known-good XML snippet and incrementally add complexity to pinpoint where the parser breaks.
  • Use SELECT CAST('<root><child>test</child></root>' AS xml) as a baseline sanity check in SSMS on SQL Server 2025.

Alternative or Verification Steps

  • Confirm the fix by re-running the original query/import job and verifying it completes without raising Error 9438, then spot-check the inserted XML with SELECT CAST(xmlColumn AS nvarchar(max)).
  • If the issue persists and the source system cannot guarantee well-formed XML, wrap the cast in a TRY_CAST or TRY_CONVERT to gracefully handle malformed entries and log them separately for manual review instead of failing the entire batch.

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

Why This Error Happens

Error 9436 occurs when SQL Server’s native XML parser encounters malformed, incomplete, or improperly encoded XML data that violates well-formedness rules (such as mismatched tags, invalid characters, or incorrect encoding declarations). This frequently happens when XML data is truncated during transmission, imported from a corrupted source file, or when an application constructs XML strings dynamically without proper escaping of special characters like &, <, or >. In SQL Server 2025 running on Windows Server 2025, this can also surface if the XML exceeds the default nested level limit (128 levels) or if a BOM (Byte Order Mark) mismatch exists between the declared encoding and the actual file encoding.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Causing the Failure

  • Run the failing query in SSMS and capture the full error message, noting the line number referenced (e.g., “XML parsing: line 12, character 45”).
  • Use SELECT CAST(@XmlVariable AS XML) in isolation to narrow down which specific XML payload is triggering the fault.
  • Check source logs or the originating application (ETL job, API payload, etc.) to pull the raw XML string before it was cast.

Step 2: Validate and Repair the XML Structure

  • Open the raw XML in a validator like Visual Studio’s XML Editor or an online XML linter to check for unclosed tags, invalid nesting, or illegal characters.
  • Ensure special characters are properly escaped: replace raw & with &amp;, < with &lt;, and > with &gt;.
  • Verify the encoding declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file — mismatches commonly occur when files are saved as UTF-8 with BOM but declared as ISO-8859-1.

Step 3: Check for Nested Level and Size Limitations

  • Confirm the XML does not exceed the default max nesting depth of 128 levels; if it does, use OPTION (MAXRECURSION 0) is not applicable here — instead, use the sp_xml_preparedocument with the MaxNodes parameter or redesign the schema to reduce depth.
  • If the XML is being passed through a stored procedure, verify the input parameter is typed as XML and not truncated by an intermediate VARCHAR or NVARCHAR field with insufficient length (common culprit: NVARCHAR(4000) truncating larger payloads).

Step 4: Update SQL Server 2025 and Windows Server 2025 Components

  • Apply the latest Cumulative Update (CU) for SQL Server 2025 via SQL Server Update Center, since XML parser bug fixes are periodically rolled into CUs.
  • On Windows Server 2025 / Windows 11, ensure the MSXML library (msxml6.dll) is not corrupted by running sfc /scannow from an elevated Command Prompt.

Alternative or Verification Steps

  • Re-run the original CAST/CONVERT or OPENXML operation after applying the fix — if it completes without Error 9436, the XML is now well-formed.
  • As a quick alternative, wrap the import logic with a TRY_CAST(@XmlData AS XML) check in a staging query to silently flag malformed records for manual review before they hit production procedures.

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

Troubleshooting Guide: SQL Server Error 9434 – XML Parsing Error

Why This Error Happens

Error 9434 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within the document. This typically stems from invalid characters, mismatched or unclosed tags, encoding mismatches (such as UTF-8 vs UTF-16 conflicts), or truncated data caused by application-layer transmission issues. Corrupted XML can also result from improper escaping of special characters (like &, <, >) when data is inserted into an xml-typed column.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the exact line number reported in the error message (e.g., “line %d”).
  • Run the failing query in SQL Server Management Studio (SSMS) on Windows Server 2025 and capture the full XML payload being inserted or parsed.
  • Use SELECT CAST(@XmlVariable AS NVARCHAR(MAX)) to visually inspect the raw content around the reported line.

Step 2: Validate and Sanitize the XML Structure

  • Check for unclosed or mismatched tags (e.g., <Item> without </Item>).
  • Verify special characters are properly escaped: replace & with &amp;, < with &lt;, and > with &gt;.
  • If the XML originates from an external file, open it in a text editor (like VS Code on Windows 11) and run an XML validation check or use xmllint --noout file.xml via WSL if installed.

Step 3: Correct Encoding Mismatches

  • Confirm the XML declaration matches the actual file encoding, e.g., <?xml version="1.0" encoding="UTF-8"?>.
  • If data is sourced from OPENROWSET(BULK...), ensure the SINGLE_CLOB or SINGLE_NCLOB option matches the file’s actual byte encoding (ANSI vs Unicode).
  • Re-save the source file with the correct encoding using Notepad++ or PowerShell: Get-Content file.xml | Set-Content -Encoding UTF8 file_fixed.xml.

Step 4: Re-Test the Insert or Query Operation

  • Re-run the original INSERT, UPDATE, or SELECT ... FOR XML statement using the corrected XML payload.
  • Monitor SQL Server Error Logs (via SSMS > Management > SQL Server Logs) to confirm Error 9434 no longer appears.

Alternative or Verification Steps

  • Verify the fix by querying the affected xml column using SELECT *.query('/') to confirm SQL Server can successfully parse and return the document tree without throwing an exception.
  • If the issue persists, bypass strict XML typing temporarily by storing the data as NVARCHAR(MAX) and using TRY_CAST(... AS XML) to isolate and log specifically which rows contain invalid XML structures.

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

Why This Error Happens

Error 9435 occurs when SQL Server’s XML parser encounters malformed or invalid XML data at a specific line number, typically due to improperly closed tags, invalid character encoding, or truncated XML content being passed into an XML data type column or OPENXML/sp_xml_preparedocument call. This can also result from corrupted data during transmission, incompatible encoding (such as UTF-16 vs UTF-8 mismatches), or application-layer bugs that generate non-well-formed XML before insertion. In some cases, this is triggered by XML schema collection validation failures when the document structure doesn’t conform to the expected schema.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of Malformed XML

  • Capture the full error message, including the line number referenced (e.g., “XML parsing: line 12, unclosed tag”).
  • Extract the raw XML payload from the source application or request log just before it was sent to SQL Server.
  • Use a validator (Visual Studio XML Editor, xmllint, or an online validator) to pinpoint the malformed section at that exact line.

Step 2: Validate Encoding and Special Characters

  • Check whether the XML document begins with a proper declaration, e.g. <?xml version="1.0" encoding="UTF-8"?>.
  • Confirm there are no unescaped special characters (&, <, >) inside element values — they must be replaced with &amp;, &lt;, &gt;.
  • If the XML originates from a file, re-save it using UTF-8 encoding without BOM in a text editor like Notepad++ or VS Code.

Step 3: Fix the Application or Import Script

  • Inspect the application code (C#, PowerShell, or SSIS package) responsible for constructing the XML string and ensure it uses a proper XML serializer (e.g., System.Xml.XmlWriter) rather than manual string concatenation.
  • If using sp_xml_preparedocument, verify the input variable is of type NVARCHAR(MAX) and not truncated due to a smaller variable size.
  • Re-run the insert or import job after correcting the structure.

Step 4: Check XML Schema Collection (If Applicable)

  • Run SELECT name FROM sys.xml_schema_collections; in SQL Server Management Studio (SSMS) to confirm the schema bound to the column.
  • Temporarily remove the schema binding using ALTER TABLE ... ALTER COLUMN ... XML(NULL) to test if the error is schema-validation related rather than a pure parsing issue.
  • Reapply the schema only after confirming the XML is well-formed and compliant.

Alternative or Verification Steps

  • Verify the fix by re-executing the original INSERT/UPDATE statement or re-importing the file; the operation should complete without raising Error 9435.
  • As an alternative, use SELECT TRY_CONVERT(XML, @YourXmlVariable); in SSMS — if it returns NULL instead of throwing an error, you’ll know immediately whether the XML is malformed before attempting a full execution.

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

Troubleshooting Guide: SQL Server Error 9433 – XML Parsing Error

Why This Error Happens

Error 9433 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during a parsing operation. This typically results from corrupted XML input files, mismatched tags, invalid character encoding (such as UTF-8 BOM issues), or truncated data caused by network interruptions or buffer size limitations. In some cases, this also surfaces when application code passes dynamically generated XML that violates well-formedness rules before it reaches SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Content Causing the Failure

  • Open the source XML file or variable content referenced in the error message using a text editor like Notepad++ or VS Code on Windows 11 / Windows Server 2025.
  • Navigate directly to the line number specified in the error (e.g., “XML parsing: line 42, unexpected end of tag”).
  • Check for unclosed tags, mismatched namespaces, or invalid special characters (such as unescaped &, <, or >).

Step 2: Validate the XML Structure Using an External Validator

  • Run the XML content through an independent validation tool (e.g., msxml6.dll via PowerShell, or an online XSD/XML validator) to isolate SQL Server-specific issues from genuine syntax errors.
  • Use the following PowerShell snippet to quickly test validity:
  [xml]$test = Get-Content "C:\Data\input.xml"
  • If PowerShell throws a parsing exception, the file itself is corrupted and not an SQL Server configuration issue.

Step 3: Check Encoding and BOM (Byte Order Mark) Settings

  • Confirm the file is saved as UTF-8 without BOM, as SQL Server’s XML parser can misinterpret a leading BOM as invalid character data.
  • In Notepad++, go to Encoding > Convert to UTF-8 (without BOM) and re-save the file.
  • Re-import or re-run the query using OPENROWSET(BULK...) or sp_xml_preparedocument referencing the corrected file path (e.g., C:\SQLData\Import\input.xml).

Step 4: Review the T-SQL Command Generating or Parsing the XML

  • Inspect the stored procedure or application code for string concatenation errors that might be injecting invalid characters into the XML variable.
  • Ensure FOR XML PATH or FOR XML AUTO clauses are correctly closed and that XML variables are explicitly cast using CAST(... AS XML) rather than relying on implicit conversion.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query or import job in SQL Server Management Studio (SSMS) 2025; a successful execution with no Error 9433 confirms the XML is now well-formed.
  • Alternative Solution: If the file is generated by a third-party application, request a re-export in a compliant XML 1.0 format, or use sp_xml_removedocument to clear memory handles and retry parsing with a freshly generated document.

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

Troubleshooting Guide: SQL Server Error 9431 – “XML Parsing: Line %d”

Why This Error Happens

Error 9431 occurs when SQL Server’s XML parser encounters malformed, truncated, or improperly encoded XML data that violates well-formedness rules during an INSERT, CAST, or CONVERT operation involving the XML data type. This is commonly caused by invalid characters (such as unescaped ampersands or angle brackets), mismatched tags, incorrect namespace declarations, or encoding mismatches (UTF-8 vs UTF-16) between the source data and the XML column definition. In some cases, this also surfaces due to corrupted data pages or truncated data streams when importing large XML documents via BULK INSERT or OPENROWSET.

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) 21 on Windows 11 to capture the full error message, including the specific line number referenced in the XML.
  • Use SELECT CAST(@XMLVariable AS XML) in isolation to narrow down which row or batch is triggering the parse failure.
  • Check source files for hidden control characters using a hex editor like HxD, especially around the reported line number.

Step 2: Validate XML Structure and Encoding

  • Confirm the XML declaration matches the actual encoding of the file (e.g., <?xml version="1.0" encoding="UTF-8"?> should match the saved file format).
  • Verify all tags are properly closed and nested; unescaped special characters like &, <, and > must be replaced with &amp;, &lt;, and &gt; respectively.
  • If importing via OPENROWSET(BULK...), confirm the file path is accessible from the SQL Server service account under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\.

Step 3: Repair or Regenerate the Source XML Data

  • If the XML is generated programmatically, inspect the application logic (e.g., .NET XmlWriter or JSON-to-XML conversion) for incomplete serialization before the data reaches SQL Server.
  • For manually edited files, run the XML through a validator tool (like xmllint or Visual Studio 2022’s XML schema checker) before re-attempting the insert.
  • Re-run the import or transaction using SET XML_PARSER_VALIDATE ON (if applicable to your scenario) to catch errors early in a test environment.

Step 4: Check for Database Corruption (If Issue Persists on Existing Data)

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORS to rule out page-level corruption affecting the XML column storage.
  • If corruption is found, restore the affected table or database from the most recent verified backup.

Alternative or Verification Steps

  • Verify the Fix: Re-execute the original INSERT or CAST statement; if successful, query the column using YourXMLColumn.exist('/') to confirm the data is queryable and structurally valid.
  • Alternative: If the source system cannot guarantee well-formed XML, stage the data in an NVARCHAR(MAX) column first, apply a cleansing/sanitization step using SQL string functions or a pre-processing script, and only cast to XML after validation passes.

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

Troubleshooting Guide: SQL Server Error 9432 — “XML Parsing: Line %d”

Why This Error Happens

Error 9432 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data during an insert, query, or import operation. This is typically caused by corrupted source files, mismatched or missing closing tags, invalid character encoding (such as UTF-8 BOM issues), or truncated data streams caused by network interruptions. In some cases, this also surfaces when legacy XML schemas are used with SQL Server 2025’s updated XML parsing engine, which enforces stricter validation rules than previous versions.

Step-by-Step Resolution Guide

Step 1: Validate the XML Source Data

  • Open the offending XML file or string in a validator (e.g., Visual Studio, Notepad++ with XML plugin, or an online XML validator) to pinpoint the exact line referenced in the error.
  • Check for unclosed tags, mismatched namespaces, or illegal characters (such as raw &, <, or > symbols not properly escaped).
  • Run the following T-SQL to test parsing in isolation:
  DECLARE @x XML = '<YourXMLContentHere/>';

Step 2: Check Encoding and BOM Issues

  • Open the file in a hex editor or VS Code and confirm it does not contain a stray Byte Order Mark (BOM) at the start (common with UTF-8 encoded files generated on Windows 11).
  • Re-save the file using UTF-8 without BOM via Notepad++ (Encoding menu → “UTF-8” instead of “UTF-8-BOM”).
  • If importing via BULK INSERT or OPENROWSET, explicitly specify encoding:
  SELECT * FROM OPENROWSET(BULK 'C:\Data\file.xml', SINGLE_CLOB) AS XMLData;

Step 3: Update SQL Server 2025 Cumulative Updates

  • Navigate to Microsoft Update Catalog and confirm the latest Cumulative Update (CU) for SQL Server 2025 is installed, as early builds had known XML parser regression bugs.
  • On Windows Server 2025, verify patch status via:
  Get-HotFix | Where-Object {$_.Description -like "*SQL*"}
  • Restart the SQL Server service after patching through SQL Server Configuration Manager.

Step 4: Inspect Network or File Transfer Integrity

  • If the XML is received over a network connection (API, linked server, or SSIS package), confirm the payload isn’t being truncated mid-transfer.
  • Check SSIS package logs or API gateway logs for incomplete HTTP responses.
  • Re-run the import with a locally saved copy of the XML file to rule out transmission corruption.

Alternative or Verification Steps

  • Re-run the original query or import job after corrections; confirm no Error 9432 appears in SQL Server Logs (via SSMS → Management → SQL Server Logs) or Event Viewer on Windows Server 2025.
  • As an alternative, use TRY_CAST or TRY_CONVERT to AS XML in a test query — if it returns NULL instead of throwing an error, the source data still contains invalid XML that needs manual correction.

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

Troubleshooting Guide: SQL Server Error 9430 — “XML Parsing: Line %d”

Why This Error Happens

Error 9430 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data being inserted into an xml data type column or passed to an XML-handling function. This is typically caused by invalid characters, unclosed tags, mismatched namespaces, or truncated XML content arriving from an application, import file, or linked server query. It can also surface due to corrupted data pages or a mismatch between the XML schema collection and the actual document structure in Microsoft SQL Server 2025 running on Windows Server 2025 / Windows 11.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XML Data

  • Identify the exact line number referenced in the error message (line %d) to narrow down the malformed section.
  • Run the failing query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF and capture the raw input using PRINT or SELECT @xmlVariable before the parsing step.
  • Use SELECT CAST(@xmlData AS XML) in isolation to confirm whether the error reproduces outside the larger batch.

Step 2: Validate and Repair the XML Source

  • Open the source file or payload in a text editor (e.g., VS Code on Windows 11) and check for unclosed tags, invalid entity references (like unescaped &, <, >), or BOM/encoding issues (UTF-8 vs UTF-16 mismatches).
  • Validate the document against any associated XML Schema Collection using:
  SELECT xml_schema_namespace('dbo', 'YourSchemaCollectionName');
  • If the data originates from an external application or ETL job, check the source system logs under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ for truncation or encoding errors during transmission.

Step 3: Correct Application-Side Encoding and Escaping

  • Ensure the client application properly escapes special characters before sending XML (e.g., using System.Xml.XmlWriter in .NET rather than manual string concatenation).
  • Confirm the connection string specifies the correct character encoding (Charset=utf-8) to prevent mid-stream corruption.
  • Re-run the insert/update operation after correcting the payload to confirm the parser no longer throws Error 9430.

Step 4: Check for Database-Level Corruption

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out page-level corruption affecting XML column storage.
  • Review the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for correlating I/O or storage engine warnings around the same timestamp as the 9430 error.

Alternative or Verification Steps

  • Verify the fix by re-executing the original INSERT/UPDATE statement or ETL job and confirming no Error 9430 appears in the SQL Server Error Log or Windows Event Viewer (Event ID source: MSSQLSERVER).
  • If the issue persists, bypass strict schema validation temporarily by casting to untyped XML (without a schema collection) to confirm whether the schema collection itself — rather than the raw document — is the root cause.

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

Troubleshooting Guide: SQL Server Error 9429 (XML Parsing Error)

Why This Error Happens

Error 9429 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number within a column, variable, or document being processed. This typically stems from corrupted XML data being inserted into an xml typed column, mismatched or unclosed tags, invalid character encoding (such as non-UTF-8 byte sequences), or truncation of XML data during a network transfer or bulk insert operation. It can also surface when an application passes malformed XML strings into stored procedures that use OPENXML, sp_xml_preparedocument, or native XML methods like .nodes() or .query().

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Note the exact line number referenced in the error message; this points to the specific location in the XML string causing the parse failure.
  • Run a diagnostic query to extract the offending XML: SELECT xml_column FROM your_table WHERE id = <problem_id> and inspect it in SQL Server Management Studio’s XML viewer.
  • Check the application or ETL log (in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ on Windows Server 2025) for the raw payload sent prior to the error.

Step 2: Validate and Repair the XML Structure

  • Use an external XML validator (such as xmllint via WSL on Windows 11, or Visual Studio’s XML editor) to confirm whether tags are improperly nested or unclosed.
  • Check for encoding mismatches — ensure the XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the data, especially if data originates from a BCP file or flat-file import.
  • If the issue stems from truncation, verify the nvarchar(max) or xml column has not been cut off due to a buffer limit in the client driver (check TDS packet size settings in the connection string).

Step 3: Correct the Application/Import Process

  • If using OPENROWSET(BULK...) or BCP to load XML files, confirm the CODEPAGE and DATAFILETYPE parameters match the source file’s actual encoding.
  • For application-generated XML, review the serialization library (e.g., .NET’s XmlWriter) to ensure special characters (&, <, >) are properly escaped before insertion.
  • Re-run the insert/update operation after correcting the payload:
DECLARE @x xml = N'<Root><Item>Test</Item></Root>';
INSERT INTO your_table (xml_column) VALUES (@x);

Step 4: Apply SQL Server Updates and Patches

  • Confirm SQL Server 2025 is running the latest Cumulative Update via SELECT @@VERSION;, as XML parser edge-case bugs are periodically patched by Microsoft.
  • Download and apply the latest CU from the Microsoft Update Catalog if running an older build.

Alternative or Verification Steps

  • Verify the fix by re-executing the original query or stored procedure that triggered Error 9429 and confirming successful execution without exceptions.
  • As an alternative, cast the XML data to varchar(max) first using TRY_CAST to isolate whether the issue is parser-related or data-related: SELECT TRY_CAST(xml_column AS xml) FROM your_table; — a NULL result confirms malformed XML rather than a server-side bug.

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

Why This Error Happens

Error 9427 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data while processing an XML data type column, variable, or during an OPENXML/FOR XML operation. This is typically caused by unclosed tags, invalid character encoding (such as BOM mismatches or non-UTF-8 characters), mismatched namespaces, or truncated XML content resulting from data transmission issues or application-side serialization bugs. It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schemas were validated under a looser parsing mode in older engine versions.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Position

  • Capture the full error message text, which includes the line number, character offset, and a description (e.g., “unexpected end of input”).
  • Run the failing query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML OFF to ensure you see the raw error rather than a truncated one.
  • Extract the offending XML string into a text editor (Notepad++ or VS Code) and navigate to the exact line/character to visually inspect the malformed section.

Step 2: Validate and Repair the XML Source Data

  • Use an XML validator (xmllint --noout file.xml on Windows Server 2025 via WSL, or an online schema validator) to confirm whether the file is well-formed.
  • Check for common culprits: unescaped ampersands (&), unclosed tags, mismatched namespace prefixes, or invalid control characters (ASCII 0x00–0x08).
  • If the XML is generated by an application, inspect the serialization logic (e.g., .NET XmlWriter settings) to ensure Encoding.UTF8 is used without an unexpected Byte Order Mark (BOM) being injected into the stream.

Step 3: Correct Encoding and Collation Settings

  • Confirm the database collation and the XML column’s expected encoding align — mismatches between UTF-16 (SQL Server’s internal XML storage format) and incoming UTF-8 byte streams often trigger 9427.
  • In connection strings, verify Packet Size and Character Encoding settings are not truncating multi-byte characters mid-stream.
  • If importing via BULK INSERT or OPENROWSET(BULK...), add the SINGLE_CLOB option explicitly and specify CODEPAGE = '65001' for UTF-8 source files.

Step 4: Patch and Test on SQL Server 2025

  • Apply the latest Cumulative Update (CU) for SQL Server 2025, as early builds have documented XML parser regressions related to strict schema validation.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) after patching.
  • Re-run the original query or import job to confirm the parser no longer throws Error 9427.

Alternative or Verification Steps

  • Verify the fix by executing SELECT CAST(@xmlVariable AS XML); against the corrected source data — if no error is thrown, the XML is now well-formed and compatible with the SQL Server parser.
  • As a workaround, if the XML is only partially malformed, use TRY_CAST or TRY_CONVERT with error logging to isolate and skip bad records instead of failing the entire batch.

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

Troubleshooting Guide: SQL Server Error 9428 (“XML parsing: line %d”)

Why This Error Happens

Error 9428 occurs when SQL Server 2025’s XML parser encounters malformed, incomplete, or improperly encoded XML data during an insert, update, or CAST/CONVERT operation into an xml data type column. This is typically caused by corrupted data during transmission, mismatched or unescaped special characters (like &, <, >), an invalid encoding declaration in the XML prolog, or a truncated XML document resulting from an application-layer bug or network interruption. In rare cases, it can also stem from a damaged XML index or corrupted page in the underlying table.

Step-by-Step Resolution Guide

Step 1: Isolate and Inspect the Offending XML Data

  • Identify the exact line number referenced in the error message (line %d) to narrow down the malformed section of the XML document.
  • Run the failing query in SQL Server Management Studio (SSMS) and capture the full XML payload being inserted using PRINT or by redirecting output to a text file.
  • Check for unescaped special characters (&, <, >, ', ") that aren’t properly encoded as entities (&amp;, &lt;, etc.).

Step 2: Validate the XML Encoding and Structure

  • Open the suspect XML in a validator (e.g., Visual Studio’s XML Editor or an online XML linter) to confirm it is well-formed.
  • Verify the XML declaration matches the actual encoding of the data stream, e.g., <?xml version="1.0" encoding="UTF-8"?> — mismatches here commonly trigger Error 9428.
  • If the XML is generated by an application, inspect the source code for string concatenation issues or premature stream closures that could truncate the document.

Step 3: Repair or Sanitize the Input Pipeline

  • Update the client application or ETL process to use a proper XML serializer (e.g., System.Xml.XmlWriter in .NET) instead of manual string building, which often introduces malformed tags.
  • If importing from a file via OPENROWSET(BULK...), confirm the file isn’t corrupted by re-exporting it from the source system.
  • Add server-side validation using an XML schema collection:
  ALTER TABLE YourTable
  ALTER COLUMN XmlColumn XML (YourSchemaCollection);

Step 4: Check for Database-Level Corruption

  • If the error persists only on existing stored data (not new inserts), run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORRESULTS; to rule out page-level corruption affecting the XML column or its index.
  • Rebuild any affected XML indexes using ALTER INDEX ALL ON YourTable REBUILD; if corruption is isolated to the index rather than the base table.

Alternative or Verification Steps

  • Verify the fix: Re-run the original INSERT/UPDATE statement with the corrected XML payload and confirm it completes without Error 9428; optionally use SELECT CAST(@xmlVariable AS XML) as a quick standalone validation test.
  • Alternative approach: If the source system cannot guarantee well-formed XML, wrap the insert logic in a TRY_CAST or TRY_CONVERT (SQL Server 2025 supports improved XML error handling) and route failures to a quarantine table for manual review instead of failing the entire transaction.

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

Troubleshooting Guide: SQL Server Error 9425 – XML Parsing Failure

Why This Error Happens

Error 9425 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during parsing operations. This typically stems from corrupted XML input (such as invalid characters, unclosed tags, or encoding mismatches like UTF-8 vs UTF-16), data truncation during transmission, or improperly escaped special characters within XML columns or variables. It can also surface when applications pass malformed XML to stored procedures using OPENXML, FOR XML, or native XML data type columns.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source and Line Number

  • Review the full error message to note the specific line number referenced (e.g., “XML parsing: line 12, unexpected end of input”).
  • Locate the source query, stored procedure, or application call generating the XML using SQL Server Profiler or Extended Events in SQL Server Management Studio (SSMS).
  • Run the query manually: SELECT TRY_CAST(YourXmlColumn AS XML) FROM YourTable WHERE ID = <ProblemRowID>; to isolate the exact malformed record.

Step 2: Validate and Repair the XML Structure

  • Check for unclosed or mismatched tags, missing root elements, or invalid special characters (&, <, >) that aren’t properly escaped as &amp;, &lt;, &gt;.
  • Verify the encoding declaration matches the actual file/stream encoding (e.g., <?xml version="1.0" encoding="UTF-8"?> must match the source).
  • Use a validation tool or run: SELECT xmlcolumn.exist('/root') FROM YourTable; to test well-formedness before full parsing.
  • If the XML originates from an external application, check the application logs on Windows Server 2025 (Event Viewer > Applications and Services Logs) for truncation or encoding errors during data transmission.

Step 3: Correct the Application or Import Process

  • If data is ingested via SSIS or BULK INSERT, confirm the file encoding matches the CODEPAGE parameter specified in the import statement.
  • Update application code to properly encode XML output using libraries like System.Xml (for .NET apps) instead of manual string concatenation, which often introduces malformed tags.
  • Re-run the import or transaction after correcting the source XML payload.

Step 4: Check for SQL Server Patch-Level Issues

  • Confirm SQL Server 2025 is updated to the latest Cumulative Update (CU) via SELECT @@VERSION; and cross-reference with Microsoft’s release notes, as XML parser bugs are occasionally patched.
  • Apply the latest CU using SQL Server Setup or Windows Update if running integrated services.

Alternative or Verification Steps

  • After applying fixes, re-execute the original query or application transaction and confirm no Error 9425 appears in the SQL Server Error Log (EXEC xp_readerrorlog;).
  • As an alternative, if the XML source cannot be immediately fixed, implement a TRY...CATCH block around the XML parsing logic to gracefully log and quarantine malformed records instead of failing the entire transaction.

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

Troubleshooting Guide: SQL Server Error 9426 — XML Parsing Error

Why This Error Happens

Error 9426 occurs when SQL Server’s native XML parser encounters malformed, incomplete, or non-well-formed XML data at a specific line/character position during a parsing operation (such as OPENXML, .query(), .value(), or casting a string to the XML data type). This is typically caused by invalid XML syntax (unclosed tags, mismatched elements, illegal characters, or encoding mismatches) in the source data rather than a SQL Server configuration problem. It can also surface when the XML data was corrupted in transit, truncated by an upstream application, or when the character encoding declared in the XML prolog doesn’t match the actual byte encoding of the data.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Position

  • Note the exact line number and character offset reported in the error message (e.g., “XML parsing: line 12, character 45”).
  • Extract the raw XML payload causing the failure by querying the source table/column directly, or capture it via a SQL Server Profiler/Extended Events trace filtered on Error 9426.
  • Open the extracted XML in a text editor (Notepad++, VS Code) with line numbers enabled to inspect the exact location.

Step 2: Validate and Correct the XML Structure

  • Run the extracted XML through an XML validator (e.g., xmllint --noout file.xml on Windows via WSL, or an online/offline XML schema validator) to pinpoint well-formedness errors.
  • Check common culprits: unescaped special characters (&, <, > not converted to &amp;, &lt;, &gt;), mismatched opening/closing tags, and missing root elements.
  • Verify the encoding declaration in the XML prolog (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual file/stream encoding — mismatches between UTF-8 and UTF-16 are a frequent cause.
  • If the XML originates from an application (API, ETL job, or client app), check the generating code for improper string concatenation instead of using an XML serializer library.

Step 3: Correct the Source Data or Application Logic

  • If the malformed XML is already stored in a table, update the offending row using UPDATE table SET xmlcol = '<corrected>...</corrected>' WHERE id = X.
  • If the XML is generated dynamically, modify the application or stored procedure to use FOR XML PATH with proper escaping, or switch to using parameterized XML serialization methods instead of manual string building.
  • Re-run the failing query or import/ETL job (e.g., SSIS package, BULK INSERT, or OPENROWSET) against the corrected XML payload.

Step 4: Patch SQL Server and Review Collation/Encoding Settings

  • Confirm SQL Server 2025 is on the latest Cumulative Update via SELECT @@VERSION; and compare against Microsoft’s release notes, as XML parser edge-case bugs are occasionally patched.
  • Check the database collation (SELECT DATABASEPROPERTYEX('YourDB', 'Collation');) to ensure it supports the character set used in the incoming XML, especially for multi-byte or non-Latin character sets.

Alternative or Verification Steps

  • Re-execute the original query/import process and confirm Error 9426 no longer appears; additionally run SELECT CAST(xmlcol AS XML) on the corrected row to confirm it casts without error.
  • As an alternative, if the data source cannot be fixed immediately, wrap the parsing logic in a TRY...CATCH block combined with TRY_CAST/TRY_CONVERT to gracefully skip or log malformed rows instead of failing the entire batch.

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

Troubleshooting Guide: SQL Server Error 9424 – XML Parsing Error

Why This Error Happens

Error 9424 occurs when SQL Server’s internal XML parser encounters malformed, incomplete, or non-well-formed XML data at a specific line number during a parsing operation. This is typically caused by invalid XML syntax (unclosed tags, mismatched elements, illegal characters, or encoding mismatches) being passed into functions like OPENXML, sys.xml, TRY_CONVERT, or during XML data type column operations. It can also surface due to truncated data transfers, corrupted source files, or application code that incorrectly constructs XML strings before sending them to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the Malformed XML

  • Note the specific line number reported in the error message (e.g., “XML parsing: line 12”).
  • Query the source table or variable holding the XML data using SELECT CAST(YourXMLColumn AS NVARCHAR(MAX)) to export the raw string for inspection.
  • Use a tool like Notepad++, VS Code, or an online XML validator to pinpoint the syntax issue at that line.

Step 2: Validate and Correct the XML Structure

  • Check for common issues: unclosed tags (<tag> without </tag>), unescaped special characters (&, <, > not converted to &amp;, &lt;, &gt;), or mismatched namespaces.
  • Verify the encoding declaration at the top of the XML (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file or string.
  • If the XML originates from an external API or application, review the serialization logic in the source code (e.g., .NET XmlWriter settings) to ensure proper escaping.

Step 3: Test the Corrected XML in a Controlled Environment

  • Run the corrected XML through a simple test query on Windows Server 2025:
DECLARE @x XML = N'<YourCorrectedXML>Data</YourCorrectedXML>';
SELECT @x;
  • If using OPENXML, ensure you are also calling sp_xml_removedocument after processing to release memory and avoid downstream parsing conflicts.
  • Confirm that SQL Server 2025 instance collation settings support the character set used in the XML payload (check via SELECT SERVERPROPERTY('Collation')).

Step 4: Check for File Corruption or Transmission Truncation

  • If the XML is read from a file path (e.g., via OPENROWSET(BULK...)), verify the file isn’t truncated by checking the file size against the expected output size from the source system.
  • Re-transfer or re-export the file to rule out network transmission corruption, especially if moving files between Windows Server 2025 shares or legacy systems.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original stored procedure or query that triggered Error 9424; successful execution without the error confirms the XML structure is now valid.
  • Alternative Solution: If the XML source cannot be modified immediately, wrap the parsing logic in a TRY...CATCH block to gracefully log the malformed record ID (rather than crashing the batch) and flag it for manual data cleansing.

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

Why This Error Happens

Error 9423 occurs when SQL Server’s native XML parser encounters malformed or non-well-formed XML data during a cast, insert, or OPENXML/FOR XML operation. This is typically caused by mismatched or unclosed tags, invalid special characters (like unescaped &, <, or >), or an incorrect text encoding declaration in the source XML string. It can also surface after a failed data migration where XML column data was truncated or corrupted during transfer.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XML Line

  • Note the exact line number (%d) reported in the error message; this points directly to the malformed section of the XML document.
  • Run the failing query in SQL Server Management Studio (SSMS) and extract the raw XML string into a VARCHAR(MAX) variable to inspect it manually.
  • Use SELECT LEN(@xmlVar) and string-splitting functions to isolate the specific line/character causing the break.

Step 2: Validate and Sanitize the XML Structure

  • Check for unescaped special characters; replace raw ampersands with &amp;, less-than symbols with &lt;, and greater-than symbols with &gt;.
  • Verify every opening tag <tag> has a corresponding closing tag </tag>.
  • Confirm the encoding declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual collation/encoding of the source file or table column.

Step 3: Repair the Source Data or File

  • If importing from a file path (e.g., via OPENROWSET(BULK...)), open the file in a text editor like Notepad++ on Windows Server 2025 to check for hidden BOM (Byte Order Mark) characters that often break parsing at line 1.
  • Re-save the file with UTF-8 encoding without BOM if the error points to the beginning of the document.
  • For data already in a table column, run an UPDATE statement using REPLACE() to strip invalid characters before re-attempting the CAST(... AS XML) operation.

Step 4: Check Application-Level Connection Settings

  • If the XML is being generated by an external application connecting to Windows Server 2025, verify the application’s connection string specifies the correct character set.
  • Ensure the SQL Server Native Client or ODBC driver version matches the requirements for SQL Server 2025 to prevent silent encoding corruption during transit.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original INSERT or SELECT statement with TRY_CAST(@xmlVar AS XML) instead of CAST; if the result returns NULL instead of an error, the sanitation was successful but further data cleaning is needed, whereas a valid XML output confirms the fix.
  • Alternative Solution: If manual sanitization is too complex for large datasets, import the data as NVARCHAR(MAX) first, use SQL Server’s OPENJSON or a Common Language Runtime (CLR) function to strip invalid characters programmatically, and then cast the cleaned string to the XML data type.

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

SQL Server 2025 Error 9421: XML Parsing Error Troubleshooting Guide

Why This Error Happens

Error 9421 occurs when SQL Server’s XML parser encounters malformed, incomplete, or improperly encoded XML data at a specific line number during a parsing operation. This typically results from truncated XML documents, invalid character encoding (such as mismatched UTF-8/UTF-16 byte order marks), unescaped special characters, or corrupted data passed into XML data type columns or OPENXML/sp_xml_preparedocument calls. It can also surface when an application writes incomplete XML payloads due to a failed transaction, network interruption, or buffer overflow during data transfer.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Source of the XML Data

  • Note the exact line number reported in the error message (e.g., “XML parsing: line 12, unclosed tag”).
  • Run the failing query in SQL Server Management Studio (SSMS) with SET SHOWPLAN_XML disabled to isolate the exact statement.
  • Use SELECT CAST(column_name AS NVARCHAR(MAX)) to extract and visually inspect the raw XML content causing the failure.

Step 2: Validate and Repair the XML Content

  • Copy the extracted XML into a validator (Visual Studio’s XML Editor or an online XML linter) to pinpoint unclosed tags, mismatched namespaces, or invalid entities.
  • Check for encoding mismatches — ensure the XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the source file or stream.
  • If the XML originates from an external file, re-export or regenerate it, ensuring the exporting application does not truncate output (common with large FOR XML or OPENROWSET(BULK...) operations).

Step 3: Correct Application or Import Logic

  • Review any OPENXML, sp_xml_preparedocument, or .nodes()/.value() XQuery calls in stored procedures for incorrect handling of large or streamed XML payloads.
  • If importing XML files via OPENROWSET(BULK 'C:\Data\import.xml', SINGLE_CLOB), confirm the file path is accessible to the SQL Server service account and that the file isn’t locked or partially written.
  • Increase timeout or buffer settings in the client application (e.g., ADO.NET CommandTimeout) if XML is being streamed and may be cut off mid-transfer.

Step 4: Rebuild or Re-insert Clean XML Data

  • If the XML is stored in a column with the xml data type, drop and recreate the affected row with validated, well-formed XML.
  • Run DBCC CHECKDB on the database if corruption is suspected at the page level, particularly if multiple unrelated XML columns are failing.
  • Restart the SQL Server 2025 service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER if the issue persists only in cached execution plans.

Alternative or Verification Steps

  • Re-run the original query or application process that triggered Error 9421 and confirm no exception is thrown; also validate output using SELECT ... FOR XML AUTO to ensure round-trip integrity.
  • As an alternative, wrap XML parsing calls in a TRY_CAST or TRY_CONVERT statement to gracefully handle malformed data without halting the entire batch, then log failures separately for manual review.

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

Why This Error Happens

Error 9422 occurs when SQL Server’s XML parser encounters malformed or incomplete XML data at a specific line number, indicating a structural violation of the XML schema (such as unclosed tags, mismatched elements, or invalid character encoding). This typically happens when data is truncated during transfer, corrupted during storage, or when an application generates non-compliant XML before inserting it into an XML-typed column. In some cases, it can also stem from encoding mismatches (UTF-8 vs UTF-16) between the client and SQL Server 2025 instance.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data

  • Run the query that triggered the error and capture the exact line number referenced in the error message.
  • Use SELECT CAST(YourXmlColumn AS NVARCHAR(MAX)) to extract the raw XML and visually inspect the reported line.
  • Check for unclosed tags, unescaped special characters (&, <, >), or missing root elements.

Step 2: Validate XML Structure Externally

  • Copy the extracted XML into a validator tool (e.g., Visual Studio XML Editor, Notepad++ XML plugin, or an online validator on an isolated/offline environment per security policy).
  • Confirm whether the issue is a single malformed character, an encoding declaration mismatch (e.g., <?xml version="1.0" encoding="UTF-8"?> when the actual content is UTF-16), or a truncated payload.
  • Fix the XML manually or regenerate it from the source system if corruption is confirmed.

Step 3: Correct the Source Application Logic

  • Review the application or ETL pipeline (SSIS package, API call, or stored procedure) generating the XML before insertion.
  • Ensure proper escaping of special characters using FOR XML PATH with TYPE directive correctly applied, or use XMLDATA/AUTO modes consistently.
  • Verify that any CONVERT or CAST operations to XML type are not truncating data due to NVARCHAR(MAX) vs NVARCHAR(n) mismatches.

Step 4: Re-Insert and Test Corrected Data

  • Replace the malformed XML with the corrected version using an UPDATE statement or re-run the import process.
  • Run SELECT * FROM sys.dm_exec_describe_first_result_set or a direct query against the column to confirm no error is raised.

Step 5: Check Collation and Encoding Settings

  • Confirm the database collation (SELECT DATABASEPROPERTYEX('YourDB', 'Collation')) matches the expected character set used by the source application.
  • Adjust client connection settings (e.g., SET TEXTSIZE, connection string Charset parameter) if encoding mismatches are causing invisible corruption.

Alternative or Verification Steps

  • Verify the fix by re-running the original query or stored procedure that failed; confirm no Error 9422 appears in SQL Server Logs (via SSMS → Management → SQL Server Logs) or Event Viewer (Windows Logs → Application) on Windows Server 2025.
  • If the error persists intermittently, enable XML Schema Collection validation (sys.xml_schema_collections) on the column to enforce structural integrity at the database level and catch malformed XML before it’s committed.