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

Troubleshooting Guide: SQL Server Error 2505 – “The device ‘%.*ls’ does not exist”

Why This Error Happens

This error occurs when a backup or restore operation references a logical or physical backup device name that SQL Server cannot locate in its system catalog. It typically happens because the backup device was never registered via sp_addumpdevice, was deleted, or the physical file path referenced by the device has been moved, renamed, or deleted from disk. It can also occur if a script references a device name with a typo or from a different server instance where the device metadata doesn’t exist locally.

Step-by-Step Resolution Guide

Step 1: Verify Existing Backup Devices

  • Open SQL Server Management Studio (SSMS) or a query window connected to the affected instance.
  • Run the following query to list all registered devices:
  SELECT name, physical_name, type FROM sys.backup_devices;
  • Confirm whether the device name referenced in your script or job actually exists in this result set.

Step 2: Check the Physical File Path on Disk

  • Navigate to the default backup directory, typically located at:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\
  • Confirm the .bak or .trn file referenced by the device still exists and has not been renamed or moved.
  • If the file is missing, check Windows Server 2025 backup/archive logs or any storage migration history for the file.

Step 3: Re-register the Backup Device (If Missing)

  • If the device was deleted or never created, re-add it using sp_addumpdevice:
  EXEC sp_addumpdevice 'disk', 'MyBackupDevice', 
  'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\MyBackup.bak';
  • Ensure the SQL Server service account has read/write permissions on the target folder (right-click folder > Properties > Security > confirm NT SERVICE\MSSQLSERVER has Modify rights).

Step 4: Correct the Script or Job Reference

  • If using a SQL Agent Job or maintenance plan, open the job step and verify the exact device name spelling matches sys.backup_devices.
  • Update any hardcoded device names in Transact-SQL scripts to match the verified name from Step 1.

Alternative or Verification Steps

  • Re-run the backup/restore command using the corrected device name or direct file path (e.g., BACKUP DATABASE ... TO DISK = 'C:\Backup\MyBackup.bak') instead of a logical device name to bypass the lookup entirely.
  • To verify the fix, execute RESTORE VERIFYONLY FROM MyBackupDevice; and confirm it completes without raising Error 2505.

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

Why This Error Happens

Error 2501 occurs when SQL Server’s query parser cannot locate the specified table, view, or object within the current database context, typically because the object was referenced without the correct schema prefix (e.g., dbo.TableName) or does not exist in the database the session is currently pointed to. This is frequently caused by a default schema mismatch for the executing user, a typo in the object name, or the object existing in a different database than the one currently selected. In some cases, this error surfaces after a migration or restore where system catalog views were not updated correctly.

Step-by-Step Resolution Guide

Step 1: Verify the Object Exists in the Correct Database

  • Open SQL Server Management Studio (SSMS) and confirm you are connected to the correct database instance.
  • Run SELECT name FROM sys.objects WHERE name LIKE '%YourTableName%'; to search across the catalog.
  • Check the USE [DatabaseName]; statement at the top of your script to ensure the context is correct.

Step 2: Check Schema Qualification and User Permissions

  • Explicitly qualify the object with its schema, e.g., SELECT * FROM dbo.YourTableName; instead of SELECT * FROM YourTableName;.
  • Run SELECT default_schema_name FROM sys.database_principals WHERE name = USER_NAME(); to confirm the default schema assigned to your login.
  • Grant SELECT permissions on the schema if the user lacks visibility: GRANT SELECT ON SCHEMA::dbo TO [YourUser];

Step 3: Rebuild or Refresh the System Catalog Cache

  • Clear the procedure cache to eliminate stale execution plans: DBCC FREEPROCCACHE;
  • Run sp_refreshview 'YourViewName'; if the error is triggered by a view referencing a renamed or altered table.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if cache corruption is suspected.

Step 4: Validate Database Integrity

  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out catalog corruption.
  • Review the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Log\ERRORLOG for related corruption warnings.
  • If corruption is found, restore from the last known good backup.

Alternative or Verification Steps

  • Re-run the original query after applying the schema fix; a successful result set with no Error 2501 confirms resolution.
  • If the issue persists, use sp_help 'YourTableName'; to display detailed metadata and confirm the object is fully registered in the current database’s system catalog.

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

Troubleshooting Guide: SQL Server Error 2502 — Memory Object List Dump Failure

Why This Error Happens

Error 2502 occurs when SQL Server’s internal DBCC MEMORYSTATUS or memory broker diagnostic routines attempt to enumerate the memory object list (MEMORYCLERK structures) while the server is under heavy concurrent memory pressure, causing a transient race condition between allocation and deallocation threads. This is typically triggered when multiple sessions request memory diagnostics simultaneously, or when a memory clerk is being resized/destroyed at the exact moment of the dump request. In most cases, this is a transient internal consistency check failure rather than actual corruption, though it can recur frequently if memory pressure persists or if there is an underlying resource governor misconfiguration.

Step-by-Step Resolution Guide

Step 1: Confirm Memory Pressure and Current State

  • Open SQL Server Management Studio (SSMS) and run DBCC MEMORYSTATUS; to capture a baseline snapshot.
  • Check sys.dm_os_memory_clerks and sys.dm_os_ring_buffers for RING_BUFFER_RESOURCE_MONITOR entries indicating memory pressure events.
  • Review Windows Event Viewer under Applications and Services Logs > Microsoft > SQL Server for correlating Event ID 2502 timestamps.

Step 2: Retry the Operation with Isolation

  • Close all other active SSMS query windows or monitoring tools that may be polling memory DMVs concurrently.
  • Re-run the diagnostic command alone: DBCC MEMORYSTATUS WITH NO_INFOMSGS;
  • If using PowerShell/sqlcmd for automation, add a retry-with-delay wrapper, for example:
  sqlcmd -S localhost -Q "DBCC MEMORYSTATUS" -t 30

Step 3: Adjust Max Server Memory Configuration

  • Open SQL Server Configuration Manager or use T-SQL:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max server memory (MB)', 16384;
  RECONFIGURE;
  • Set this value to leave at least 20-25% of total RAM free for the OS (e.g., on a 32 GB Windows Server 2025 box, cap SQL Server at 24 GB or lower).
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 4: Apply Latest Cumulative Update

  • Navigate to Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Verify current build number with SELECT @@VERSION; before and after patching.
  • Apply the update during a maintenance window, as several memory clerk race conditions are addressed in CU rollups.

Step 5: Rebuild Resource Governor Pools (If Applicable)

  • If using Resource Governor, run ALTER RESOURCE GOVERNOR RECONFIGURE; to flush stale pool configurations.
  • Check sys.dm_resource_governor_resource_pools for orphaned or misconfigured pools consuming excess memory clerks.

Alternative or Verification Steps

  • To verify the fix, run DBCC MEMORYSTATUS; three to five times consecutively under normal workload — the command should complete without Error 2502 appearing in the SQL Server error log.
  • If the issue persists, enable Trace Flag 2335 (increases memory diagnostic stability) at startup via SQL Server Configuration Manager Startup Parameters, then restart the service and re-test.

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

Troubleshooting Guide: SQL Server 2025 Error 2503 — “Successfully Deleted the Physical File”

Why This Error Happens

This message is typically informational rather than a true failure, logged when SQL Server’s database file autogrow/autoshrink or a manual DBCC SHRINKFILE operation removes an empty secondary data file. However, it surfaces as an unexpected error when a maintenance plan or shrink task tries to delete a file that is still referenced in the file group metadata, often due to a stale cached file handle or a permissions mismatch on the MSSQL\DATA directory. In some cases, this is triggered because Windows Server 2025’s updated NTFS ACL inheritance rules revoke delete permissions for the SQL Server service account mid-operation, leaving the database in an inconsistent state despite the file being physically removed.

Step-by-Step Resolution Guide

Step 1: Verify the Database File Group Consistency

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no orphaned file references remain.
  • Check sys.master_files and sys.database_files for mismatched entries pointing to the deleted file.

Step 2: Reset Service Account Permissions on the Data Directory

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA (adjust instance folder name as needed).
  • Right-click the folder, go to Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • Apply the permissions recursively and restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Clear Stale File Handles and Restart the Instance

  • Use Process Explorer (Sysinternals) to confirm no lingering file handles reference the deleted .ndf or .mdf file.
  • If a handle is found, close it manually or restart the SQL Server Windows Service to release it.
  • Re-run the shrink or delete operation using ALTER DATABASE YourDatabaseName REMOVE FILE LogicalFileName; to cleanly finalize the removal.

Step 4: Review SQL Server Error Logs for Correlated Events

  • Open C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Search for Event ID 2503 entries and cross-reference the timestamp with Windows Event Viewer (Applications and Services Logs > MSSQL Server).
  • Confirm no concurrent autogrowth or backup job was interfering with the file deletion process.

Alternative or Verification Steps

  • Run sp_helpdb YourDatabaseName and confirm the file list no longer shows the removed file, with no error flags in the status column.
  • If the error persists, detach and reattach the database (sp_detach_db / CREATE DATABASE ... FOR ATTACH) to force SQL Server to rebuild its internal file metadata cache.

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

Why This Error Happens

Error 2399 is typically thrown by SQL Server Analysis Services (SSAS) when the XML metadata engine encounters an attribute in a Data Definition Language (DDL) script or ASSL (Analysis Services Scripting Language) file that does not match the expected data type defined in the schema. This usually occurs due to a corrupted or manually edited .xmla deployment script, a mismatched Compatibility Level between the Analysis Services instance and the project file, or a failed/interrupted metadata migration during an upgrade to SQL Server 2025. In most cases, the root cause is a type mismatch (e.g., a string value passed where an integer or GUID was expected) within the cube, dimension, or data source definition.

Step-by-Step Resolution Guide

Step 1: Validate the XMLA/ASSL Script Integrity

  • Open the deployment script (.xmla or .asdatabase file) in SQL Server Management Studio (SSMS) or a text editor.
  • Search for the specific attribute named in the error message (e.g., <ID>, <Type>, or <DataType>) and confirm the value matches the expected schema type (string, integer, boolean, or GUID).
  • Correct any manually inserted values that do not conform to the ASSL schema definitions found in C:\Program Files\Microsoft SQL Server\160\Tools\Binn\VSShell\Common7\IDE\...\Microsoft.AnalysisServices.xsd.

Step 2: Check Compatibility Level Alignment

  • Right-click the SSAS database in SSMS, select Properties, and verify the CompatibilityLevel matches your SQL Server 2025 instance (should be 1710 or higher).
  • If deploying from Visual Studio/SSDT, open the project properties and ensure the Deployment Server Edition and Compatibility Level match the target server.
  • Redeploy the project after aligning these values to avoid legacy attribute types being pushed into a newer engine.

Step 3: Rebuild the Corrupted Object Definition

  • Navigate to the specific dimension, measure group, or data source referenced in the error stack trace.
  • In SSDT, right-click the affected object and select Delete, then recreate it manually using the GUI wizard rather than copy-pasting XML.
  • Run Process Full on the object via SSMS:
  <Process xmlns="http://schemas.microsoft.com/analysisservices/2020/engine">
    <Object>
      <DatabaseID>YourDatabaseID</DatabaseID>
    </Object>
    <Type>ProcessFull</Type>
  </Process>
  • Confirm the Windows Event Viewer (Applications and Services Logs > SQL Server Analysis Services) no longer logs Event ID 2399 after processing.

Step 4: Restart the Analysis Services Instance

  • Open Services.msc on Windows Server 2025, locate SQL Server Analysis Services (MSSQLSERVER), and restart the service to clear any cached metadata locks.
  • Re-attempt the deployment or query that originally triggered the error.

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM $SYSTEM.DISCOVER_XML_METADATA in an MDX query window to confirm the object schema now validates without throwing type exceptions.
  • If the error persists, restore the SSAS database from a last-known-good backup (.abf file) taken prior to the SQL Server 2025 upgrade, then re-apply only the verified schema changes incrementally.

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

Troubleshooting Guide: SQL Server Error 2431

Why This Error Happens

Error 2431 in Microsoft SQL Server 2025 typically occurs when the database engine encounters an inconsistency while attempting to read or allocate a page structure, often tied to corrupted system catalog metadata or a damaged database file header. This can be triggered by improper shutdowns, storage-level corruption, or incomplete I/O operations during a failover on Windows Server 2025 environments. In some cases, it also surfaces when SQL Server’s internal resource monitor cannot reconcile memory-mapped file structures due to permission restrictions on the data directory.

Step-by-Step Resolution Guide

Step 1: Verify Database Integrity

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to identify the scope of corruption.
  • Review the output for allocation or consistency errors tied to specific page IDs referenced in Error 2431.

Step 2: Check File and Folder Permissions

  • Navigate to the default data directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA.
  • Right-click the .mdf and .ldf files, select Properties > Security, and confirm the SQL Server service account has Full Control.
  • Restart the SQL Server service via services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 3: Repair or Restore the Database

  • If corruption is confirmed, attempt DBCC CHECKDB ('YourDatabaseName') WITH REPAIR_REBUILD; first, as it does not risk data loss.
  • If errors persist, restore the most recent clean backup using SSMS’s Restore Database wizard or the RESTORE DATABASE T-SQL command.
  • Ensure the backup file path is accessible and not blocked by Windows Defender or third-party antivirus software.

Step 4: Validate Windows Server Storage Health

  • Open Event Viewer and check the System log under “Disk” and “Ntfs” sources for related hardware I/O warnings.
  • Run chkdsk C: /f /r from an elevated Command Prompt and schedule a restart if prompted.
  • Confirm the underlying storage (physical disk, SAN, or virtual disk) is reporting no SMART errors.

Alternative or Verification Steps

  • After applying fixes, re-run DBCC CHECKDB on the affected database to confirm zero allocation or consistency errors are returned.
  • If Error 2431 reoccurs immediately after service restart, consider rebuilding the master database using SQL Server Setup’s repair option, as corruption may reside in system-level metadata rather than the user database.

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

Why This Error Happens

Error 2397 occurs when SQL Server rejects an identifier (such as a table, column, variable, or constraint name) because it exceeds the maximum allowed length of 128 characters. This typically happens due to dynamically generated SQL scripts, automated schema migration tools, or ORM frameworks that concatenate long naming conventions (e.g., prefixes, GUIDs, or environment tags) without validation. It can also surface when linked server or distributed query naming conventions produce overly long three-part or four-part object names.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Identifier

  • Capture the full T-SQL statement from SQL Server Management Studio (SSMS) or the application log that triggered Error 2397.
  • Run the query manually in SSMS to isolate which specific identifier (table, column, alias, or constraint) is too long.
  • Use SELECT LEN('YourIdentifierName') to confirm it exceeds 128 characters.

Step 2: Shorten the Identifier Name

  • Rename the object using an abbreviated naming convention (e.g., truncate prefixes or remove redundant environment/version tags).
  • For auto-generated constraint names (common in EF Core or Hibernate), configure the ORM to use shorter naming templates instead of full namespace paths.
  • Example fix in T-SQL:
EXEC sp_rename 'dbo.VeryLongOriginalTableNameExceedingLimit', 'ShortTableName';

Step 3: Update Schema Generation Scripts or Migration Tools

  • If the identifier is generated dynamically (e.g., via Entity Framework migrations, Liquibase, or Flyway), edit the naming strategy/template in the tool’s configuration file.
  • On Windows Server 2025, check scheduled SQL Agent jobs under SQL Server Agent > Jobs for scripts that programmatically concatenate names; add a truncation function (e.g., LEFT(@identifier, 128)) before execution.
  • Redeploy the corrected migration script.

Step 4: Validate Linked Server and Synonym References

  • If the error originates from a linked server query, check sys.servers and reduce the length of server aliases or synonym names used in four-part naming (Server.Database.Schema.Object).
  • Recreate synonyms with shorter names using CREATE SYNONYM.

Alternative or Verification Steps

  • Re-run the original failing script or stored procedure in SSMS and confirm Error 2397 no longer appears in the Messages tab.
  • If the issue persists, enable SQL Server Profiler or Extended Events to trace the exact batch text at the moment of failure, then cross-check identifier lengths programmatically using a PowerShell script that scans your schema metadata (INFORMATION_SCHEMA.COLUMNS, sys.objects) for names nearing the 128-character limit.

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

Troubleshooting Guide: SQL Server Error 2398 – Duplicate ID Value Found

Why This Error Happens

Error 2398 occurs when SQL Server’s replication or metadata subsystem encounters two or more objects (such as articles, publications, or system catalog entries) sharing an identical identifier that should be unique. This typically results from corrupted system tables, improperly restored replication metadata, or manual tampering with system catalog views like sysarticles or sysobjects. It can also surface after a failed upgrade migration to SQL Server 2025 where GUID or ID generation collided due to an interrupted transaction log replay.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Duplicate ID

  • Run the following query to inspect replication metadata for conflicting IDs:
  SELECT artid, name, COUNT(*) 
  FROM dbo.sysarticles 
  GROUP BY artid, name 
  HAVING COUNT(*) > 1;
  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact object name referenced in the %ls placeholder.
  • Cross-reference the ID with sys.objects and sys.indexes to confirm whether the conflict is in user data or system catalogs.

Step 2: Remove or Reinitialize the Conflicting Replication Article

  • If the issue stems from replication, drop and re-add the offending article using SQL Server Management Studio (SSMS) or:
  EXEC sp_droparticle @publication = 'YourPubName', @article = 'ConflictingArticleName';
  • Reinitialize the subscription to force a clean snapshot:
  EXEC sp_reinitsubscription;
  • Ensure no orphaned entries remain in distribution.dbo.MSarticles on the Distributor instance.

Step 3: Run Database Consistency Checks

  • Execute DBCC CHECKDB on the affected database to rule out underlying corruption:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is confirmed, restore the database from the last known good backup rather than attempting repair, since REPAIR_ALLOW_DATA_LOSS can worsen replication ID conflicts.
  • Validate Windows Server 2025 storage drivers and disk health via Get-PhysicalDisk | Get-StorageReliabilityCounter to rule out disk-level corruption as the root cause.

Step 4: Rebuild Replication Topology (If Necessary)

  • If duplicates persist across multiple articles, drop the entire publication and recreate it:
  EXEC sp_droppublication @publication = 'YourPubName';
  • Recreate the publication and subscriptions from scratch using the Replication Wizard in SSMS, ensuring unique artid values are regenerated automatically.

Alternative or Verification Steps

  • After applying fixes, re-run the replication monitor (replmonitor) in SSMS and confirm no Error 2398 entries appear in the Agent history for at least one full synchronization cycle.
  • If the error persists, uninstall and reinstall the SQL Server 2025 Replication components via “Add or Remove Programs” on Windows Server 2025, then restore replication configuration from a scripted .sql backup of your topology.

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

Troubleshooting Guide: SQL Server Error 2395 — “There is no function ‘%ls:%ls()'”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to resolve a call to a CLR (Common Language Runtime) or extended function that does not exist within the specified assembly or namespace, typically due to a mismatched or corrupted assembly registration. It is commonly triggered after a partial upgrade, a missing assembly reference in sys.assembly_modules, or when a function signature was altered in code but not redeployed to the database. Incompatibility between the .NET runtime version used to compile the assembly and the CLR version hosted by SQL Server 2025 can also cause this lookup to fail.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly and Function Metadata

  • Run SELECT * FROM sys.assembly_modules; to confirm the function and assembly name referenced in the error actually exist.
  • Cross-check the exact namespace and method casing against your source project, since CLR function names are case-sensitive.
  • Confirm the assembly is marked as VISIBLE = ON if it is being called externally.

Step 2: Re-register or Redeploy the CLR Assembly

  • Drop the outdated assembly using DROP ASSEMBLY [YourAssemblyName]; (ensure no dependent functions are active first).
  • Rebuild the DLL in Visual Studio 2022/2025 targeting the correct .NET Framework version supported by SQL Server 2025 (typically .NET Framework 4.8.1 for CLR integration, not .NET Core/5+).
  • Re-import the assembly: CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Recreate the function mapping: CREATE FUNCTION dbo.YourFunction (...) RETURNS ... AS EXTERNAL NAME [YourAssemblyName].[Namespace.ClassName].[MethodName];

Step 3: Validate CLR Configuration on the Server

  • Ensure CLR integration is enabled: sp_configure 'clr enabled', 1; RECONFIGURE;
  • On Windows Server 2025/Windows 11, verify that the .NET Framework 4.8.1 feature is installed via Server Manager > Add Roles and Features > .NET Framework 4.8 Features.
  • Restart the SQL Server service (services.msc > SQL Server (MSSQLSERVER) > Restart) to clear any cached assembly metadata.

Step 4: Check for Version Mismatch Across Environments

  • If this function worked in a different environment (Dev/QA), compare the assembly’s file version using Get-Item "C:\SQLAssemblies\YourAssembly.dll" | Select-Object VersionInfo in PowerShell.
  • Redeploy the exact matching DLL version to Production to eliminate drift.

Alternative or Verification Steps

  • To verify the fix, execute the failing query or stored procedure again and confirm no Error 2395 is raised; also query sys.assembly_modules to ensure the function-to-assembly mapping resolves correctly.
  • If the error persists, as a fallback, uninstall and reinstall the CLR assembly entirely using ALTER ASSEMBLY [YourAssemblyName] WITH UNCHECKED DATA to force a full metadata refresh, then redeploy from a clean build.

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

Troubleshooting Guide: SQL Server Error 2396 — “%sAttribute may not appear outside of an element”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to parse a malformed XML document or an XML-based configuration file (such as an SSIS package, Policy-Based Management policy, or an XML column payload) where an attribute is defined outside the scope of a valid parent element. This is typically caused by corrupted XML metadata, a manually edited .dtsx or .xml file with broken tag nesting, or truncated data being passed into an XML typed column via OPENROWSET or sp_xml_preparedocument. In some cases, this also surfaces when Windows Server 2025 security policies interfere with how the MSXML parser (used internally by the Database Engine) reads XML streams during deserialization.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Document

  • Open the offending XML file (configuration file, SSIS package, or XML variable source) in a validating editor like Visual Studio 2025 or XML Notepad.
  • Look specifically for attributes placed after a closing tag (</element> attribute="value") or attributes floating at the root level without a parent element.
  • Run a quick syntax check using PowerShell: [xml](Get-Content "C:\Path\To\File.xml") — if this throws an error, the file is confirmed malformed.

Step 2: Repair or Re-Export the Corrupted Metadata

  • If the error originates from an SSIS package, re-deploy the package from the original Visual Studio project rather than a manually patched .dtsx file.
  • If the issue is tied to a Policy-Based Management (PBM) policy, navigate to Management > Policy Management > Policies in SSMS, right-click the suspect policy, and select Export Policy to regenerate clean XML.
  • For data being inserted into an XML column, verify the source application isn’t truncating the payload mid-stream; check buffer limits in your ETL or API layer.

Step 3: Clear Corrupted Cache and Restart Services

  • On Windows Server 2025, navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA and check for orphaned temp XML schema cache files.
  • Restart the SQL Server service via PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force
  • Restart SQL Server Agent as well if the error was triggered by a scheduled job: Restart-Service -Name 'SQLSERVERAGENT' -Force

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

  • If a custom XML Schema Collection (XSD) is tied to the column, drop and recreate it:
  • DROP XML SCHEMA COLLECTION dbo.YourSchemaName;
  • Re-import the corrected, validated schema using CREATE XML SCHEMA COLLECTION.

Alternative or Verification Steps

  • To verify the fix, re-run the original operation (SSIS package execution, policy evaluation, or query) and confirm Error 2396 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • As an alternative, if re-validating XML is not feasible, isolate the problematic record or file and process it through an external XML linter (like xmllint --noout file.xml on a WSL instance) before reintroducing it to SQL Server.

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

Why This Error Happens

Error 2393 occurs when SQL Server attempts to parse an XML Schema Collection (XSD) that contains a malformed <xs:list> element. Per the W3C XML Schema specification, any list simple type definition must declare its item type using either the itemType attribute or by nesting a simpleType child element directly inside the list tag. When neither is present—often due to a corrupted import file, a manual editing mistake, or an incomplete schema export from a third-party ORM/ETL tool—the SQL Server XML parser rejects the registration of the schema collection entirely.

Step-by-Step Resolution Guide

Step 1: Locate the Offending XSD File or Script

  • Identify the exact CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement referenced in the error’s Location: '%ls' placeholder.
  • Open the source .xsd file (commonly found under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Schemas\ or wherever your deployment scripts store them) in a text editor like VS Code.
  • Search for all instances of <xs:list to narrow down the problematic node.

Step 2: Correct the Malformed list Definition

  • Add a valid itemType attribute pointing to an existing simple type, for example: <xs:list itemType="xs:integer"/>.
  • Alternatively, nest a simpleType child directly, for example:
<xs:list>
  <xs:simpleType>
    <xs:restriction base="xs:string"/>
  </xs:simpleType>
</xs:list>
  • Save the corrected file using UTF-8 encoding to avoid introducing hidden BOM characters that can trigger secondary parsing errors.

Step 3: Re-Import the Schema Collection

  • Drop the existing broken collection if it partially registered: DROP XML SCHEMA COLLECTION dbo.YourSchemaName;
  • Re-run the corrected CREATE XML SCHEMA COLLECTION dbo.YourSchemaName AS '<xsd content>'; statement via SQL Server Management Studio (SSMS) or sqlcmd.
  • Confirm no other <xs:list>, <xs:union>, or nested complex type elements in the same file reference the broken type definition.

Step 4: Validate Server and OS-Level XML Parser Dependencies

  • On Windows Server 2025 / Windows 11, ensure the MSXML6 component is not corrupted by running sfc /scannow from an elevated Command Prompt.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to clear any cached schema parsing state.

Alternative or Verification Steps

  • Run SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; to confirm the schema registered successfully without errors.
  • If the error persists, validate the XSD independently using an external tool (e.g., xmllint --schema or Visual Studio’s XML Schema Explorer) before attempting to re-import it into SQL Server, as this isolates whether the issue is SQL Server-specific or a genuinely invalid XSD file.

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

Why This Error Happens

Error 2394 occurs when SQL Server’s query optimizer references a system function (often tied to replication, CDC, or compatibility-level features) that cannot be resolved in the current database context. This typically happens after a database is restored or upgraded to SQL Server 2025 with an incompatible or corrupted system object catalog, or when a user-defined function referenced in a view/procedure was dropped or never properly deployed. It can also surface when the database compatibility level doesn’t match the installed SQL Server version, causing internal metadata function mismatches.

Step-by-Step Resolution Guide

Step 1: Verify the Function Exists in the Target Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to confirm the function is missing or misnamed:
SELECT * FROM sys.objects WHERE type IN ('FN','IF','TF') AND name LIKE '%<function_name>%';
  • If no rows return, the function was dropped, never migrated, or exists in a different schema.

Step 2: Check Database Compatibility Level

  • Right-click the database in SSMS, go to Properties > Options, and confirm the Compatibility Level matches SQL Server 2025 (160 or higher).
  • Alternatively, run:
ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 160;
  • Mismatched compatibility levels often cause system functions to resolve incorrectly.

Step 3: Run DBCC CHECKDB to Rule Out Corruption

  • Execute:
DBCC CHECKDB ('YourDB') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review output for corrupted system catalog views or orphaned metadata entries.
  • If corruption is found, restore from a known good backup rather than attempting repair on system objects.

Step 4: Rebuild or Redeploy Missing Objects

  • If the function is part of a third-party schema (replication, CDC, or custom framework), redeploy the original creation script located in your deployment repository or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Install\.
  • For CDC-related errors specifically, run:
EXEC sys.sp_cdc_disable_db;
EXEC sys.sp_cdc_enable_db;
  • This resets internal CDC function bindings that commonly trigger Error 2394.

Step 5: Restart SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart.
  • This clears cached execution plans that may be referencing the stale function signature.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 2394 and confirm it executes without errors.
  • If the issue persists, restore the database to a pre-upgrade backup and re-apply the SQL Server 2025 upgrade using the Data Migration Assistant to properly map deprecated or renamed system functions.

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

Troubleshooting Guide: SQL Server Error 2391 – “Redefining XSD Schemas is Not Supported”

Why This Error Happens

This error occurs when a CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement attempts to add a schema component (such as a complex type, element, or attribute) that already exists within the target namespace of an existing XML Schema Collection. SQL Server 2025 enforces strict immutability on XSD definitions once they are registered, meaning you cannot silently overwrite or redefine a type that was previously committed to the collection. This typically happens during application deployment scripts or ORM migrations where a schema is pushed multiple times without first checking for existing definitions or properly versioning the namespace.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Schema Collection

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025.
  • Run the following query to locate the specific collection causing the conflict:
  SELECT xsc.name, xsc.xml_collection_id, s.name AS schema_owner
  FROM sys.xml_schema_collections xsc
  JOIN sys.schemas s ON xsc.schema_id = s.schema_id;
  • Note the xml_collection_id and the specific namespace mentioned in the Error 2391 message detail.

Step 2: Drop and Recreate the Schema Collection (Rather Than Redefining)

  • Since “Redefining” is unsupported, you must explicitly drop the old definition before pushing the new one.
  • Use the following syntax to safely remove the old schema before your deployment script runs:
  IF EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName')
  DROP XML SCHEMA COLLECTION YourSchemaName;
  • Re-run your original CREATE XML SCHEMA COLLECTION script immediately after the drop completes.

Step 3: Update Deployment Scripts to Use ALTER Correctly

  • If you are trying to add new types to an existing collection (rather than changing existing ones), ensure you are using ALTER XML SCHEMA COLLECTION ADD with net-new, non-conflicting namespace components.
  • Check your CI/CD pipeline (e.g., Azure DevOps or GitHub Actions) configuration files located in your deployment repository to ensure the schema migration step includes a “drop-if-exists” check rather than a direct “create” command on every run.

Step 4: Check for Dependent Objects

  • Before dropping the schema collection in Step 2, verify no existing tables or XML-typed columns are bound to it, as this will throw a dependency error.
  • Run sp_depends 'YourSchemaName' or query sys.xml_schema_collections dependencies to identify and temporarily unbind affected columns if necessary.

Alternative or Verification Steps

  • Verification: Re-run the deployment script a second time to confirm the CREATE XML SCHEMA COLLECTION command completes without throwing Error 2391, confirming the drop/recreate cycle is working.
  • Alternative: If dropping the schema is not feasible due to production dependencies, create a new schema collection with a versioned name (e.g., MySchema_v2) and update the application’s table definitions to point to the new collection instead of overwriting the old one.

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

Why This Error Happens

Error 2392 ('%ls::' is not a valid axis) is thrown by the SQL Server Analysis Services (SSAS) MDX parser when it encounters a malformed axis specifier in a query—commonly caused by a corrupted or incorrectly generated MDX string from a reporting layer (SSRS, Excel PivotTables, or a third-party BI tool). This typically happens after an OS or driver update changes how the client library formats axis syntax (e.g., ON COLUMNS, ON ROWS, ON 0), or when a double-colon (::) placeholder is left in a dynamically generated query template. It can also surface after upgrading to Windows Server 2025/Windows 11 if the MSOLAP provider or ADOMD.NET client library version mismatches the SSAS engine version.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Profiler or enable Query Log on the SSAS instance (Server Properties → Log → Query Log).
  • Reproduce the error and capture the exact MDX statement that triggered Event ID 2392.
  • Look specifically for axis clauses that contain stray characters like ::, missing axis numbers, or empty ON clauses.

Step 2: Correct the MDX Axis Syntax

  • Open the query in SQL Server Management Studio (SSMS) MDX query window.
  • Replace any malformed axis reference (e.g., SELECT {[Measures].[Sales]} ON %ls:: ) with a valid axis definition such as ON COLUMNS or ON 0.
  • If the query is generated dynamically (via SSRS dataset or custom app), check the report’s query-builder template for unresolved placeholder tokens (%ls, {0}, etc.) that failed to substitute correctly.

Step 3: Update and Realign Client Libraries

  • Verify the installed ADOMD.NET and MSOLAP provider versions match your SQL Server 2025 Analysis Services build.
  • Path to check: C:\Program Files\Microsoft.NET\ADOMD.NET\<version>\
  • Reinstall the matching redistributable from the SQL Server 2025 Feature Pack if versions are mismatched.
  • Restart the SQL Server Analysis Services (SSAS) service via services.msc or:
  net stop MSSQLServerOLAPService
  net start MSSQLServerOLAPService

Step 4: Rebuild or Refresh Cube Definitions

  • If the error persists only on specific cubes, reprocess the affected cube fully (Full Process) via SSMS → right-click cube → Process.
  • Rule out metadata corruption by validating the cube’s XMLA definition for broken axis tags under <Axes> in the cube script.

Alternative or Verification Steps

  • Re-run the original report or query that failed and confirm Event Viewer (Applications and Services Logs → SQL Server Analysis Services) no longer logs Event ID 2392.
  • As a fallback, export the MDX query to a .mdx file, manually validate syntax using the MDX Query Designer in SSMS, and re-import it into the reporting tool once confirmed error-free.

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

Troubleshooting Guide: SQL Server Error 2389 — “Requires a Singleton (or Empty Sequence)”

Why This Error Happens

Error 2389 occurs when an XQuery or XPath expression executed against an xml data type column returns multiple nodes, but the calling function (such as value()) expects a single scalar result or an empty sequence. This typically happens due to poorly constrained XPath predicates, malformed XML schema collections, or queries written against XML data that has grown to include unexpected repeating elements. It is a logical/query design issue rather than a corruption or permissions issue, but it can also surface after an in-place upgrade to SQL Server 2025 if legacy XQuery syntax is no longer being evaluated the same way against updated XML indexes.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement from the application trace, SQL Server error log, or Extended Events session.
  • Look specifically for .value(), .exist(), or .query() method calls on an xml typed column or variable.
  • Example of a problematic pattern:
  SELECT XmlCol.value('(/Root/Item)[1]/text()[1]', 'nvarchar(100)')

Step 2: Correct the XPath to Enforce a Singleton

  • Add explicit positional predicates to force a single-node result instead of a node-set.
  • Rewrite the query using array indexing syntax, for example:
  SELECT XmlCol.value('(/Root/Item)[1]', 'nvarchar(100)')

instead of:

  SELECT XmlCol.value('/Root/Item', 'nvarchar(100)')
  • If multiple nodes are expected, switch to .nodes() combined with CROSS APPLY to shred results into rows rather than forcing a scalar extraction.

Step 3: Validate the Underlying XML Schema Collection

  • Open SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and run:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Confirm the schema does not allow unbounded repeating elements (maxOccurs="unbounded") where your application logic assumes a single occurrence.
  • If necessary, update the XML Schema Collection definition using ALTER XML SCHEMA COLLECTION to tighten the maxOccurs constraint.

Step 4: Rebuild XML Indexes (If Applicable)

  • Navigate to the affected table in SSMS under Databases > [YourDB] > Tables > [YourTable] > Indexes.
  • Right-click the Primary XML Index and select Rebuild to ensure the index reflects current document structure after schema or data changes:
  ALTER INDEX ALL ON dbo.YourTable REBUILD;
  • This ensures stale index statistics aren’t contributing to inconsistent query evaluation under the new SQL Server 2025 query optimizer.

Alternative or Verification Steps

  • Re-run the corrected query in a test environment using SET SHOWPLAN_XML ON to confirm the execution plan no longer throws Error 2389 and returns a single scalar value.
  • If the error persists intermittently, use .query() first to inspect the raw node-set being returned (SELECT XmlCol.query('/Root/Item')) to visually confirm how many nodes match your XPath before finalizing the .value() expression.

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

Troubleshooting Guide: SQL Server Error 2390 – “Top-level %s nodes are not supported”

Why This Error Happens

This error typically occurs when SQL Server’s XML parser encounters an XML document or schema definition that contains multiple top-level nodes, or a top-level node type (such as a DTD declaration or processing instruction) that is not supported by the SQL Server XML engine. It is commonly triggered during XML schema collection imports, SSIS package execution, or when application code passes malformed XML into an XML-typed column or OPENXML/sp_xml_preparedocument call. This can also surface after an in-place upgrade to SQL Server 2025 on Windows Server 2025, where stricter XML parsing validation was introduced compared to legacy engines.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Document

  • Open the XML file or payload causing the error in a text editor or XML validator (e.g., Visual Studio, Notepad++ with XML plugin).
  • Confirm there is only one root-level element; SQL Server’s XML type requires a single top-level node.
  • Remove any extraneous top-level comments, multiple root elements, or stray processing instructions outside the root node.

Step 2: Check for Unsupported DTD or Processing Instructions

  • Search the XML for <!DOCTYPE ...> declarations — SQL Server’s XML parser does not support DTDs at the top level.
  • Strip out any <?xml-stylesheet?> or custom processing instructions placed before or after the root element.
  • If using sp_xml_preparedocument, ensure the input string passed is a fully well-formed single-document XML, not a fragment with multiple siblings.

Step 3: Review the Import/Integration Pipeline

  • If using SSIS, open the package in SQL Server Data Tools and inspect the XML Source component configuration.
  • Check the XSD/Schema Collection referenced by CREATE XML SCHEMA COLLECTION for multiple top-level <xs:schema> definitions and consolidate them into one.
  • Update any .NET or PowerShell ingestion scripts to wrap multi-record payloads in a single enclosing root element before insertion.

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog and confirm the instance is running the latest Cumulative Update (CU) for SQL Server 2025.
  • Run the following in SSMS to check the current build:
  • SELECT @@VERSION;
  • Install any pending CU via Windows Server 2025’s Server Manager or the standalone SQL Server Installer, then restart the MSSQLSERVER service.

Step 5: Re-test the XML Operation

  • Re-run the original INSERT, CREATE XML SCHEMA COLLECTION, or SSIS task against the corrected XML file.
  • Monitor the SQL Server Error Log (Management > SQL Server Logs in SSMS) to confirm Error 2390 no longer appears.

Alternative or Verification Steps

  • Verify the fix by executing SELECT CAST(@XmlVariable AS XML); against the corrected payload in a test query window — it should return without error.
  • If the issue persists, use sp_xml_removedocument to clear any cached XML document handles, then reattempt with a freshly validated XML fragment to rule out memory/handle corruption.

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

Troubleshooting Guide: SQL Server Error 2387 — “Cannot have both ‘type’ and ‘ref’ attributes”

Why This Error Happens

This error occurs when SQL Server parses an XML Schema Collection (XSD) definition, typically during CREATE XML SCHEMA COLLECTION or when validating XML data against a registered schema. The underlying XSD file contains an element or attribute declaration that illegally specifies both a type attribute and a ref attribute simultaneously, which violates the W3C XML Schema specification since these two attributes are mutually exclusive. This is almost always caused by a hand-edited or auto-generated schema file that wasn’t validated before being imported into SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema File

  • Locate the exact XML Schema Collection referenced in the error’s Location: '%ls' placeholder — this points to the namespace or file path of the problematic schema.
  • Run the following query to find the collection in your database:
  SELECT name, xml_schema_namespace, XML_SCHEMA_NAMESPACE('dbo', name) AS SchemaBody
  FROM sys.xml_schema_collections;
  • Export the schema body to a .xsd file using SQL Server Management Studio (SSMS) or bcp for manual inspection.

Step 2: Correct the Conflicting Attributes in the XSD

  • Open the exported .xsd file in a text editor or XML IDE (such as Visual Studio or VS Code with an XML extension).
  • Search for any <xs:element> or <xs:attribute> tag that contains both type="..." and ref="..." on the same line, for example:
  <xs:element name="Customer" type="CustomerType" ref="BaseCustomer" />
  • Remove one of the two attributes based on intended design: use ref only if the element is reusing a globally declared element, or use type only if you are defining the element’s type inline.
  • Save the corrected file as schema_fixed.xsd.

Step 3: Validate the XSD Before Re-Importing

  • On Windows Server 2025 or Windows 11, use the built-in xsd.exe utility (part of the .NET SDK) to validate syntax:
  xsd.exe schema_fixed.xsd
  • Alternatively, open the file in Visual Studio and check the “Error List” pane for schema validation errors before proceeding.
  • Ensure no other elements in the file share the same conflict by searching globally for ref= and cross-referencing nearby type= attributes.

Step 4: Drop and Recreate the XML Schema Collection

  • Drop the broken schema collection in SQL Server:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Recreate it using the corrected file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
  AS N'<paste contents of schema_fixed.xsd here>';
  • Confirm the command completes without throwing Error 2387 or related parsing errors.

Step 5: Restart Dependent Services (If Applicable)

  • If the schema collection is used by SSIS packages, linked applications, or SQL CLR procedures, restart the SQL Server service to clear any cached schema metadata:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Re-run any ETL jobs or applications that previously failed due to this error.

Alternative or Verification Steps

  • Verify the fix by querying sys.xml_schema_collections again and attempting to insert or validate a sample XML document against the schema using CAST(@xml AS XML) with the WITH SCHEMA clause — it should succeed without errors.
  • If the issue persists across multiple schema collections, consider using the Microsoft XML Schema Definition Tool (xsd.exe /validate) in a batch script to scan all exported .xsd files in bulk and flag conflicting type/ref attributes before any future imports.

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

Why This Error Happens

Error 2388 (“Invalid element occurrence”) typically occurs when SQL Server 2025 parses a malformed or corrupted XML/structured configuration element during metadata operations, such as DBCC commands, replication schema parsing, or Service Broker message validation. This often stems from a schema definition that violates the expected occurrence constraints (minOccurs/maxOccurs) in an internal XSD validation layer. It can also surface when a corrupted system catalog entry or a damaged configuration file passes malformed structural data to the SQL engine.

Step-by-Step Resolution Guide

Step 1: Identify the Source Operation

  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact statement or stored procedure that triggered Error 2388.
  • Run EXEC sp_readerrorlog 0, 1, 'Error: 2388'; in SQL Server Management Studio (SSMS) to pinpoint the timestamp and session ID.
  • Cross-reference the session ID with sys.dm_exec_requests to identify the offending query.

Step 2: Validate and Repair the Schema/XML Structure

  • If the error originates from an XML column or Service Broker message, run a validation check:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Drop and recreate the XML schema collection if it shows invalid occurrence constraints:
  DROP XML SCHEMA COLLECTION YourSchemaName;
  • Re-import a clean, validated XSD from your source control or backup.

Step 3: Run Consistency Checks on the Database

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out catalog corruption.
  • If corruption is found, review repair options (REPAIR_REBUILD before REPAIR_ALLOW_DATA_LOSS) in a maintenance window.
  • On Windows Server 2025/Windows 11, confirm the underlying storage volume isn’t reporting disk errors via Event Viewer > Windows Logs > System.

Step 4: Update SQL Server 2025 Cumulative Update

  • Open SQL Server Setup or use winget upgrade Microsoft.SQLServer.2025 to confirm you’re on the latest Cumulative Update (CU), since element-occurrence parsing bugs are frequently patched.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after installation.

Alternative or Verification Steps

  • Re-run the original query/operation that threw Error 2388; if it completes without the message, the schema/catalog fix was successful.
  • If the error persists, restore the affected database object (table, XML schema, or stored procedure) from a known-good backup taken before the corruption was introduced.

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

Troubleshooting Guide: SQL Server Error 2385 — Invalid Target Namespace Specified

Why This Error Happens

Error 2385 typically occurs when SQL Server 2025 attempts to process an XML-related operation (such as WMI-based queries, SQL Server Agent configuration, or XML schema validation) and encounters a namespace reference that does not match any registered or expected schema definition. This often results from corrupted WMI repository data, outdated or mismatched XML schema collections, or misconfigured management interfaces following an OS upgrade to Windows Server 2025 or Windows 11. In some cases, this also stems from SQL Server Configuration Manager failing to communicate properly with the WMI provider due to namespace registration issues introduced during installation or patching.

Step-by-Step Resolution Guide

Step 1: Verify and Rebuild the WMI Repository

  • Open an elevated Command Prompt on the affected Windows Server 2025 / Windows 11 machine.
  • Run winmgmt /verifyrepository to check if the WMI repository is consistent.
  • If inconsistencies are found, run winmgmt /salvagerepository to attempt an automatic repair.
  • As a last resort, run winmgmt /resetrepository (note: this will reset WMI to default state and may require reconfiguration of dependent services).

Step 2: Re-register the SQL Server WMI Provider

  • Navigate to the SQL Server installation directory, typically C:\Program Files\Microsoft SQL Server\160\Shared\.
  • Locate the file sqlmgmproviderxpsp2up.mof.
  • Run the command mofcomp sqlmgmproviderxpsp2up.mof to re-register the namespace definitions with WMI.
  • Restart the Windows Management Instrumentation service via services.msc or net stop winmgmt && net start winmgmt.

Step 3: Validate XML Schema Collections in the Database

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the query SELECT * FROM sys.xml_schema_collections WHERE name LIKE '%target%'; to identify any schema entries with malformed or missing namespace URIs.
  • Drop and recreate any corrupted schema collection using DROP XML SCHEMA COLLECTION followed by a correct CREATE XML SCHEMA COLLECTION statement referencing the valid namespace.

Step 4: Reapply SQL Server Configuration Manager Settings

  • Open SQL Server Configuration Manager as Administrator.
  • Right-click on SQL Server Services, select Refresh, and confirm that all namespace-dependent services (Agent, Browser, Engine) load without error.
  • If the error persists, uninstall and reinstall the Configuration Manager snap-in via mmc /unregister and mmc /register.

Alternative or Verification Steps

  • To verify the fix, restart the SQL Server and SQL Server Agent services, then check the Event Viewer (Windows Logs > Application) to confirm Error 2385 no longer appears.
  • As an alternative, if the issue persists, run the SQL Server 2025 Repair option from the installation media/Setup Wizard to restore default namespace bindings and WMI provider registrations.

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

Troubleshooting Guide: SQL Server Error 2386 – Facet Value Outside Allowed Range

Why This Error Happens

Error 2386 occurs when a Policy-Based Management (PBM) policy evaluates a property (facet) against a condition whose value falls outside the permissible range defined by SQL Server’s internal metadata or the SMO (SQL Management Objects) facet definition. This is typically caused by a misconfigured policy condition, a manually edited policy XML with an invalid numeric value, or a mismatch between the facet property’s expected data type and the value supplied during evaluation. It can also surface after an in-place upgrade to SQL Server 2025 if legacy policies reference facets whose valid ranges changed between versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Policy or Condition

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Navigate to Management > Policy Management > Policies.
  • Check the SQL Server Agent Job history or Event Viewer (Windows Logs > Application) for the full error text, which includes the facet name (e.g., MaxDegreeOfParallelism, FillFactor, NumberOfLogFiles).
  • Note the exact policy name tied to Error 2386 in the Policy Management history.

Step 2: Inspect and Correct the Condition Value

  • Right-click the identified policy and select Properties.
  • Click the linked Condition and review the Field/Operator/Value expression.
  • Compare the entered value against the facet’s documented valid range in Microsoft Docs (e.g., FillFactor must be between 0–100; MaxDegreeOfParallelism must be between 0–32767).
  • Correct the out-of-range value, then click OK to save.

Step 3: Validate Policy XML for Manual Edits

  • If the policy was imported via script, open the .xml export file in a text editor.
  • Search for <Value> tags under the relevant <Condition> node.
  • Ensure numeric values are not negative, null, or exceeding Int32/Int16 boundaries depending on the facet’s underlying SMO property type.
  • Re-import the corrected policy using:
EXEC msdb.dbo.sp_syspolicy_add_policy @policy_stream = N'C:\Policies\corrected_policy.xml';

Step 4: Clear Cached Policy Metadata

  • Restart the SQL Server Agent service via Services.msc (Windows Server 2025/Windows 11) to flush cached PBM evaluation data.
  • Alternatively, run:
EXEC msdb.dbo.sp_syspolicy_purge_history @policy_id = NULL;
  • This clears stale policy history entries that may reference the invalid facet value.

Step 5: Re-run Policy Evaluation

  • Right-click the corrected policy in SSMS and select Evaluate.
  • Confirm no errors are thrown and the policy returns a Pass/Fail result instead of Error 2386.

Alternative or Verification Steps

  • Run EXEC msdb.dbo.sp_syspolicy_get_conditions; to manually confirm the condition values are now within SMO-documented ranges before re-enabling automated policy execution.
  • If the error persists, drop and recreate the policy from scratch via the Policy Management Wizard instead of reusing an imported XML file, as this guarantees SMO populates valid default ranges.

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

Troubleshooting Guide: SQL Server Error 2383

Why This Error Happens

Error 2383 occurs when SQL Server 2025 receives a configuration attribute value that falls outside its permitted numeric range, typically during DMO (Distributed Management Objects) operations, replication configuration, or Analysis Services property assignments. This is most commonly triggered by malformed XML configuration files, incorrect registry values, or scripts that pass hardcoded values which exceed the valid threshold defined in the server’s schema. In some cases, a corrupted configuration cache or an outdated client library attempting to set a property using a deprecated value range can also produce this error.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Attribute and Value

  • Check the full error message text for the specific placeholders: the attribute name (%ls) and the invalid value (%ls) will be populated in the actual error output.
  • Review SQL Server Error Logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact timestamp and preceding context.
  • Cross-reference the attribute name against Microsoft’s official Tabular Model or Replication object model documentation to confirm the valid numeric range (usually 0 to a defined upper bound like 2147483647).

Step 2: Correct the Configuration Source

  • If the error originates from an XMLA script or SSAS Tabular model, open the .xmla or .bim file and locate the property tag matching the attribute name.
  • Manually edit the value to fall within the valid range, for example changing a negative or out-of-bound integer like -1 or 99999999999 to a valid entry such as 1024.
  • If using PowerShell or SMO (Microsoft.SqlServer.Management.Smo) automation scripts, inspect variable assignments feeding into the .Properties collection and ensure input validation exists before execution.

Step 3: Clear Cached Configuration and Restart Services

  • Open Services.msc on Windows Server 2025 and restart the “SQL Server (MSSQLSERVER)” and “SQL Server Analysis Services” services to clear any in-memory cached invalid states.
  • If using Failover Clustering, run the restart via Failover Cluster Manager instead of Services.msc to maintain cluster resource health.
  • Run DBCC FREEPROCCACHE in SQL Server Management Studio (SSMS) if the error persists after a configuration fix, to eliminate cached execution plans referencing the old value.

Step 4: Validate Permissions and Schema Version Compatibility

  • Confirm the executing account has ALTER ANY SERVER CONFIGURATION and sysadmin roles, especially if the attribute relates to server-level settings like max worker threads or min memory per query.
  • Check Windows Event Viewer under Applications and Services Logs > Microsoft > SQL Server Setup for any failed Setup or Patch events that might have left configuration tables in an inconsistent state.

Alternative or Verification Steps

  • Re-run the original operation (replication setup, XMLA deployment, or SMO script) and confirm no Error 2383 appears in SSMS or the Windows Event Viewer Application log.
  • As an alternative, restore the configuration from a known-good backup of the .bim/.xmla file or server configuration script, then reapply any custom changes incrementally while validating each value against the documented range.

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

Why This Error Happens

Error 2384 occurs when SQL Server validates XML data against a registered XML Schema Collection and finds that an element appears in an order, position, or frequency that violates the schema’s defined sequence or occurrence constraints (minOccurs/maxOccurs). This typically happens due to a mismatch between the application’s XML payload structure and the XSD schema stored in SQL Server, or because the schema collection itself was imported incorrectly or has become corrupted. It can also surface after an in-place upgrade to SQL Server 2025 where stricter XML validation parsing rules were introduced for schema collections.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run SELECT name, schema_id FROM sys.xml_schema_collections; to list all registered collections on the database.
  • Cross-reference the collection name mentioned in the error message with the table/column using XML (CONTENT schema_name).
  • Use SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName'); to export the raw XSD for manual review.

Step 2: Validate the Incoming XML Payload Against the XSD

  • Open the exported XSD in Visual Studio 2022/2025 or an XML editor and check <xs:sequence>, <xs:choice>, and minOccurs/maxOccurs attributes for the failing element.
  • Compare the application-generated XML (from logs or a trace) against the schema order — look for duplicated elements, missing closing tags, or elements inserted out of sequence.
  • Correct the source application code or ETL job generating the XML so element order and counts match the schema exactly.

Step 3: Drop and Re-import a Clean Schema Collection

  • If the schema itself is suspected to be corrupted, back up the current definition, then run:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'<xsd content>';
  • Ensure the XSD file has no encoding issues (UTF-8 without BOM is recommended) and was not truncated during copy/paste.

Step 4: Apply Latest Cumulative Update

  • Check Server Properties in SSMS or run SELECT @@VERSION; to confirm the exact build.
  • Install the latest SQL Server 2025 Cumulative Update from Microsoft, as XML parser fixes are frequently bundled in CU releases.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after patching.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement or application transaction that triggered Error 2384; confirm it completes without validation errors and check sys.dm_exec_requests for a clean execution state.
  • As an alternative if schema correction isn’t feasible immediately, temporarily cast the column to untyped XML (without schema binding) to unblock operations, then re-apply schema validation once the payload generation logic is fixed.

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

Why This Error Happens

Error 2380 typically originates from SQL Server Reporting Services (SSRS) when the Report Server Web Portal attempts to load resources (scripts, images, or API calls) over an insecure HTTP connection while the parent page is being served over HTTPS. Modern browsers block this “mixed content” scenario for security reasons, causing the portal to fail silently or render incompletely. This is most commonly caused by a misconfigured URL reservation in rsreportserver.config, a reverse proxy/load balancer terminating SSL before traffic reaches the Report Server, or hardcoded HTTP references in custom report items.

Step-by-Step Resolution Guide

Step 1: Verify the Report Server URL Configuration

  • Open the Report Server Configuration Manager on Windows Server 2025.
  • Navigate to Web Portal URL and Web Service URL tabs and confirm both are bound to HTTPS, not HTTP.
  • Check the underlying XML at C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\rsreportserver.config and ensure the <UrlRoot> key does not reference http:// when HTTPS is expected.

Step 2: Correct Reverse Proxy / Load Balancer SSL Termination

  • If using IIS ARR, NGINX, or Azure Application Gateway in front of SQL Server 2025, confirm that X-Forwarded-Proto headers are correctly set to https.
  • Update the <HostHeader> and <Secure> elements in rsreportserver.config to force SSRS to recognize the original HTTPS request.
  • Restart the SQL Server Reporting Services service via services.msc or run:
  net stop SQLServerReportingServices
  net start SQLServerReportingServices

Step 3: Scan for Hardcoded HTTP References

  • Search custom report definitions (.rdl files) and any embedded web parts for absolute URLs starting with http://.
  • Replace all static references with protocol-relative URLs (e.g., //yourserver/resource) or explicit https:// paths.
  • Clear the browser cache and Report Server temporary cache located at C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\Microsoft.ReportingServices.* if stale cached assets persist.

Step 4: Validate Certificate Binding on Windows Server 2025

  • Open IIS Manager (if applicable) or use PowerShell to confirm the SSL certificate is correctly bound to port 443:
  Get-ChildItem -Path Cert:\LocalMachine\My
  netsh http show sslcert
  • Re-bind the certificate to the Report Server endpoint if it is missing or expired.

Alternative or Verification Steps

  • Open the browser Developer Console (F12) on the Report Portal page and confirm no “Mixed Content” warnings appear in the Console tab after applying the fix.
  • If the error persists, temporarily disable the reverse proxy and connect directly to the Report Server via HTTPS to isolate whether the issue is proxy-related or SSRS-configuration-related.

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

Why This Error Happens

Error 2382 occurs when SQL Server 2025 attempts to parse or register an XML Schema Collection (XSD) that contains a logically invalid particle declaration, specifically where the minOccurs value is greater than the maxOccurs value, or where maxOccurs is set to a non-positive integer incorrectly. This typically happens when a schema file has been manually edited, corrupted during a migration, or generated by a third-party tool that does not strictly adhere to W3C XSD validation rules. Because SQL Server’s native XML parser enforces strict compliance, it rejects the schema binary entirely rather than attempting a partial import.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Schema Collection

  • Open SQL Server Management Studio (SSMS) and connect to the instance throwing the error.
  • Run SELECT name, xml_schema_namespace FROM sys.xml_schema_collections; to identify the specific collection being loaded or altered when the error triggers.
  • Export the XSD using SELECT CONVERT(xml, xml_schema_namespace) FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; to inspect the raw text.

Step 2: Validate the XSD Structure Manually

  • Copy the exported schema definition into a local .xsd file on your Windows Server 2025 or Windows 11 machine (e.g., C:\Temp\schema_validation\broken_schema.xsd).
  • Search the file for the attributes minOccurs and maxOccurs. Look specifically for instances where minOccurs="2" is paired with maxOccurs="1", or where maxOccurs="0" is used without minOccurs="0".
  • Correct the logic so that maxOccurs is always greater than or equal to minOccurs, or set maxOccurs="unbounded" if the field repetition count is not fixed.

Step 3: Re-Register the Corrected Schema

  • Drop the broken collection using DROP XML SCHEMA COLLECTION YourSchemaName; (ensure no active tables are strictly bound to it, or use ALTER instead if constraints exist).
  • Re-import the fixed file using a command prompt or SSMS query: CREATE XML SCHEMA COLLECTION YourSchemaName AS 'C:\Temp\schema_validation\fixed_schema.xsd';
  • Restart the “SQL Server (MSSQLSERVER)” service via services.msc on Windows Server 2025 to clear any cached execution plans referencing the old, corrupted schema structure.

Step 4: Check Application-Side Serialization Libraries

  • If the schema is generated dynamically by a .NET application (common in Windows 11 dev environments), verify the version of System.Xml.Schema being used.
  • Ensure the application code explicitly defines Occurs properties rather than relying on default serialization behaviors which can sometimes generate conflicting values during complex type inheritance.

Alternative or Verification Steps

  • To verify the fix, run a test INSERT or UPDATE statement against a table that uses the XML datatype bound to this schema; if the data passes validation without throwing Error 2382, the structure is confirmed fixed.
  • If the error persists after manual editing, use the XML Schema Explorer in Visual Studio 2025 to visually validate the “Compositor” properties of the schema, as this tool often catches nested sequence/choice conflicts that a simple text search might miss.

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

Troubleshooting Guide: SQL Server Error 2377 — “Result of expression is statically ’empty'”

Why This Error Happens

Error 2377 occurs when the SQL Server Query Optimizer statically analyzes a Transact-SQL expression — often within computed columns, check constraints, or Intelligent Query Processing (IQP) scalar inlining — and determines that it will always evaluate to an empty result set or NULL regardless of runtime input. This typically stems from contradictory predicates, a type mismatch during an implicit conversion, or a logic error introduced after a schema change (such as a column being altered to a non-matching data type). It can also surface after upgrading compatibility levels in SQL Server 2025, which exposes stricter static analysis rules in the optimizer that previous versions silently ignored.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object

  • Check the SQL Server error log or Extended Events session for the exact statement or module name referenced by the %ls placeholder in the error text.
  • Run the following to isolate recently modified objects:
  SELECT name, modify_date FROM sys.objects ORDER BY modify_date DESC;
  • Note whether the error originates from a view, computed column, user-defined function, or an inline table-valued function.

Step 2: Review and Correct the Expression Logic

  • Open the object definition using SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Look for contradictory WHERE clauses (e.g., WHERE 1 = 0 or WHERE ColumnA = 'X' AND ColumnA = 'Y').
  • Check for implicit data type conversions that always fail, such as comparing an INT column against a non-numeric string literal.
  • Rewrite the logic using explicit CAST or CONVERT functions to ensure type-safe comparisons:
  SELECT * FROM dbo.Orders WHERE CAST(OrderStatus AS VARCHAR(10)) = 'Shipped';

Step 3: Adjust Database Compatibility Level (If Needed)

  • Navigate to Databases > [YourDatabase] > Properties > Options in SSMS, or run:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 160;
  • Temporarily lowering compatibility level can confirm whether a new optimizer rule in SQL Server 2025 is triggering the static analysis.
  • Only use this as a diagnostic step — plan to fix the underlying expression rather than permanently downgrading compatibility.

Step 4: Clear Cached Execution Plans

  • After correcting the code, remove any stale cached plans tied to the faulty expression:
  DBCC FREEPROCCACHE;
  • On Windows Server 2025, restart the SQL Server (MSSQLSERVER) service via services.msc if the issue persists after cache clearing.

Step 5: Validate Check Constraints and Computed Columns

  • Script out all check constraints and computed columns on the affected table:
  EXEC sp_helpconstraint 'dbo.YourTable';
  • Drop and recreate any constraint found referencing a logically impossible condition.

Alternative or Verification Steps

  • Re-run the original query or execute the stored procedure/view in isolation to confirm Error 2377 no longer appears in SSMS or the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER).
  • If the error persists, use SET SHOWPLAN_XML ON to inspect the execution plan directly — this reveals exactly which predicate the optimizer is folding to “empty,” allowing for a more targeted fix than relying on error text alone.

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

Why This Error Happens

Error 2378 occurs when SQL Server’s XML parser attempts to validate a document against an XML Schema Collection but encounters content that does not conform to the expected XML Schema Definition (XSD) structure. This typically happens when a malformed, truncated, or incorrectly namespaced XML document is passed into a column or variable that is typed with XML(SCHEMA COLLECTION ...). It can also surface when the registered schema collection itself has become corrupted or was registered with conflicting namespace definitions, causing the engine to reject even well-formed XML during insert or update operations.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Document

  • Open the XML payload being inserted and confirm it begins with a valid root element and, if applicable, a proper <?xml version="1.0"?> declaration.
  • Use a tool like SELECT CAST(@xmlVar AS XML) in a scratch query window to isolate whether the raw document is well-formed before schema validation is applied.
  • Check for truncation — large XML payloads exceeding buffer limits (especially via ODBC/OLE DB drivers on Windows Server 2025) are a common silent cause.

Step 2: Inspect and Repair the XML Schema Collection

  • Run the following query to review the registered schema collection definition:
  • SELECT name, xml_schema_namespace, schema_collection_id FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • If the collection appears incomplete or outdated, drop and re-add it using:
  • DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  • CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS N'<xsd:schema>...</xsd:schema>';
  • Ensure the targetNamespace attribute in the XSD exactly matches the namespace used in the incoming XML document.

Step 3: Check Application-Level Serialization Settings

  • On Windows 11/Windows Server 2025 clients, confirm that the application layer (e.g., .NET SqlXml or XmlDocument objects) is not re-encoding the payload with an unexpected encoding (UTF-16 vs UTF-8 mismatches are common).
  • Verify connection string parameters such as Packet Size are sufficiently large (e.g., Packet Size=32767) to avoid silent truncation of large XML blobs over the wire.

Step 4: Rebuild the Column Binding

  • If the error persists only on a specific table/column, script out the table, drop the XML(SCHEMA COLLECTION) typed column constraint, and recreate it after confirming the schema collection is valid:
  • ALTER TABLE YourTable ALTER COLUMN XmlCol XML(YourSchemaCollectionName);
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear any cached execution plans referencing the old schema.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement after Step 2 — if it completes without Error 2378, the schema collection repair was the root cause.
  • As a fallback, temporarily cast the column to untyped XML (without schema binding) to confirm the document inserts successfully, isolating the issue to schema validation rather than XML well-formedness.

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

Troubleshooting Guide: SQL Server Error 2379 – Invalid XML Name

Why This Error Happens

Error 2379 occurs when SQL Server attempts to generate or parse XML data (such as through FOR XML clauses, XML schema collections, or column/element names) and encounters an identifier that violates XML naming rules. This typically happens when a column name, alias, or element name contains illegal characters (such as spaces, symbols, or a leading digit) that are valid in T-SQL but not permitted in the W3C XML specification. It can also surface when corrupted metadata or a malformed XML schema collection forces SQL Server to reference an invalid name during serialization.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column or Alias

  • Review the exact query or stored procedure referenced in the error message, paying attention to the %ls placeholder which usually contains the invalid name.
  • Check for column names or aliases containing spaces, hyphens, special characters (#, @, $ in certain positions), or names starting with a numeral.
  • Run the query in SQL Server Management Studio (SSMS) 21 with SET FMTONLY ON or a limited TOP 1 execution to isolate the exact FOR XML segment causing the failure.

Step 2: Apply Valid XML Aliasing

  • Rewrite the query to assign XML-safe aliases to any problematic columns using square brackets, ensuring the alias starts with a letter or underscore and contains no spaces.
  • Example fix: Change SELECT [Order #] FROM Sales FOR XML AUTO to SELECT [Order #] AS OrderNumber FROM Sales FOR XML AUTO.
  • If using FOR XML PATH, explicitly define safe element names using the AS syntax for every computed or aggregated column.

Step 3: Validate XML Schema Collections

  • If the error originates from a typed XML column, open the associated XML Schema Collection (XSD) in SSMS under Databases > [YourDB] > Programmability > Types > XML Schema Collections.
  • Verify that the targetNamespace and element definitions comply with standard XML naming conventions (no leading numbers or invalid symbols).
  • If the schema is corrupted, drop and recreate it using DROP XML SCHEMA COLLECTION followed by CREATE XML SCHEMA COLLECTION with the corrected .xsd definition file.

Step 4: Check for Hidden Whitespace or Unicode Characters

  • Inspect the source data or variable names for non-printable Unicode characters that may have been introduced via copy-pasting from external documents or web sources.
  • Use the T-SQL function SELECT ASCII(SUBSTRING(ColumnName, 1, 1)) to detect hidden characters at the start of a string being used as an XML node name.
  • Clean the data using REPLACE() or TRIM() functions before passing it into the FOR XML command.

Alternative or Verification Steps

  • Verification: Re-run the original query or application call that triggered Error 2379; confirm the XML output renders correctly in the SSMS results grid without throwing a parser exception.
  • Alternative: If renaming columns is not feasible due to application dependencies, wrap the query in a subquery or CTE that renames the columns to XML-compliant aliases before the final FOR XML conversion is applied.

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

Troubleshooting Guide: Error 2375 — Aggregate Function Expects a Sequence Argument

Why This Error Happens

This error occurs when a T-SQL query attempts to pass a scalar expression, column reference, or non-sequence data type to an aggregate function (such as STRING_AGG, PERCENTILE_CONT, or newer SQL Server 2025 vector/sequence-based aggregates) that strictly requires an ordered sequence or array-type input. It is typically triggered by malformed query syntax, incorrect casting of a column to a scalar before aggregation, or a mismatch between the expected input type (sequence) and the actual argument type passed during query compilation. Less commonly, this can surface due to corrupted or outdated query plans cached from a previous SQL Server version during an upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Function

  • Check the SQL Server error log or SSMS output pane for the exact query batch that triggered Error 2375.
  • Look specifically for aggregate functions like STRING_AGG(), PERCENTILE_CONT(), PERCENTILE_DISC(), or new SQL Server 2025 sequence-aggregate functions.
  • Run the query in isolation using SQL Server Management Studio (SSMS) 21 or Azure Data Studio to reproduce the error outside of application context.

Step 2: Correct the Argument Type Passed to the Aggregate Function

  • Ensure the argument passed is a valid sequence type (e.g., a column of array/table type, or a subquery returning an ordered row set), not a scalar variable or single expression.
  • For STRING_AGG, confirm the input expression resolves to a column, not a hardcoded scalar value:
  SELECT STRING_AGG(ColumnName, ',') WITHIN GROUP (ORDER BY ColumnName)
  FROM YourTable;
  • If using SQL Server 2025’s new native vector/sequence aggregate functions, verify the input data type matches the expected SEQUENCE or VECTOR type defined in the function signature using sys.types.

Step 3: Clear and Rebuild the Query Plan Cache

  • Open a new query window in SSMS connected to the affected instance.
  • Run the following to clear potentially corrupted cached plans:
  DBCC FREEPROCCACHE;
  • Re-execute the original query to confirm the plan recompiles correctly against the current SQL Server 2025 engine.

Step 4: Update SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog or use SQL Server Setup on Windows Server 2025 / Windows 11 to check for the latest Cumulative Update (CU).
  • Apply the update via:
  Control Panel > Programs > Microsoft SQL Server 2025 > Uninstall/Change > Check for Updates
  • Restart the SQL Server service after installation:
  Restart-Service -Name 'MSSQLSERVER'

Alternative or Verification Steps

  • Verify the fix by re-running the original failing query and confirming it returns results without Error 2375; also check sys.dm_exec_query_stats to confirm a new, valid execution plan has been cached.
  • If the error persists, isolate the aggregate function call into a simplified test script with sample static data to confirm whether the issue is data-driven (bad input) or a genuine compatibility bug requiring a Microsoft support case.

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

Troubleshooting Guide: Error 2376 — “%sOperand of a single numeric type expected”

Why This Error Happens

This error occurs when SQL Server 2025 encounters a mismatched or ambiguous data type during an internal aggregate, arithmetic, or comparison operation where a single consistent numeric type is required. It is commonly triggered by implicit conversion failures between types such as decimal, float, or numeric in system views, computed columns, or statistics calculations. In some cases, this error surfaces due to corrupted metadata in system catalogs or an incompatible collation/data type mix introduced after an in-place upgrade to SQL Server 2025 on Windows Server 2025 or Windows 11.

Step-by-Step Resolution Guide

Step 1: Identify the Query or Process Triggering the Error

  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact statement or stored procedure referenced alongside Error 2376.
  • Run DBCC INPUTBUFFER(<session_id>) to capture the exact query text if the error occurs during an active session.
  • Review any recent changes to computed columns, views, or CLR functions that mix numeric data types.

Step 2: Validate and Correct Data Type Consistency

  • Open the offending query in SQL Server Management Studio (SSMS) 21 and inspect all numeric columns involved in SUM(), AVG(), CAST(), or CONVERT() operations.
  • Explicitly cast ambiguous columns to a single numeric type, for example: CAST(column_name AS DECIMAL(18,2)).
  • Avoid mixing float/real with decimal/numeric in the same expression, as SQL Server 2025 enforces stricter type resolution rules than prior versions.

Step 3: Rebuild Statistics and Check Catalog Integrity

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS to rule out catalog or metadata corruption.
  • Execute EXEC sp_updatestats; to refresh outdated statistics that may be feeding incorrect type estimates to the query optimizer.
  • If corruption is found, restore the affected database from the last known good backup.

Step 4: Apply the Latest Cumulative Update

  • Navigate to Settings > Windows Update on Windows Server 2025 or Windows 11 to confirm the OS is fully patched.
  • Download and apply the latest SQL Server 2025 Cumulative Update (CU) from the Microsoft Update Catalog, as this error has known fixes tied to the query optimizer’s numeric type resolution logic.
  • Restart the SQL Server service via services.msc after the update completes.

Alternative or Verification Steps

  • Re-run the original query or job that triggered Error 2376 and confirm it completes without the “%sOperand of a single numeric type expected” message in the Error Log.
  • If the issue persists, isolate the query by running it against a tempdb copy of the affected table with explicitly typed columns to confirm whether the fix lies in schema design rather than server configuration.

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

Troubleshooting Guide: SQL Server Error 2373 – “%s%ls is not supported with constructed XML”

Why This Error Happens

This error occurs when an operation—such as creating an index, applying a constraint, or executing certain DML operations—is attempted on XML data that was generated dynamically (constructed) rather than retrieved directly from a typed XML column or variable. SQL Server 2025 restricts operations like indexing or schema validation on constructed XML because it lacks the persistent structure and schema binding required for these features. This typically surfaces in queries that use FOR XML, XML methods (like .query() or .nodes()), or functions that return XML results on-the-fly within a nested query, rather than reading from a stored, schema-validated XML column.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Operation

  • Review the exact T-SQL statement that triggered Error 2373 using SQL Server Management Studio (SSMS) or the Extended Events log.
  • Check Windows Event Viewer under Applications and Services Logs > Microsoft > SQL Server for the full error context and the %ls substitution value, which indicates the specific unsupported operation (e.g., indexing, schema collection binding).
  • Confirm whether the XML data originates from a function, subquery, or FOR XML clause rather than a native XML column.

Step 2: Materialize the XML Before Performing the Operation

  • Instead of operating directly on constructed XML, insert the result into a temporary table or table variable with a proper XML typed column first.
  • Example fix:
DECLARE @TempXML TABLE (XmlData XML);
INSERT INTO @TempXML
SELECT (SELECT * FROM YourTable FOR XML AUTO);
  • Now apply indexing, constraints, or further XML methods against @TempXML.XmlData instead of the inline constructed result.

Step 3: Rebind or Recreate XML Schema Collections (If Applicable)

  • If the error relates to schema-bound XML operations, verify the XML Schema Collection is correctly attached to a persisted column:
ALTER TABLE YourTable
ALTER COLUMN XmlColumn XML (YourSchemaCollectionName);
  • Ensure the schema collection exists and is not orphaned by running:
SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog and confirm the instance is running the latest Cumulative Update (CU) for SQL Server 2025, as early builds had stricter XML construction validation that has since been patched.
  • Verify current build version by running:
SELECT @@VERSION;
  • Install any pending updates via Windows Update or the standalone SQL Server Setup package, then restart the SQL Server (MSSQLSERVER) service from services.msc.

Alternative or Verification Steps

  • Re-run the original query against the materialized temporary table/variable version to confirm Error 2373 no longer appears in SSMS or the Windows Application Event Log.
  • If the issue persists, as a workaround, cast the constructed XML result explicitly using CAST(... AS XML) into a declared variable before passing it to any indexing or schema-validation operation.

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

Troubleshooting Guide: Error 2374 – “A node or set of nodes is required for %ls”

Why This Error Happens

Error 2374 occurs when SQL Server 2025 attempts to parse or execute an XML Schema Collection, XQuery expression, or XML DML statement that references a node path which does not resolve to any valid node in the target XML structure. This typically stems from a malformed XPath/XQuery expression, a mismatch between the expected XML schema and the actual XML instance data, or corruption in the XML index/schema collection metadata. It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schema collections were built against deprecated parsing behaviors no longer supported by the updated XQuery engine.

Step-by-Step Resolution Guide

Step 1: Validate the XQuery/XPath Expression Syntax

  • Open the stored procedure, function, or ad-hoc query that triggered Error 2374 in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Check .nodes(), .query(), .value(), or .modify() calls for correct node path syntax — a missing / or incorrect namespace prefix is a common cause.
  • Run the query in isolation: SELECT XmlColumn.query('/Root/Node') FROM YourTable; to confirm the path resolves against sample data.

Step 2: Inspect and Repair the XML Schema Collection

  • Query existing schema collections: SELECT name, xml_collection_id FROM sys.xml_schema_collections;
  • Compare the registered schema against the actual XML documents being inserted using: SELECT SCHEMA_NAME(schema_id), name FROM sys.xml_schema_collections WHERE name = 'YourCollectionName';
  • If the schema is outdated or mismatched, drop and recreate it:
DROP XML SCHEMA COLLECTION YourCollectionName;
GO
CREATE XML SCHEMA COLLECTION YourCollectionName AS N'<your updated XSD content>';

Step 3: Rebuild XML Indexes on Affected Tables

  • Corrupted or stale primary/secondary XML indexes can cause node resolution failures during query execution.
  • Identify XML indexes on the affected table:
SELECT i.name, i.type_desc FROM sys.indexes i
WHERE i.object_id = OBJECT_ID('YourTableName') AND i.type_desc LIKE 'XML%';
  • Rebuild the index to clear any fragmentation or metadata drift:
ALTER INDEX PrimaryXmlIndexName ON YourTableName REBUILD;

Step 4: Apply the Latest SQL Server 2025 Cumulative Update

  • On Windows Server 2025 / Windows 11, open Settings > Windows Update or use SQL Server Setup to check for the latest Cumulative Update (CU), as early 2025 builds had known XQuery engine regressions affecting node-set evaluation.
  • Download and install the CU from the Microsoft Update Catalog, then restart the MSSQLSERVER service via services.msc or:
Restart-Service -Name MSSQLSERVER -Force

Alternative or Verification Steps

  • After applying fixes, re-run the original failing query/procedure and confirm Error 2374 no longer appears in the SQL Server Error Log (EXEC sp_readerrorlog;).
  • If the error persists, isolate the issue by testing the same XML document and schema in a clean tempdb table to rule out table-specific corruption versus a genuine schema/query defect.

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

Troubleshooting Guide: SQL Server Error 2371

Why This Error Happens

Error 2371 occurs when an XQuery function such as last(), position(), or similar context-dependent functions is used outside of a valid predicate or XPath selector context within a T-SQL .query(), .value(), or .exist() method call against XML data. This typically results from malformed XQuery syntax where functions that require positional or filtering context are placed directly in the selection path rather than inside square brackets [ ]. It is almost always a query authoring issue rather than a server configuration, permissions, or corruption problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XQuery Statement

  • Locate the stored procedure, view, or ad-hoc query referenced in the error message from SQL Server Management Studio (SSMS) or the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER).
  • Search for .query(, .value(, .nodes(, or .exist( method calls operating on xml-typed columns or variables.
  • Note the exact XPath/XQuery string, as the function named in %ls (e.g., last()) is the one misused.

Step 2: Correct the XPath Predicate Syntax

  • Ensure functions like last() or position() are enclosed within square brackets [ ] immediately following a node reference, not appended loosely to the path.
  • Example of incorrect syntax: /Root/Item/last()
  • Example of corrected syntax: /Root/Item[last()]
  • If using position(), confirm it is used as a comparison inside a predicate: /Root/Item[position()=1]

Step 3: Validate XML Schema and Namespace Declarations

  • Open the query in SSMS and check if a WITH XMLNAMESPACES clause is required and correctly declared above the query.
  • Verify the XML column’s schema collection (if bound via XML SCHEMA COLLECTION) actually supports the node structure being queried; run sp_help on the schema collection to confirm.
  • Re-run the corrected query against a small test dataset using SELECT TOP 10 before deploying to production procedures.

Step 4: Rebuild and Redeploy the Stored Procedure

  • Once the XQuery predicate is fixed, use ALTER PROCEDURE (not DROP/CREATE) to preserve permissions.
  • Clear the plan cache for the specific object using DBCC FREEPROCCACHE (plan_handle) to ensure SQL Server 2025 doesn’t reuse a cached invalid execution plan reference tied to the error.
  • Restart the SQL Server Agent job (if applicable) via SQL Server Configuration Manager on Windows Server 2025 to confirm the corrected procedure executes on schedule.

Alternative or Verification Steps

  • Run the modified query manually in a new SSMS query window with SET STATISTICS XML ON to confirm no exceptions are thrown and valid XML output is returned.
  • If the error persists despite correct bracket placement, check for nested .query() calls where an inner expression inadvertently inherits an outer context; isolate each .query() call independently to pinpoint the exact failure point.

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

Troubleshooting Guide: SQL Server Error 2372

Why This Error Happens

Error 2372 occurs when SQL Server’s metadata schema validation encounters an XML or DDL attribute (denoted as @%ls:%ls) that is being applied to an element or object type (%ls) that does not support it. This typically happens due to a mismatch between a metadata annotation—such as a namespace-prefixed attribute used in XML schema collections, CLR integration, or Service Broker definitions—and the target object’s supported attribute set. It can also surface after an in-place upgrade to SQL Server 2025 where deprecated or renamed metadata attributes remain referenced in legacy scripts, stored procedures, or SSIS packages that were not updated for the new schema validation engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Object

  • Open SQL Server Management Studio (SSMS) and check the Activity Monitor or SQL Server Error Log (Management > SQL Server Logs) to capture the full error text, including the specific attribute and object name reported.
  • Run the following query to pinpoint recent DDL operations that may have triggered the validation failure:
  SELECT * FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL) WHERE object_name = 'error_reported';
  • Note the exact namespace prefix and attribute name from the error message for cross-referencing in Step 2.

Step 2: Validate XML Schema Collections and Metadata Definitions

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Types > XML Schema Collections and inspect any collection referenced by the failing object.
  • Use sp_help or query sys.xml_schema_collections to confirm the attribute is valid for the SQL Server 2025 schema version:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Remove or correct any deprecated attributes (common culprits include legacy sql: or xsi: prefixed attributes not supported on newer element types like sparse columns or temporal table metadata).

Step 3: Update or Recompile Affected Stored Procedures/SSIS Packages

  • Open any stored procedures, functions, or SSIS packages that reference the object in question via C:\Program Files\Microsoft SQL Server\160\DTS\Packages\ (or your custom deployment path).
  • Replace outdated metadata attribute calls with the SQL Server 2025-compliant syntax found in the Breaking Changes section of Microsoft Docs for the 2025 release.
  • Recompile using:
  EXEC sp_recompile 'YourStoredProcedureName';

Step 4: Apply the Latest Cumulative Update (CU)

  • Check your current build via SELECT @@VERSION; and compare against the latest CU listed on the Microsoft Update Catalog.
  • Download and install the newest Cumulative Update for SQL Server 2025, as metadata validation bugs are frequently patched in CU releases.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after installation.

Alternative or Verification Steps

  • Re-run the original DDL statement or SSIS package in a test/staging environment and confirm Error 2372 no longer appears in the SQL Server Error Log.
  • If the error persists, use DBCC CHECKDB with the WITH DATA_PURITY option to rule out underlying metadata corruption, and consider restoring the schema collection from a known-good backup if corruption is confirmed.

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

Troubleshooting Guide: SQL Server Error 2368

Why This Error Happens

Error 2368 occurs when SQL Server parses an XML Schema Collection (XSD) definition and encounters a type that has been declared with simple content (meaning it should only contain text or attribute values) but the schema also attempts to nest child elements inside it. This is typically caused by a malformed or manually edited XSD file, a corrupted schema collection in the database, or an application update that pushed an invalid XML configuration schema. It frequently surfaces during SSIS package execution, database schema imports, or when SQL Server attempts to validate XML data against a XML SCHEMA COLLECTION that violates W3C XML Schema structure rules.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate the specific schema collection referenced in the error location path (%ls):
  • SELECT name, xml_schema_namespace, schema_collection_id FROM sys.xml_schema_collections WHERE name LIKE '%YourSchemaName%';
  • Cross-reference the Location string in the error message with the namespace URI returned to confirm which object is causing the conflict.
  • Check SQL Server Error Logs via C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact timestamp and triggering T-SQL statement.

Step 2: Extract and Validate the XSD Definition

  • Export the raw schema text using: SELECT xml_schema_namespace FROM sys.xml_schema_collections WHERE schema_collection_id = [ID_FROM_STEP_1];
  • Paste the output into a validator tool (such as Visual Studio’s XML Schema Explorer or an online XSD linter) to pinpoint the exact complexType tag causing the conflict.
  • Look specifically for a <xs:simpleContent> or <xs:restriction base="xs:string"> block that incorrectly contains nested <xs:element> tags—this structure is illegal per XML Schema specification and must be converted to <xs:complexContent> if child elements are required.

Step 3: Drop and Recreate the Corrected Schema Collection

  • Since ALTER XML SCHEMA COLLECTION only supports adding components (not fixing existing ones), you must drop the broken collection first: DROP XML SCHEMA COLLECTION [YourSchemaName];
  • Re-create it using the corrected XSD file: CREATE XML SCHEMA COLLECTION [YourSchemaName] AS 'C:\SchemaFiles\CorrectedSchema.xsd';
  • If the schema is tied to a third-party application (e.g., SSIS, BizTalk, or a vendor ERP), update the application’s configuration files to point to the patched schema version rather than editing the database object directly, in case the app overwrites it on restart.

Step 4: Restart the SQL Server Service and Clear Cache

  • Open Services.msc on Windows Server 2025 and restart the SQL Server (MSSQLSERVER) service to clear any cached execution plans referencing the old schema.
  • Alternatively, run DBCC FREEPROCCACHE; to avoid a full service restart if this is a production environment with high availability requirements.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query, SSIS package, or application process that triggered the error. Check sys.xml_schema_collections again to confirm the schema_collection_id is active and query XML_SCHEMA_NAMESPACE() function against a sample document to ensure it validates without throwing Error 2368.
  • Alternative Fix: If you cannot immediately edit the XSD source, temporarily cast the problematic column to untyped XML (removing the WITH XMLSCHEMA binding) to restore functionality while the schema file is corrected offline by the development team.

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

Troubleshooting Guide: SQL Server Error 2369

Why This Error Happens

Error 2369 occurs when SQL Server parses an XML Schema Collection (XSD) that contains a complexType definition with more than one structural model group—such as sequence, choice, all, or group—nested directly within a single restriction or extension element. The XML Schema specification strictly permits only one such compositor per restriction/extension block, so when SQL Server’s schema validation engine encounters a malformed or hand-edited XSD with duplicate compositors, it rejects the registration and throws this error. This typically happens after a schema collection is altered manually, imported from an external system, or generated by a third-party tool that does not strictly adhere to W3C XSD structural rules.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate the schema collection referenced in the error’s location path (%ls):
  • SELECT name, schema_namespace FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Extract the full XSD definition using SELECT xml_schema_namespace(N'SchemaName', N'CollectionName'); to inspect its raw structure.

Step 2: Locate and Correct the Duplicate Compositor

  • Open the extracted XSD in a text editor or Visual Studio XML editor on your Windows Server 2025 / Windows 11 machine.
  • Search for <xs:restriction> or <xs:extension> blocks containing more than one of: <xs:sequence>, <xs:choice>, <xs:all>, or <xs:group>.
  • Consolidate the content into a single compositor (commonly <xs:sequence>) by merging child elements from the duplicate groups into one valid group.
  • Save the corrected file as a .xsd file, for example: C:\SQLSchemas\CorrectedSchema.xsd.

Step 3: Drop and Re-Register the Schema Collection

  • Drop the broken collection (only if no dependent tables/columns reference it): DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  • Re-create it using the corrected XSD file:
  • CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS 'contents_of_corrected_xsd_file';
  • If dependencies exist, use ALTER XML SCHEMA COLLECTION YourSchemaCollectionName ADD 'corrected_fragment'; instead to patch incrementally.

Step 4: Validate Application/ETL Source Files

  • If the schema originates from an external application (e.g., BizTalk, a .NET XSD generator, or a third-party ETL tool), check the generator’s export settings under its configuration directory, typically found in C:\Program Files\<VendorApp>\Config\.
  • Update or patch the generator so future exports do not produce duplicate compositors.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE XML SCHEMA COLLECTION or ALTER statement that previously failed — it should complete without raising Error 2369.
  • As an alternative, validate the XSD offline using the xsd.exe utility (included with Visual Studio Build Tools) or an online XSD validator before importing it into SQL Server, catching compositor violations prior to deployment.

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

Troubleshooting Guide: SQL Server Error 2370 – XQuery Expression Parsing Failure

Why This Error Happens

Error 2370 occurs when SQL Server’s XQuery parser encounters unexpected or malformed syntax after what it determined should be the logical end of an XQuery expression, typically due to extra characters, unbalanced brackets, or stray tokens left in the query string. This commonly results from improperly concatenated dynamic XQuery strings, copy-paste errors introducing hidden characters, or mismatched quotes/parentheses within .query(), .value(), .exist(), or .nodes() method calls on XML data types. In some cases, this also stems from application code (such as ORM-generated queries) that incorrectly builds XPath/XQuery strings with trailing or duplicated tokens.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Query

  • Capture the exact T-SQL statement using SQL Server Profiler, Extended Events, or the Windows Event Viewer (under Applications and Services Logs > MSSQLSERVER) to find the full error text, which includes the problematic token in place of %ls.
  • Run the query manually in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance to reproduce the error in isolation.

Step 2: Inspect and Correct the XQuery Syntax

  • Check for unbalanced parentheses, brackets, or quotation marks within the XML method calls, e.g., column.query('/Root/Element[1]').
  • Look specifically for trailing characters after the final closing bracket of the expression, such as stray ), ], or ' characters left over from string concatenation.
  • Validate that any dynamically built XQuery strings (from application code or stored procedures) are not appending extra delimiters or whitespace artifacts.

Step 3: Rebuild Dynamic Query Strings Safely

  • If the XQuery is generated programmatically (e.g., in C#, Python, or via an ORM), refactor the string-building logic to use parameterized construction rather than raw concatenation.
  • Use PRINT or SELECT statements in a T-SQL script to output the final constructed XQuery string before execution, allowing visual inspection for syntax errors.
  • Example check in SSMS:
DECLARE @xquery NVARCHAR(500) = '/Root/Element[1]/Value'
SELECT @xquery

Step 4: Update SQL Server and Validate XML Schema Collections

  • Ensure SQL Server 2025 has the latest Cumulative Update (CU) installed via SQL Server Setup > Check for Updates, since XQuery parser edge-case bugs are periodically patched by Microsoft.
  • If the XML column uses a typed XML Schema Collection, verify the schema definition itself doesn’t contain malformed XPath constraints by reviewing it with:
SELECT xml_schema_namespace('SchemaName', 'SchemaCollectionName')

Step 5: Test in a Clean Query Window

  • Strip the query down to its simplest form (minimal XML fragment and simplest XPath) and incrementally rebuild complexity to pinpoint exactly which clause introduces the extra token.
  • Remove any non-printable or Unicode characters that may have been introduced via copy-paste from documentation or web sources using a plain text editor (e.g., Notepad) before re-running in SSMS.

Alternative or Verification Steps

  • Verify the fix by re-executing the corrected query in SSMS and confirming it returns expected results without Error 2370, then re-test through the original application workflow to confirm end-to-end resolution.
  • As an alternative, if the issue stems from a third-party application or ORM-generated query, check the vendor’s documentation or support forums for known XQuery generation bugs specific to SQL Server 2025 compatibility, and apply any recommended patches or configuration overrides.

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

Troubleshooting Guide: Error 2366 – Circular Definition Error in SQL Server 2025

Why This Error Happens

Error 2366 occurs when SQL Server detects a circular reference within object definitions, typically involving computed columns, views, or user-defined functions that directly or indirectly reference themselves. This happens because the schema binding resolution process traces dependency chains and identifies a loop—such as Object A referencing Object B, which in turn references Object A. Circular definitions can also be introduced inadvertently during schema migrations, replication setups, or when synonyms are chained incorrectly across linked servers.

Step-by-Step Resolution Guide

Step 1: Identify the Circular Dependency Chain

  • Run the following query to inspect dependency relationships for the affected object:
  • SELECT * FROM sys.sql_expression_dependencies WHERE referencing_id = OBJECT_ID('YourObjectName');
  • Cross-reference the output to manually trace whether any referenced object loops back to the original object name.
  • Check the exact object name mentioned in the error message (the %ls placeholder) in SQL Server Management Studio (SSMS) 21 Object Explorer under Databases > [YourDB] > Programmability.

Step 2: Review and Modify Computed Columns or Views

  • Open the definition of the flagged object using sp_helptext 'YourObjectName'; or by scripting it out via SSMS (right-click > Script Object as > CREATE To).
  • Look specifically for computed columns that reference a function, which in turn queries the same table/column defining the computation.
  • Remove or rewrite the self-referencing logic, replacing it with a static calculation, a temporary staging table, or an intermediate view that breaks the loop.
  • If using nested views, flatten the view hierarchy by querying base tables directly instead of stacking dependent views.

Step 3: Rebuild the Object Without the Circular Logic

  • Drop the problematic constraint, computed column, or view using DROP VIEW YourViewName; or ALTER TABLE YourTable DROP COLUMN YourComputedColumn;
  • Recreate the object with corrected logic, ensuring no reference points back to the originating object in the dependency chain.
  • If the issue stems from synonyms or linked servers, verify the synonym target in sys.synonyms does not point back to a local object with the same alias.

Step 4: Clear and Refresh the Metadata Cache

  • Run EXEC sp_refreshsqlmodule 'YourObjectName'; to force SQL Server to recompile and re-validate the object definition.
  • If the error persists, restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 to clear any stale cached execution plans related to the dependency.

Alternative or Verification Steps

  • Verify the fix by re-running the original DDL or query that triggered Error 2366; if no error returns and sys.sql_expression_dependencies shows a clean, non-looping chain, the issue is resolved.
  • As an alternative, if the circular reference is deeply embedded in legacy code, use SQL Server Data Tools (SSDT) schema comparison to export the database schema, visually map dependencies, and refactor the object chain before redeploying.

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

Why This Error Happens

This error occurs when registering an XML schema collection in SQL Server where an xsd:list element references a complex type instead of a simple type as its item type. The SQL Server XML schema validation engine strictly enforces W3C XSD rules, which mandate that list items must resolve to simple types (atomic or union types). This typically results from a malformed or manually edited XSD file, or from an XSD generated by a third-party tool that does not fully comply with the XSD 1.0/1.1 specification.

Step-by-Step Resolution Guide

Step 1: Locate and Inspect the Offending XSD File

  • Identify the exact schema file referenced in the error message’s Location: '%ls' placeholder.
  • Open the XSD in a validating editor (Visual Studio 2022/2025, Oxygen XML, or VS Code with the XML extension) rather than a plain text editor.
  • Search for the <xsd:list itemType="..."> declaration and note the type it references.

Step 2: Correct the itemType Reference

  • Verify the type referenced by itemType is declared with <xsd:simpleType> and not <xsd:complexType>.
  • If the referenced type is complex, either redefine it as a simple type (e.g., <xsd:restriction base="xsd:string">) or create a new simple type and point itemType to it.
  • Example fix:
  <xsd:simpleType name="ValidItem">
    <xsd:restriction base="xsd:string"/>
  </xsd:simpleType>
  <xsd:simpleType name="ItemList">
    <xsd:list itemType="ValidItem"/>
  </xsd:simpleType>

Step 3: Re-register the XML Schema Collection

  • In SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance, drop the existing faulty schema collection:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Re-create it using the corrected XSD file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
  AS N'<paste corrected XSD content here>';

Step 4: Validate Dependent Objects

  • Check any tables, stored procedures, or XML columns bound to this schema collection for compatibility with the updated type definitions.
  • Recompile affected stored procedures using sp_recompile if type changes impact parameter validation.

Alternative or Verification Steps

  • Run SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName'; to confirm the schema registered without error.
  • If the issue persists, validate the XSD independently using the xmllint --schema command-line tool or an online XSD validator to confirm W3C compliance before re-importing it into SQL Server.

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

Troubleshooting Guide: Error 2364 — “Cannot Implicitly Convert” in SQL Server 2025

Why This Error Happens

This error occurs when SQL Server’s type system encounters a mismatch between two incompatible data types during an implicit conversion attempt, typically within a T-SQL expression, stored procedure, or application query. Common root causes include comparing or joining columns of differing data types (such as varchar vs. int, or datetime2 vs. nvarchar), passing mismatched parameter types into a stored procedure, or corrupted/outdated query metadata following a schema change. Unlike explicit conversion errors, this specific message indicates SQL Server refuses to silently coerce the types because precision loss or ambiguity would result.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Data Types

  • Review the full error message text, which specifies the exact source (%ls) and target (%ls) data types involved.
  • Open SQL Server Management Studio (SSMS) and run the offending query in isolation to pinpoint the exact line number.
  • Use sp_help 'YourTableName' or query INFORMATION_SCHEMA.COLUMNS to confirm the declared data types of all columns referenced in the statement.

Step 2: Apply Explicit Type Casting

  • Modify the query to use CAST() or CONVERT() functions on the mismatched column or variable.
  • Example fix: SELECT * FROM Orders WHERE CAST(OrderID AS VARCHAR(10)) = @OrderIdParam
  • If working with stored procedures, update the CREATE PROCEDURE parameter definitions to match the exact data type expected by the calling application (check via sys.parameters).

Step 3: Validate Application Connection Strings and ORM Mappings

  • On Windows Server 2025/Windows 11, open your application’s configuration file (e.g., web.config, appsettings.json) and verify the data provider is not auto-mapping types incorrectly (common with Entity Framework or ODBC drivers).
  • Check the ODBC Data Source Administrator (odbcad32.exe) under Control Panel > Administrative Tools to confirm the driver version matches SQL Server 2025 requirements.
  • Update any outdated Microsoft.Data.SqlClient or System.Data.SqlClient NuGet packages to their latest versions, as older drivers mishandle newer type mappings (e.g., datetime2, sql_variant).

Step 4: Rebuild Affected Query Metadata

  • Run sp_recompile 'YourProcedureName' to force SQL Server to regenerate the execution plan and type-check metadata.
  • If the issue persists across multiple objects, run DBCC FREEPROCCACHE to clear the plan cache (use cautiously in production environments, ideally during a maintenance window).

Alternative or Verification Steps

  • Re-run the original query or application transaction and confirm Error 2364 no longer appears in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If the error persists after casting fixes, enable SQL Server Profiler or Extended Events to trace the exact statement and parameter values being sent from the client application, as the mismatch may originate from a hidden implicit conversion in a linked server or view definition.

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

Troubleshooting Guide: SQL Server Error 2365 — “Cannot explicitly convert from ‘%ls’ to ‘%ls'”

Why This Error Happens

This error occurs when a Transact-SQL statement attempts an explicit CAST or CONVERT operation between two data types that SQL Server’s type system does not support converting between (for example, converting a XML type directly to image, or an incompatible CLR user-defined type to a native type). It is almost always a query-authoring or schema-design issue rather than a server configuration fault, often introduced after a schema change, a column type alteration, or when code written for an older SQL Server version runs against SQL Server 2025’s updated type-compatibility matrix. It can also surface when linked server queries or application ORM layers (Entity Framework, Dapper, etc.) generate implicit type mappings that resolve to an unsupported explicit conversion under the hood.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Statement and Data Types Involved

  • Capture the full error message text, which includes the specific source type (%ls) and target type (%ls) SQL Server attempted to convert between.
  • Use SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance, and re-run the query in isolation to reproduce the error.
  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full statement context if the error originated from an application rather than an ad hoc query.

Step 2: Validate the Source and Target Column/Variable Definitions

  • Run sp_help 'TableName' or query INFORMATION_SCHEMA.COLUMNS to confirm the actual data types of the columns referenced in the failing statement.
  • Pay special attention to large object types (varchar(max), nvarchar(max), varbinary(max)), sql_variant, xml, geography/geometry, and CLR user-defined types, since these have the most restrictive explicit conversion rules.
  • Cross-reference Microsoft’s current “Data Type Conversion (Database Engine)” compatibility matrix for SQL Server 2025 to confirm whether the conversion path is supported at all, even via CONVERT with a style code.

Step 3: Rewrite the Query Using a Supported Conversion Path

  • Replace the unsupported direct CAST/CONVERT with a two-step conversion through an intermediate compatible type (e.g., convert xml to nvarchar(max) first, then to the final target type).
  • For CLR user-defined types, ensure the ToString() or a custom serialization method is used instead of relying on implicit engine-level conversion.
  • Update any ORM-generated SQL (Entity Framework, NHibernate) by adjusting the entity model’s column type mapping annotations so generated queries no longer attempt the invalid conversion.

Step 4: Check Database Compatibility Level

  • Run SELECT name, compatibility_level FROM sys.databases; to confirm the database is running under a compatibility level consistent with SQL Server 2025 behavior.
  • If the database was upgraded from an older version (e.g., SQL Server 2016/2019), legacy conversion behaviors may no longer apply; use ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170; and re-test.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator) if compatibility level changes do not take effect immediately for cached query plans.

Step 5: Clear Cached Execution Plans and Re-Test

  • Run DBCC FREEPROCCACHE; to eliminate stale execution plans that may have been compiled against outdated type metadata.
  • Re-execute the corrected query and confirm Error 2365 no longer appears in SSMS output or the ERRORLOG.

Alternative or Verification Steps

  • Verify the fix by running the corrected statement multiple times with representative production data (including NULLs and boundary values) to ensure the new conversion path handles all edge cases without truncation or silent data loss.
  • If the error persists after rewriting the conversion logic, use SELECT * FROM sys.dm_exec_query_stats combined with sys.dm_exec_sql_text to locate any other hidden or cached queries performing the same invalid conversion elsewhere in the application stack.

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

Why This Error Happens

Error 2362 occurs when SQL Server’s XML schema collection validator hits internal complexity limits while parsing an XSD definition, typically caused by excessive nesting levels, recursive type definitions, or an overly large number of declared elements/attributes within a single schema. This is a hard-coded parser limitation in the SQLOS XML engine, not a permissions or connectivity issue. It frequently surfaces after importing third-party XSDs (e.g., FHIR, SOAP/WSDL contracts) that were never optimized for relational XML Schema Collections.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE schema_id = SCHEMA_ID('dbo'); to locate the collection tied to the failing operation.
  • Check Event Viewer under Applications and Services Logs > Microsoft > SQL Server for the exact XSD file path referenced in the error text.
  • Export the raw XSD using SELECT xml_schema_namespace('dbo', 'YourCollectionName'); for offline inspection.

Step 2: Flatten and Simplify the XSD Structure

  • Open the exported schema in Visual Studio 2022 or an XML editor and reduce nested <xs:complexType> and <xs:sequence> depth to under 20 levels (SQL Server’s practical ceiling).
  • Remove circular/recursive type references (Type A referencing Type B referencing Type A).
  • Split large monolithic schemas into multiple smaller ADD SCHEMA batches using ALTER XML SCHEMA COLLECTION instead of one massive CREATE XML SCHEMA COLLECTION call.

Step 3: Re-import Using Chunked T-SQL Batches

  • Drop the broken collection: DROP XML SCHEMA COLLECTION dbo.YourCollectionName;
  • Re-create it in stages:
CREATE XML SCHEMA COLLECTION dbo.YourCollectionName AS '<xsd core content>';
GO
ALTER XML SCHEMA COLLECTION dbo.YourCollectionName ADD '<additional namespace chunk>';
GO
  • Confirm each ALTER batch stays under 4000 elements/attributes combined to avoid retriggering the complexity threshold.

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Configuration Manager and verify the current build via SELECT @@VERSION;
  • Download and install the latest CU from the Microsoft Update Catalog, as early SQL Server 2025 builds had a lower internal XSD node-count limit later patched upward.
  • Restart the SQL Server (MSSQLSERVER) service from services.msc after patching.

Alternative or Verification Steps

  • Verify success by re-running the original CREATE XML SCHEMA COLLECTION or application import job; Error 2362 should no longer appear in sys.messages logs or the SQL Server error log (%ProgramFiles%\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • If the schema cannot be simplified, store the XML as untyped XML data type columns instead of binding it to a Schema Collection, bypassing the XSD complexity check entirely.

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

Troubleshooting Guide: SQL Server Error 2363 – “%sXQuery too complex”

Why This Error Happens

This error occurs when SQL Server’s XML query processor hits an internal complexity threshold while parsing or optimizing an XQuery expression, typically due to deeply nested predicates, excessive FLWOR expressions, or overly long path expressions within a single XML data type method call. The query optimizer allocates a finite amount of memory and recursion depth for compiling XQuery execution trees, and once that limit is exceeded, compilation aborts rather than risking server instability. This is frequently triggered after migrating large XML-heavy workloads to SQL Server 2025, where stricter resource governance on Windows Server 2025 can lower the effective complexity ceiling compared to older environments.

Step-by-Step Resolution Guide

Step 1: Identify and Isolate the Offending Query

  • Enable SQL Server Profiler or Extended Events to capture the exact statement raising Error 2363.
  • Look for calls using .query(), .value(), .nodes(), or .exist() methods on XML columns with heavy nested predicates.
  • Run SELECT * FROM sys.dm_exec_query_stats cross-referenced with sys.dm_exec_sql_text to pinpoint the plan handle associated with the failure.

Step 2: Simplify the XQuery Expression

  • Break down complex nested FLWOR (for, let, where, order by, return) expressions into multiple smaller queries using temporary tables or table variables.
  • Replace deeply chained .query() calls with intermediate shredding into relational columns using OPENXML or .nodes() with a simpler XPath.
  • Avoid combining more than 3–4 predicate conditions within a single [...] XPath filter; split them into sequential WHERE clauses instead.

Step 3: Adjust Server-Level XML Processing Limits

  • Open SQL Server Management Studio (SSMS) and connect to the instance via Object Explorer.
  • Navigate to Server Properties > Advanced and verify the max worker threads and index create memory settings are not artificially constrained, as low memory grants can lower the XQuery compile budget.
  • On Windows Server 2025, check Local Group Policy Editor > Computer Configuration > Administrative Templates > SQL Server Resource Governor (if configured) and ensure the resource pool assigned to the SQL Server service account has sufficient MAX_MEMORY_PERCENT.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after any changes.

Step 4: Rebuild XML Indexes and Update Statistics

  • Run ALTER INDEX ALL ON [YourTable] REBUILD; on tables containing the XML columns referenced in the failing query.
  • Execute UPDATE STATISTICS [YourTable] WITH FULLSCAN; to ensure the optimizer has accurate cardinality estimates, which can reduce plan complexity.
  • Confirm the XML schema collection (if used) isn’t outdated by checking sys.xml_schema_collections.

Step 5: Apply the Latest Cumulative Update

  • Check Windows Update or the Microsoft Update Catalog for the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the CU using the standalone installer, ensuring you run it as Administrator on Windows Server 2025.
  • Reboot the server if prompted and re-validate the SQL Server version using SELECT @@VERSION;.

Alternative or Verification Steps

  • To verify the fix, re-run the original failing query in SSMS and confirm it returns results without raising Error 2363; also check the SQL Server Error Log (via EXEC sp_readerrorlog) for recurrence.
  • As an alternative, if simplification isn’t feasible, convert the XML column’s complex query logic into a CLR (Common Language Runtime) stored procedure, which bypasses the native XQuery compiler’s complexity limits entirely.

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

Why This Error Happens

Error 2360 occurs when SQL Server 2025 parses an XML Schema Definition (XSD) and encounters an element or attribute declaration that specifies both a name and a ref attribute simultaneously, which violates the W3C XML Schema specification. This typically happens when a custom XML Schema Collection is registered with malformed XSD syntax, or when a third-party tool generates XSD files for SSIS packages, XML columns, or SOAP endpoints with conflicting declarations. It can also surface after a failed in-place upgrade from SQL Server 2022 to 2025, where legacy schema collections were not revalidated against the stricter 2025 XML parser.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema File

  • Review the full error message for the Location: '%ls' value — this points to the exact XSD file path or XML Schema Collection name causing the conflict.
  • Run the following query to locate schema collections in the affected database:
  SELECT name, schema_namespace, xml_schema_namespace_id 
  FROM sys.xml_schema_collections;
  • Export the suspect schema using SELECT xml_schema_namespace('dbo','SchemaName') to inspect its raw XSD content.

Step 2: Correct the XSD Declaration

  • Open the XSD file in a text editor or Visual Studio 2022/2025 XML editor.
  • Locate the <xs:element> or <xs:attribute> node that has both name="..." and ref="..." set.
  • Per XSD rules, keep only one: use name when defining a new element locally, or use ref when referencing an already-declared global element — remove the redundant attribute.
  • Save the corrected file with UTF-8 encoding (no BOM) to avoid secondary parsing errors.

Step 3: Re-register the XML Schema Collection

  • Drop the broken collection if it partially registered:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaName;
  • Re-create it using the corrected XSD file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaName AS N'<corrected XSD content>';
  • If the error originated from an SSIS package or SSDT project, right-click the .dtsx/.xsd reference in Solution Explorer and select Validate XML before redeploying.

Step 4: Clear Cached Metadata (Windows Server 2025 / Windows 11)

  • Restart the SQL Server (MSSQLSERVER) service via services.msc or:
  Restart-Service -Name MSSQLSERVER -Force
  • Clear the SSISDB cache if applicable by running exec [SSISDB].[catalog].[clean_logs] to remove stale schema references tied to failed deployments.

Alternative or Verification Steps

  • Verify the fix by re-running the query/import operation that triggered Error 2360; confirm sys.xml_schema_collections now shows the schema without errors using SELECT * FROM sys.dm_exec_describe_xml_schema_collection(...).
  • If the issue persists, use the XSD Schema Validation Tool (xsd.exe from the Windows SDK) locally to lint the file independently of SQL Server — this isolates whether the error is in the SQL Server parser or the source XSD itself.

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

Troubleshooting Guide: Error 2361 – XSD Extension/Restriction Base Type Must Be Simple Type

Why This Error Happens

This error occurs when SQL Server 2025’s XML Schema Collection parser encounters an XSD definition where a complexType is used as the base type for an xs:extension or xs:restriction element, which violates XML Schema specification rules. This typically happens due to a malformed or hand-edited XSD file, a corrupted schema collection registered in the database, or a third-party export tool generating non-compliant XSD structures. Additionally, on Windows Server 2025/Windows 11 environments, outdated SQLXML provider components or mismatched .NET Framework XML libraries can cause valid schemas to be misinterpreted during validation.

Step-by-Step Resolution Guide

Step 1: Validate the XSD File Structure Independently

  • Open the offending .xsd file in Visual Studio 2022+ or an XML validator tool (e.g., xmllint) outside of SQL Server.
  • Locate the <xs:extension base="..."> or <xs:restriction base="..."> tag and confirm the referenced base attribute points to a simpleType, not a complexType.
  • Run xmllint --schema base.xsd target.xsd --noout from PowerShell to isolate the exact line number causing the conflict.

Step 2: Correct the Base Type Definition

  • If the base type is incorrectly defined as <xs:complexType name="BaseType">, change the extension to use <xs:complexContent> wrapping instead of a direct simple extension.
  • For simple value inheritance, ensure the base type is defined strictly as <xs:simpleType name="BaseType"> with a valid <xs:restriction base="xs:string"> (or appropriate primitive type) inside it.
  • Save the corrected file and re-import it into your project directory (e.g., C:\SQLServer\Schemas\).

Step 3: Drop and Re-register the Schema Collection in SQL Server

  • Connect to the instance via SQL Server Management Studio (SSMS) 21.
  • Execute DROP XML SCHEMA COLLECTION [dbo].[YourSchemaName]; to remove the cached corrupted version.
  • Re-create it using the corrected file:
  CREATE XML SCHEMA COLLECTION [dbo].[YourSchemaName] 
  AS N'C:\SQLServer\Schemas\corrected_schema.xsd';
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to clear any cached schema validation metadata.

Step 4: Update SQL Server Native Client Components

  • Navigate to Control Panel > Programs and Features on the Windows Server 2025 host.
  • Verify that the Microsoft OLE DB Driver for SQL Server and SQLXML 6.0 components are updated to the latest build compatible with SQL Server 2025.
  • If missing, download and install the latest redistributable from the official Microsoft Download Center to ensure XSD parsing libraries are current.

Alternative or Verification Steps

  • To verify the fix, run a test INSERT or CAST operation against a column bound to the schema collection; if Error 2361 does not resurface, the schema is valid.
  • If the error persists after correction, bypass the native validator temporarily by setting the column to untyped XML (without schema binding) to confirm the data payload itself is valid before re-binding the collection.

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

Troubleshooting Guide: SQL Server Error 2358 — XML Schema Derivation Conflict

Why This Error Happens

This error occurs when SQL Server’s XML Schema Collection parser encounters a complexType definition that simultaneously declares a base attribute (via restriction or extension) and contains an embedded (anonymous) type definition within the same derivation element. SQL Server 2025’s XML parser does not support this dual-declaration pattern, as it creates ambiguity in how the schema should resolve type inheritance. This typically surfaces when importing third-party XSD files, migrating schema collections from an older SQL Server version, or when a schema was hand-edited and introduced a malformed derivation block.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema File and Location

  • Review the full error message — it includes a Location: '%ls' path pointing to the exact XSD file or XML Schema Collection object causing the conflict.
  • Run the following query to locate the schema collection in question:
  SELECT name, schema_id, xml_schema_namespace 
  FROM sys.xml_schema_collections 
  WHERE name LIKE '%YourSchemaName%';
  • Export the raw schema definition for inspection:
  SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');

Step 2: Correct the Malformed Complex Type Definition

  • Open the exported XSD in a text editor and search for <xs:complexContent> or <xs:simpleContent> elements that contain both a base="..." attribute and a nested <xs:sequence>, <xs:choice>, or <xs:all> block defined directly alongside it.
  • Separate the derivation logic: either use the base attribute with restriction/extension referencing an already-defined named type, OR define the embedded type anonymously — never both within the same node.
  • Example fix — change this invalid structure:
  <xs:complexType name="Invalid">
    <xs:complexContent>
      <xs:extension base="BaseType">
        <xs:complexType>
          <xs:sequence>...</xs:sequence>
        </xs:complexType>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

to a valid single-level derivation referencing a named type instead of nesting an embedded one.

Step 3: Re-register the XML Schema Collection

  • Drop the broken schema collection (if already partially registered):
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Re-create it using the corrected XSD file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName 
  AS N'<paste corrected XSD content here>';
  • Confirm there are no residual references in dependent tables or XML columns that still point to the old, invalid schema version.

Step 4: Validate Third-Party or Legacy Schema Sources

  • If the XSD originated from an external vendor or legacy system, check for an updated schema version compatible with SQL Server 2025’s stricter XML parser.
  • Run the corrected file through an independent XSD validator (such as xmllint --schema on Windows via WSL, or Visual Studio’s XML Schema Designer) before re-importing into SQL Server.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE XML SCHEMA COLLECTION statement and confirming it completes without Error 2358, then test any dependent stored procedures or XML column constraints that reference the schema.
  • If re-authoring the schema isn’t feasible, use sp_xml_schema_validate or a staging environment on a prior-compatible SQL Server version to pre-process and simplify the schema before migrating it to SQL Server 2025.

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

Why This Error Happens

This error occurs when an XML Data Modification Language (DML) statement—such as insert, delete, or replace value of—attempts to target a node that was generated dynamically (e.g., through a nodes() function result that was already transformed, a derived table, or a computed expression) rather than a node that exists persistently in an xml-typed column. SQL Server’s XQuery engine requires a direct, stable reference to the underlying storage node in order to apply a mutation, and a “constructed” node (one created in memory via a function or expression) has no addressable location to write back to. This typically surfaces after application updates, ORM-generated queries, or migration scripts that use nested .query() or .nodes() calls incorrectly in UPDATE statements.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML DML Statement

  • Enable statement-level logging or check SQL Server Profiler/Extended Events for the exact query raising Error 2359.
  • Look specifically for .modify('insert ...'), .modify('delete ...'), or .modify('replace value of ...') calls in stored procedures or application code.
  • Confirm the target path inside the modify() call references a column directly, not a subquery result.

Step 2: Correct the XQuery Target Reference

  • Rewrite the query so the modify() method is called directly against the xml column in the base table, not against an aliased or joined derived table.
  • Example of the problem:
  UPDATE t
  SET t.XmlCol.modify('insert <Node/> into (/Root)[1]')
  FROM (SELECT XmlCol FROM MyTable) AS t
  • Example of the fix:
  UPDATE MyTable
  SET XmlCol.modify('insert <Node/> into (/Root)[1]')
  WHERE PrimaryKeyID = @ID
  • Ensure the WHERE clause isolates the exact row(s) using the primary key rather than filtering through a joined or computed source.

Step 3: Validate XML Schema Collection Compatibility

  • If the column uses a typed XML schema collection, run sys.xml_schema_collections to confirm the schema matches the structure being inserted/modified.
  • Drop and recreate the schema collection binding if it was altered during a recent SQL Server 2025 upgrade:
  ALTER TABLE MyTable
  ALTER COLUMN XmlCol XML (SchemaCollectionName)

Step 4: Test in Isolation on Windows Server 2025

  • Reproduce the failing statement in SQL Server Management Studio (SSMS) or Azure Data Studio directly on the Windows Server 2025 host, bypassing the application layer.
  • Confirm the SQL Server service account has appropriate ALTER and UPDATE permissions on the target table (check via sys.fn_my_permissions('MyTable', 'OBJECT')).

Alternative or Verification Steps

  • Re-run the corrected UPDATE/.modify() statement and confirm it completes without Error 2359; verify data integrity afterward with SELECT XmlCol FROM MyTable WHERE PrimaryKeyID = @ID.
  • If the issue persists, convert the operation to a two-step process: first SELECT the XML into a variable, run the XQuery .modify() against the local variable, then UPDATE the table using the fully modified variable value.

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

Why This Error Happens

Error 2355 occurs when the T-SQL parser encounters an IF block or CASE statement where the expected ELSE keyword is either missing, misplaced, or malformed due to a syntax mismatch. This typically happens when a script contains unbalanced BEGIN...END blocks, a misplaced semicolon terminating the IF clause prematurely, or when legacy scripts generated by older SSMS versions are run against the stricter parser in SQL Server 2025. It can also surface during automated deployment pipelines where a templating engine incorrectly injects a newline or comment between the IF condition and its corresponding ELSE clause.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Script Block

  • Open the specific stored procedure, trigger, or script referenced in the SQL Server Error Log using SQL Server Management Studio (SSMS) 21.
  • Locate the exact line number provided in the error details (usually found in the “Procedure” column of the error output).
  • Check for a semicolon (;) immediately following the IF condition’s END statement, as this breaks the association with the subsequent ELSE.

Step 2: Validate Block Structure and Syntax

  • Ensure every BEGIN keyword within the IF statement has a corresponding END keyword before the ELSE is declared.
  • Remove any comments (-- or /* */) placed directly between the END of the IF block and the ELSE keyword, as the 2025 parser can sometimes misinterpret complex nested comments in this specific gap.
  • Rewrite the conditional logic using explicit BEGIN...END blocks for both the IF and ELSE sections to eliminate ambiguity:
  IF (1=1)
  BEGIN
      PRINT 'True';
  END
  ELSE
  BEGIN
      PRINT 'False';
  END

Step 3: Clear the Plan Cache and Re-deploy

  • Clear the procedure cache to ensure the old, broken query plan is not being reused during compilation attempts.
  • Run the following command in a new query window: DBCC FREEPROCCACHE;
  • Re-deploy the corrected script or recompile the stored procedure using EXEC sp_recompile 'YourProcedureName';

Step 4: Check Compatibility Level Settings

  • Verify the database compatibility level is correctly set, as SQL Server 2025 introduces stricter parsing under higher compatibility levels (170).
  • Navigate to Database Properties > Options in SSMS and check the “Compatibility Level” dropdown.
  • If the script was written for an older engine, temporarily test compatibility level 160 to confirm if the parser behavior changes.

Alternative or Verification Steps

  • Execute the corrected script via sqlcmd from a command prompt to verify it parses without errors outside of the GUI environment: sqlcmd -S localhost -i C:\Scripts\FixedScript.sql
  • If the error persists after fixing syntax, use the SSMS Query > Parse feature (Ctrl+F5) to validate the T-SQL syntax tree before execution to pinpoint hidden whitespace or encoding issues.

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

Troubleshooting Guide: SQL Server Error 2356 — “The target of ‘replace value of’ must be a non-metadata attribute or an element with simple typed content”

Why This Error Happens

This error occurs when SQL Server’s XML processing engine attempts to execute an XQuery replace value of expression against a target node that does not qualify as a simple-typed element or attribute. In Microsoft SQL Server 2025, this typically happens when the XQuery path resolves to an element containing complex content (such as child elements or mixed content) rather than a single text/attribute node. It can also surface due to schema drift in XML indexes, corrupted XML column metadata, or a mismatch between the XML schema collection bound to the column and the actual document structure being modified.

Step-by-Step Resolution Guide

Step 1: Validate the XQuery Target Node Structure

  • Run a SELECT query using .query() on the same XPath used in your .modify('replace value of ...') statement to confirm the node is a leaf node.
  • Confirm the target does not contain nested child elements — replace value of only works on simple-typed content.
  • Example check:
  SELECT XmlColumn.query('/Root/Element[1]') FROM YourTable;

Step 2: Inspect and Repair XML Schema Collection Bindings

  • Navigate to SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and expand Databases > [YourDB] > Programmability > Types > XML Schema Collections.
  • Run the following to check for schema mismatches:
  SELECT name, xml_collection_id FROM sys.xml_schema_collections;
  • If the schema collection is outdated or corrupted, drop and re-bind it using ALTER XML SCHEMA COLLECTION or re-import the .xsd file via T-SQL.

Step 3: Rebuild Affected XML Indexes

  • Open an elevated PowerShell or SQLCMD session on your Windows Server 2025 host.
  • Rebuild primary and secondary XML indexes to clear stale metadata pointers:
  ALTER INDEX ALL ON YourTable REBUILD;
  • Confirm there are no orphaned index fragments by checking sys.xml_indexes.

Step 4: Correct the .modify() Syntax to Target a Single Node

  • Rewrite the XQuery to explicitly target an atomic-valued node using [1] positional indexing to avoid ambiguous node sets.
  • Example fix:
  UPDATE YourTable
  SET XmlColumn.modify('replace value of (/Root/Element[1]/text())[1] with "NewValue"')
  WHERE Id = 1;
  • Ensure the path does not accidentally resolve to an element with sub-elements.

Step 5: Clear SQL Server Plan Cache and Restart the Service (If Needed)

  • If the error persists due to cached execution plans referencing old schema metadata, clear the plan cache:
  DBCC FREEPROCCACHE;
  • Restart the SQL Server service via Services.msc or Restart-Service MSSQLSERVER in PowerShell on Windows Server 2025.

Alternative or Verification Steps

  • Re-run the original UPDATE ... .modify('replace value of ...') statement and confirm it completes without Error 2356 in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If the issue persists, use .modify('replace value of (expression)[1] with (...)') with an explicit text() node cast, or fall back to .modify('delete ...') followed by .modify('insert ...') to fully replace the element structure.

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

Troubleshooting Guide: SQL Server Error 2357 – “A document node may only be replaced with another document node”

Why This Error Happens

This error occurs when an application or T-SQL script attempts to use the modify() method of the xml data type to replace a top-level document node with a non-document node (such as a fragment or element without a single root). SQL Server’s XML schema validation enforces strict hierarchy rules, and the XQuery replace value of expression fails when the target and replacement node types do not match structurally. This is typically caused by malformed XML modification logic in stored procedures, corrupted XML column data, or an outdated application layer generating improperly structured XML fragments.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Stored Procedure

  • Enable SQL Server Profiler or Extended Events to capture the exact T-SQL statement triggering Error 2357.
  • Filter for Error Number = 2357 under the Errors and Warnings event category.
  • Note the associated SPID, stored procedure name, and the XML column involved.

Step 2: Review and Correct the XML .modify() Syntax

  • Open the stored procedure or script in SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025).
  • Check the replace value of clause — ensure you are not targeting (/*)[1] (the document node) with a replacement that isn’t also a full document node.
  • Correct example:
  SET @xmlData.modify('replace value of (/root/element/text())[1] with "NewValue"')
  • Avoid replacing (/)[1] directly; target a specific child node instead.

Step 3: Validate XML Schema Collections (if XSD-bound)

  • Run the following to check if the column is bound to an XML Schema Collection:
  SELECT c.name, xsc.name AS SchemaCollection
  FROM sys.columns c
  JOIN sys.xml_schema_collections xsc 
      ON c.xml_collection_id = xsc.xml_collection_id
  WHERE c.object_id = OBJECT_ID('YourTableName');
  • If a schema collection exists, confirm the replacement node structure matches the XSD-defined root element exactly.

Step 4: Rebuild or Repair Corrupted XML Data

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying page-level corruption affecting the XML binary large object (BLOB).
  • If corruption is found, restore the affected table/database from the last known good backup via RESTORE DATABASE ... WITH RECOVERY.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog and confirm you are on the latest Cumulative Update (CU) for SQL Server 2025.
  • On Windows Server 2025, verify via:
  SELECT @@VERSION;
  • Install any pending CU through SQL Server Setup → Maintenance → Edition Upgrade/Patch to ensure known XQuery engine bugs are patched.

Alternative or Verification Steps

  • Re-run the original query in a test environment (non-production) using SET STATISTICS XML ON to confirm the .modify() call executes without raising Error 2357.
  • If the issue persists after code correction, isolate the XML column into a temporary untyped xml variable (remove schema binding temporarily) to confirm whether the XSD schema collection is the root cause.

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

Why This Error Happens

Error 2353 is a T-SQL parser error that occurs when the CREATE TRIGGER or ALTER TRIGGER statement has an invalid or incomplete event clause. SQL Server expects the keywords INSERT, UPDATE, or DELETE immediately following the FOR or AFTER/INSTEAD OF clause, but finds an unrecognized token, a typo, or a missing comma between multiple trigger events instead. This is almost always caused by a malformed script—either hand-written or generated by a third-party migration/ORM tool—rather than a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Trigger Script

  • Open the script or stored procedure that raised the error in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Identify the exact CREATE TRIGGER or ALTER TRIGGER statement referenced in the error message line number.
  • Check the syntax template: CREATE TRIGGER trigger_name ON table_name FOR [INSERT],[UPDATE],[DELETE] AS BEGIN ... END.

Step 2: Correct the Trigger Event Clause

  • Verify that FOR, AFTER, or INSTEAD OF is directly followed by one or more of the valid keywords: INSERT, UPDATE, DELETE.
  • Ensure multiple events are separated by commas, not spaces or semicolons (e.g., FOR INSERT, UPDATE).
  • Remove any stray characters, extra parentheses, or copy-paste artifacts (common when scripts are exported from mssql-scripter or legacy SQL Server 2000/2005 tools).

Step 3: Validate Against SQL Server 2025 Syntax Changes

  • Confirm the database compatibility level is set correctly for SQL Server 2025 by running:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If compatibility level is below 170, consider updating it with:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-run the corrected CREATE TRIGGER statement in a new query window to isolate it from other batch statements.

Step 4: Rebuild and Redeploy the Trigger

  • Drop the broken trigger if a partial object was created: DROP TRIGGER trigger_name;
  • Re-create the trigger using the corrected syntax in a transaction block so you can roll back on failure:
  BEGIN TRANSACTION;
  CREATE TRIGGER trg_Example ON dbo.YourTable
  AFTER INSERT, UPDATE
  AS
  BEGIN
      SET NOCOUNT ON;
  END;
  COMMIT TRANSACTION;
  • Check the Windows Event Viewer (Application log) on Windows Server 2025 for any additional SQL Server engine errors tied to the same timestamp.

Alternative or Verification Steps

  • Run sys.triggers and sys.sql_modules to confirm the trigger definition was stored correctly: SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('trg_Example');
  • If the error persists after syntax correction, use the built-in SQL Server Query Editor IntelliSense (enable via Tools > Options > Text Editor > Transact-SQL) to catch malformed keywords in real time before execution.

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

Troubleshooting Guide: SQL Server Error 2354 – Invalid Source Character Encoding

Why This Error Happens

This error typically occurs when SQL Server 2025 encounters a data import or ETL operation where the source file’s character encoding does not match the encoding expected by the destination collation settings. It is commonly triggered by BCP, BULK INSERT, or SSIS operations reading flat files saved in an unsupported or mismatched format (such as UTF-8 without a BOM, or extended ASCII) when the server expects UTF-16 or a specific code page. Corrupted or truncated source files can also trigger this error even when encoding settings are technically correct.

Step-by-Step Resolution Guide

Step 1: Verify the Source File Encoding

  • Open the source file in a text editor like VS Code or Notepad++ and check the encoding indicator in the status bar.
  • Confirm whether the file is saved as UTF-8, UTF-8-BOM, UTF-16 LE, or ANSI.
  • Run file -i sourcefile.csv if using WSL or a Linux-based utility to cross-check encoding metadata.

Step 2: Align the Format File or Import Statement with the Correct Encoding

  • If using BULK INSERT or BCP, explicitly declare the CODEPAGE parameter in your T-SQL command (e.g., CODEPAGE = '65001' for UTF-8).
  • For BCP operations, regenerate the format file using bcp dbo.TableName format nul -c -t, -f C:\Formats\table.fmt -U sa -P password -S ServerName.
  • Ensure the DATAFILETYPE parameter matches the actual file type (char, native, widechar, or widenative).

Step 3: Re-Save or Convert the Source File

  • Use PowerShell to force a clean re-encoding pass: Get-Content C:\Data\source.csv | Set-Content -Encoding UTF8 C:\Data\source_fixed.csv.
  • If the file originated from a non-Windows system, strip any stray BOM characters using a hex editor to confirm no leading byte-order-mark artifacts remain.
  • Re-attempt the import process against the newly saved file.

Step 4: Check Database and Column-Level Collation Settings

  • Navigate to SQL Server Management Studio (SSMS) and right-click the target database > Properties > Options to confirm the default collation.
  • Run SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('dbo.TableName'); to verify no column-level collation conflicts exist.
  • Adjust collation to a Unicode-compatible setting (e.g., Latin1_General_100_CI_AS_SC_UTF8) if cross-language characters are involved.

Alternative or Verification Steps

  • After re-running the import, query the affected table with SELECT TOP 100 * FROM dbo.TableName WHERE Column1 LIKE '%?%'; to check for unexpected replacement characters indicating lingering encoding mismatches.
  • If the error persists, bypass BCP/BULK INSERT entirely and import the dataset through SSIS using a Flat File Source component, manually setting the “Code Page” property in the Connection Manager to match the verified source encoding from Step 1.

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

Why This Error Happens

Error 2350 occurs when SQL Server’s XML parser encounters malformed or unexpected content while processing an XML document, schema collection, or configuration file—most commonly triggered by invalid characters, improperly escaped entities, or a mismatch between the XML data and its associated XSD schema. This frequently happens after importing XML data from external sources (APIs, flat files, or third-party applications) that don’t conform to well-formed XML standards. It can also surface when SQL Server Management Objects (SMO) or Policy-Based Management files have been corrupted or manually edited incorrectly.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Invalid XML

  • Run the failing query or import process in SQL Server Management Studio (SSMS) with SET FMTONLY OFF to capture the exact XML payload.
  • Use SELECT CAST(your_xml_column AS XML) on a copy of the data in a test table to isolate which row or element triggers the error.
  • Check for unescaped special characters (&, <, >) that haven’t been converted to entities (&amp;, &lt;, &gt;).

Step 2: Validate Against the XML Schema Collection

  • If using a typed XML column, run SELECT * FROM sys.xml_schema_collections to confirm the correct schema is bound.
  • Validate the XML manually against the schema using PowerShell:
  [System.Xml.Schema.XmlSchema]::Read(...)
  • Look for missing namespaces, incorrect element ordering, or unclosed tags that violate the schema definition.

Step 3: Repair or Re-Import Clean Data

  • Strip or sanitize invalid characters at the source (e.g., using REPLACE() or a pre-processing script) before inserting into SQL Server.
  • If importing via SSIS, open the package in Visual Studio and inspect the XML Source component’s error output path for the exact byte offset causing the failure.
  • Re-run the import after correcting the source file using a validated XML editor (e.g., Visual Studio Code with XML extension).

Step 4: Check for Corrupted Configuration Files (if error is server-side)

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ and inspect the ERRORLOG for the full stack trace.
  • If the error relates to Policy-Based Management or Maintenance Plans, verify the XML stored in msdb.dbo.sysxmitqueue or policy definition tables isn’t corrupted.
  • Restore the affected configuration from a known-good backup if corruption is confirmed.

Alternative or Verification Steps

  • Re-run the original query or import job and confirm no Error 2350 appears in SSMS or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, use sp_xml_preparedocument with explicit error handling in a TRY...CATCH block to gracefully log and skip malformed XML rows instead of halting the entire batch.

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

Why This Error Happens

Error 2351 is a T-SQL parser error that occurs when SQL Server encounters a RANGE clause (most commonly inside a CREATE PARTITION FUNCTION statement or an OFFSET/FETCH boundary clause) where it expects the keyword FIRST or LAST to define which side of the boundary value the partition belongs to, but finds an invalid token instead. This is typically caused by hand-edited or auto-generated DDL scripts (often produced by older SSDT/DACPAC tooling or migration scripts) that were written against an older T-SQL grammar and are missing the required keyword. It can also surface after an in-place upgrade to SQL Server 2025 if the database compatibility level has not been updated to match the new parser rules.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Script

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and re-run the failing script in isolation to capture the exact line number referenced in the error output.
  • Check deployment logs under C:\Program Files\Microsoft SQL Server\160\DTS\Binn\ (or your SSDT output folder) if the script was generated via a DACPAC publish.

Step 2: Correct the Partition Function Syntax

  • Inspect the CREATE PARTITION FUNCTION or RANGE clause and ensure it explicitly states RANGE LEFT FOR VALUES (...) or RANGE RIGHT FOR VALUES (...).
  • Add the missing FIRST or LAST keyword where required, for example:
  CREATE PARTITION FUNCTION PF_Range (int)
  AS RANGE LEFT FOR VALUES (10, 20, 30);
  • If the script uses OFFSET...FETCH, confirm the correct syntax is FETCH FIRST n ROWS ONLY or FETCH NEXT n ROWS ONLY rather than a malformed hybrid.

Step 3: Validate Database Compatibility Level

  • Run the following to confirm the database is set to the SQL Server 2025 compatibility level (170):
  SELECT name, compatibility_level FROM sys.databases;
  ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170;
  • Re-run the script after updating the compatibility level, as older levels can cause the parser to reject newer or reorganized grammar paths.

Step 4: Update Deployment Tooling

  • If the script originates from SSDT/DACPAC, update Visual Studio/SSDT to the latest build that supports SQL Server 2025 T-SQL syntax, since outdated tooling can emit deprecated RANGE clause formats.
  • Re-generate and re-publish the DACPAC after the tooling update.

Alternative or Verification Steps

  • Re-execute the corrected script in a test database and confirm it completes without Error 2351, then verify partition boundaries with sys.partition_range_values.
  • If the error persists, run DBCC FREEPROCCACHE to clear any cached malformed plans, then restart the SQL Server service via services.msc on Windows Server 2025/Windows 11 before retesting.

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

Troubleshooting Guide: SQL Server Error 2348 — “A namespace URI should contain at least one non-whitespace character”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to parse an XML schema or SSIS package configuration that contains a malformed or empty xmlns (namespace) attribute. It is typically triggered by corrupted SSIS package XML files, improperly exported/imported DTSX packages, or manual edits to configuration files that leave a namespace declaration blank or filled with only whitespace characters. Third-party deployment tools or source control merge conflicts can also introduce stray whitespace into XML namespace URIs during automated builds.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML File

  • Check the SQL Server Agent job history or SSIS execution logs for the exact package (.dtsx) or configuration file (.xml) referenced alongside Error 2348.
  • Open Event Viewer on Windows Server 2025 under Applications and Services Logs > Microsoft > SQL Server to confirm the timestamp and associated file path.
  • Use findstr /s /i "xmlns=\"\"" C:\SSIS\Packages\*.dtsx in Command Prompt to quickly scan for empty namespace declarations.

Step 2: Repair the Malformed Namespace Declaration

  • Open the identified .dtsx or .xml file in a text editor such as VS Code or Notepad++ (not Notepad, to preserve encoding).
  • Search for any xmlns=" or xmlns:xsi=" entries followed immediately by a closing quote or only spaces/tabs before the closing quote.
  • Replace the blank value with the correct, fully qualified namespace URI (e.g., xmlns="www.microsoft.com/SqlServer/Dts" for SSIS packages).
  • Save the file using UTF-8 encoding without BOM to avoid introducing hidden whitespace characters.

Step 3: Validate and Re-import the Package

  • Open SQL Server Management Studio (SSMS) 2025 and connect to the Integration Services catalog.
  • Right-click the SSISDB catalog, select Validate, and re-deploy the corrected package using dtutil /FILE "C:\SSIS\Packages\PackageName.dtsx" /COPY SQL;PackageName.
  • If the package was stored in msdb, run EXEC msdb.dbo.sp_validatepackage to confirm the XML structure passes schema validation.

Step 4: Clear Cached Package Metadata

  • Restart the SQL Server Integration Services 18.0 service via services.msc on Windows Server 2025 to flush any cached package metadata referencing the broken namespace.
  • Clear the local SSIS package cache folder, typically located at C:\Program Files\Microsoft SQL Server\160\DTS\Packages, after backing up the originals.

Alternative or Verification Steps

  • Re-run the SSIS job or query that originally triggered Error 2348 and confirm it completes without namespace-related warnings in the SQL Server Agent Job History.
  • If the error persists, use an XML validator (e.g., xmllint --noout file.dtsx) to pinpoint any remaining schema violations, or restore the package from a known-good backup and reapply recent changes manually.

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

Troubleshooting Guide: SQL Server Error 2349 – “Attempt to Redefine Namespace Prefix”

Why This Error Happens

Error 2349 occurs when SQL Server’s XML parser encounters a document where the same namespace prefix (e.g., xmlns:ns1) is declared more than once with conflicting URI values within the same scope. This is typically caused by malformed XML being passed into a FOR XML query, an OPENXML call, or an XML schema collection, often due to improperly concatenated XML fragments or a corrupted source document. It can also surface during SSIS package execution or application-layer XML generation where prefixes are hardcoded rather than dynamically managed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source

  • Capture the exact query or stored procedure throwing the error using SQL Server Profiler or Extended Events on your Windows Server 2025 instance.
  • Check if the XML is being built via string concatenation (+=) rather than native FOR XML PATH or FOR XML AUTO constructs.
  • Export the raw XML payload to a .xml file for manual inspection.

Step 2: Validate and Correct Namespace Declarations

  • Open the exported XML in Visual Studio Code or Visual Studio 2022 and look for duplicate xmlns:prefix attributes with different URIs at nested or sibling node levels.
  • Ensure every custom prefix (e.g., xmlns:ns1="uri1") is declared only once per scope; rename conflicting prefixes to unique values like ns1, ns2.
  • If using WITH XMLNAMESPACES in your T-SQL query, verify you are not redeclaring a prefix already defined in the source XML being merged.

Step 3: Fix the T-SQL Query Construction

  • Rewrite the query using explicit namespace handling:
WITH XMLNAMESPACES ('http://example.com/ns1' AS ns1)
SELECT * FROM YourTable
FOR XML PATH('Root'), ELEMENTS
  • Avoid manually injecting xmlns strings into XML columns via CAST or CONVERT; let SQL Server manage prefix serialization natively.

Step 4: Check XML Schema Collections (If Applicable)

  • Run SELECT * FROM sys.xml_schema_collections; to see if a registered schema collection enforces a conflicting namespace prefix.
  • If found, drop and recreate the schema collection using DROP XML SCHEMA COLLECTION and CREATE XML SCHEMA COLLECTION with corrected namespace mappings.

Step 5: Rebuild Corrupted XML Indexes (If Error Persists on Storage)

  • If the XML is stored in a column with a primary/secondary XML index, rebuild it:
ALTER INDEX ALL ON YourTable REBUILD;
  • This clears any cached malformed structure that may be re-triggering the parser error on retrieval.

Alternative or Verification Steps

  • Re-run the original query or SSIS package after applying fixes; confirm Error 2349 no longer appears in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • As a quick alternative, validate the XML externally using an XSD/XML validator tool before insertion to catch prefix conflicts upstream, preventing the malformed data from ever reaching SQL Server.

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

Troubleshooting Guide: SQL Server Error 2342 – Invalid Numeric Constant

Why This Error Happens

This error typically occurs when SQL Server’s parser encounters a numeric literal that violates T-SQL syntax rules, such as malformed decimal points, invalid scientific notation, or regional/locale formatting mismatches (e.g., using commas instead of periods as decimal separators). It can also arise from corrupted query scripts, improperly escaped characters in dynamically generated SQL, or data import files containing non-numeric characters (like currency symbols or stray whitespace) in fields mapped to numeric columns. In some cases, this is triggered by a collation or regional settings mismatch between the client application and the SQL Server instance on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Query or Script

  • Review the exact T-SQL statement referenced in the error log or application stack trace.
  • Check for malformed numeric literals, such as 1,234.56 (invalid) instead of 1234.56 (valid).
  • Run the query manually in SQL Server Management Studio (SSMS) to reproduce the error in isolation.

Step 2: Validate Data Import Sources

  • If the error originates from a bulk insert, SSIS package, or BULK INSERT/BCP operation, inspect the source file for hidden characters.
  • Open the source .csv or .txt file in a plain text editor and check for stray commas, currency symbols ($, €), or Unicode byte-order marks (BOM) in numeric fields.
  • Correct the source data or add a FORMATFILE to explicitly define column data types during import.

Step 3: Check Regional and Language Settings

  • Navigate to Windows Server 2025 Control Panel > Region > Administrative > Change system locale.
  • Ensure the SQL Server service account and the client application use matching locale settings (decimal symbol should be a period . for standard T-SQL parsing).
  • Restart the SQL Server service after any locale changes via services.msc or run:
  net stop MSSQLSERVER && net start MSSQLSERVER

Step 4: Rebuild or Repair the Corrupted Script/Procedure

  • If the error persists in a stored procedure or script file, drop and recreate the object using a known-good backup copy.
  • Use sp_helptext 'ProcedureName' to extract the current definition and manually inspect for corruption near numeric values.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or import job and confirm it completes without Error 2342 appearing in the SQL Server Error Log (SQL Server Logs folder, typically under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\).
  • As an alternative, wrap suspect numeric values in explicit CAST() or CONVERT() functions (e.g., CAST('123.45' AS DECIMAL(10,2))) to force proper type handling and bypass ambiguous parsing.

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

Why This Error Happens

Error 2343 (“%sUnterminated text section – missing `”) typically occurs when SQL Server 2025 encounters a malformed or corrupted script, batch file, or configuration string where a quoted text block was opened but never properly closed with a matching backtick or delimiter. This often happens due to truncated SQL scripts, encoding mismatches (such as UTF-8 vs ANSI) during file transfer, or corruption introduced by an interrupted write operation on Windows Server 2025. It can also surface when third-party tools or automation scripts generate dynamic T-SQL with improper string escaping.

Step-by-Step Resolution Guide

Step 1: Identify the Source Script or File

  • Open SQL Server Error Logs via SQL Server Management Studio (SSMS) or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Locate the exact query, job step, or import file referenced near the Error 2343 entry.
  • Note the file path if the error originates from an external .sql script or PowerShell-invoked batch.

Step 2: Inspect and Repair the Text Encoding

  • Open the offending file in a text editor like Notepad++ or VS Code.
  • Check for an unclosed backtick (`), single quote, or double-quote character near the end of the file or string literal.
  • Save the file explicitly as UTF-8 without BOM to avoid hidden encoding characters that corrupt delimiters.
  • Run sqlcmd -i yourscript.sql -f 65001 to force UTF-8 interpretation during execution.

Step 3: Validate SQL Agent Jobs and Linked Scripts

  • Navigate to SQL Server Agent > Jobs in SSMS and review any job steps that dynamically build T-SQL strings.
  • Check for missing closing characters in concatenated strings, especially in PowerShell or CMD steps calling SQL Server.
  • Update the job step command, ensuring every opened quote or backtick has a corresponding closing character.

Step 4: Rebuild or Restore the Corrupted Object

  • If the error persists on a stored procedure or view definition, script out the object via Generate Scripts in SSMS.
  • Drop and recreate the object using the corrected, properly terminated script.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear cached execution plans.

Alternative or Verification Steps

  • Re-run the original script or job step and confirm no Error 2343 appears in the ERRORLOG or Agent Job History.
  • If the issue persists, restore the affected script/object from a known-good backup and re-apply only the necessary changes incrementally to isolate the corrupted section.

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

Troubleshooting Guide: SQL Server Error 2339 – “Either a memberType attribute or a simpleType child must be present”

Why This Error Happens

This error occurs when SQL Server attempts to parse an XML Schema Collection (XSD) that contains a malformed simpleType definition, specifically where a union or list element is missing its required memberType attribute or an inline simpleType child node. This typically happens due to a corrupted or manually edited XSD file, an incomplete schema migration from an older SQL Server version, or third-party tooling that generates non-compliant XML schema collections during deployment. It can also surface when upgrading databases to SQL Server 2025 if legacy schema collections were created against relaxed validation rules in earlier engine versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate XML Schema Collections in the affected database:
  • SELECT name, schema_id, xml_schema_namespace FROM sys.xml_schema_collections;
  • Cross-reference the Location path returned in the Error 2339 message with the schema collection name to isolate the exact XSD causing the failure.
  • Export the schema definition using SELECT xml_schema_namespace(SCHEMA_NAME(schema_id), name) FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'; to inspect it externally.

Step 2: Validate and Repair the XSD Structure

  • Open the exported XSD in a validation tool such as Visual Studio 2025 XML Editor or an online XSD validator to confirm the exact line/node failing.
  • Locate any <xs:union> or <xs:list> elements and confirm they either include a memberType="..." attribute or a nested <xs:simpleType> child element — one of the two is mandatory per W3C XML Schema spec.
  • Manually correct the schema by adding the missing attribute, for example: <xs:union memberType="xs:string xs:int" />.
  • Save the corrected file as FixedSchema.xsd in a working directory such as C:\SQLFixes\Schemas\.

Step 3: Re-register the Corrected Schema Collection

  • Drop the broken schema collection (if it’s not actively referenced by typed XML columns): DROP XML SCHEMA COLLECTION YourSchemaName;
  • Re-create it using the corrected file: CREATE XML SCHEMA COLLECTION YourSchemaName AS 'C:\SQLFixes\Schemas\FixedSchema.xsd';
  • If the schema is in use by existing typed XML columns, use ALTER XML SCHEMA COLLECTION YourSchemaName ADD 'C:\SQLFixes\Schemas\FixedSchema.xsd'; instead to append the corrected definitions without breaking dependencies.

Step 4: Restart the SQL Server Service and Clear Plan Cache

  • On Windows Server 2025 / Windows 11, open Services.msc, locate SQL Server (MSSQLSERVER), and restart it to clear any cached invalid schema references.
  • Alternatively, run DBCC FREEPROCCACHE; from SQL Server Management Studio (SSMS) to flush cached execution plans tied to the old schema.

Alternative or Verification Steps

  • Verify the fix by re-running the original DDL/DML operation that triggered Error 2339, and confirm no errors appear in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • If re-creating the schema collection isn’t feasible due to dependencies, use sp_help 'YourSchemaName' to identify dependent objects first, then script out and migrate those objects to a new schema collection built from a validated XSD template.

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

Troubleshooting Guide: SQL Server Error 2340 — “%sComment started on line %u has no end”

Why This Error Happens

This error occurs when SQL Server’s parser encounters an unterminated block comment (/* ... */) within a T-SQL script, stored procedure, function, or trigger definition. The parser scans for a closing */ delimiter and, upon reaching the end of the batch or file without finding one, raises this error at the line number where the comment block began. This is commonly caused by manual editing mistakes, nested comments that aren’t properly closed, truncated script files, or corruption introduced during file transfer, encoding conversion, or version control merges.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line Referenced in the Error

  • Note the line number (%u) provided in the error message — this is where the unterminated comment begins, not necessarily where the problem is visually obvious.
  • Open the script in SQL Server Management Studio (SSMS) or Azure Data Studio and navigate directly to that line using Ctrl+G (Go To Line).
  • Use Ctrl+F with “Match Case” enabled to search for all instances of /* in the file and count them against */ occurrences — a mismatch confirms the unterminated block.

Step 2: Inspect for Nested or Malformed Comment Blocks

  • Check whether a comment block contains another /* inside it without SQL Server’s support for proper nesting closure (T-SQL does support nested comments, but every opening tag needs a matching closing tag).
  • Look for comments that were partially deleted during edits, e.g., a developer removed the */ while refactoring but left the /* intact.
  • Manually add the missing */ at the appropriate location, typically right before the next executable statement or at the logical end of the comment’s intended scope.

Step 3: Check for File Truncation or Encoding Corruption

  • If the script was copied from source control, email, or a legacy system, verify the file wasn’t truncated mid-transfer by checking the file size against the original source.
  • Open the file in a plain text editor (e.g., Notepad++ or VS Code) and inspect the encoding — ensure it’s saved as UTF-8 or UTF-16 without BOM corruption, as encoding mismatches can sometimes cause parsers to misread comment delimiters.
  • On Windows Server 2025 or Windows 11, use PowerShell to quickly scan the file for comment balance:
  (Get-Content "C:\Scripts\YourScript.sql" -Raw | Select-String -Pattern '/\*' -AllMatches).Matches.Count
  (Get-Content "C:\Scripts\YourScript.sql" -Raw | Select-String -Pattern '\*/' -AllMatches).Matches.Count
  • If the counts don’t match, locate and correct the unbalanced comment block manually.

Step 4: Re-Deploy or Re-Execute the Corrected Script

  • Save the corrected .sql file and re-run it through SSMS, sqlcmd, or your deployment pipeline (e.g., Azure DevOps, SSDT project build).
  • If the script is part of a stored procedure or function stored in source control, update the repository and redeploy to avoid reintroducing the same corrupted version.
  • Rebuild any SSDT (SQL Server Data Tools) database projects to confirm no other objects reference the broken script.

Alternative or Verification Steps

  • Re-execute the script in SSMS and confirm it compiles/runs without Error 2340 — check the Messages tab for a clean “Command(s) completed successfully” result.
  • If the issue persists, temporarily strip all comments using a regex-based find/replace (/\*[\s\S]*?\*/) in a text editor to isolate whether the error is comment-related or caused by a different parsing issue, then selectively reintroduce comments one block at a time.

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

Troubleshooting Guide: Error 2341 — “Expected hex character code following ‘\x'”

Why This Error Happens

This error occurs when SQL Server’s parser encounters an improperly escaped string literal, typically within a script, configuration file, or query that uses a backslash-x (\x) sequence intended for hexadecimal character encoding. The root cause is usually malformed input in a SQLCMD script, PowerShell string, or an ETL/import file (such as JSON or XML passed into SQL Server 2025) where the \x was not followed by valid hex digits (0-9, A-F). This can also stem from a corrupted or mis-encoded source file that was generated or edited with incompatible character encoding (e.g., UTF-16 vs. UTF-8) before being ingested by SQL Server.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Input Source

  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact line number and statement that triggered Error 2341.
  • If using SQLCMD, re-run the script with verbose output: sqlcmd -S localhost -i script.sql -o output.log
  • Look specifically for any string literal containing \x not followed by two valid hexadecimal characters (e.g., \xZZ or \x at the end of a string).

Step 2: Correct the Escape Sequence Syntax

  • Open the script or data file in a text editor (Notepad++ or VS Code recommended for encoding visibility).
  • Replace invalid sequences like \x or \xG1 with properly formatted hex codes, such as \x4E or \x00.
  • If the backslash is not meant to be an escape character, escape it literally using \\x depending on the parser (T-SQL, PowerShell, or JSON import function OPENJSON).

Step 3: Validate File Encoding and Re-Import

  • Re-save the source file using UTF-8 encoding without BOM (Byte Order Mark) to avoid hidden character corruption.
  • In Windows 11 or Windows Server 2025, use PowerShell to validate encoding: Get-Content -Path "C:\Scripts\import.sql" -Encoding UTF8 | Select-Object -First 10
  • Re-run the import or script execution in SQL Server Management Studio (SSMS) 21 to confirm the parser no longer throws Error 2341.

Step 4: Check for Corrupted Application Dependencies

  • If the error originates from a linked application (e.g., an ETL tool or custom .NET connector) rather than a raw script, verify that the SQL Native Client or ODBC Driver 18 is updated to the latest build compatible with SQL Server 2025.
  • Reinstall or repair the driver via Settings > Apps > Installed Apps on Windows 11, or Server Manager > Manage Roles and Features on Windows Server 2025.

Alternative or Verification Steps

  • Run a syntax-only dry pass of the corrected script using SET PARSEONLY ON; in SSMS before executing it fully to confirm no further hex-escape errors exist.
  • If the error persists in a third-party application despite valid script syntax, isolate the issue by testing the exact query directly in SSMS; if it succeeds there, the fault lies in the application’s string-handling layer rather than SQL Server itself.

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

Why This Error Happens

Error 2337 occurs when an XQuery replace value of expression within a .modify() method targets an XPath path that resolves to multiple nodes instead of a single, unique node. SQL Server’s XML data type methods require the target node to be unambiguous, so if your XPath expression (e.g., using wildcards or non-unique element names) matches more than one node in the XML instance, the engine throws this error instead of guessing which node to replace. This is commonly triggered by malformed XML schemas, duplicate sibling elements without differentiating attributes, or overly broad XPath predicates in stored procedures/triggers that manipulate XML columns.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Enable SQL Server Profiler or Extended Events to capture the exact T-SQL statement throwing Error 2337.
  • Look specifically for .modify('replace value of (XPath) with (value)') syntax in stored procedures, triggers, or ad-hoc scripts.
  • Note the XML column and the XPath expression being used.

Step 2: Refine the XPath to Target a Single Node

  • Review the XPath predicate inside the replace value of clause (e.g., (/Root/Item/text())[1]).
  • Add an explicit positional index such as [1] if multiple matching nodes are expected but only one should be modified.
  • Example fix:
  UPDATE dbo.YourTable
  SET XmlColumn.modify('replace value of (/Root/Item[@id="123"]/text())[1] with "NewValue"')
  WHERE PrimaryKeyColumn = @id;
  • Ensure attributes like @id or @name are used to uniquely filter the target node.

Step 3: Validate the XML Schema or Instance Data

  • Open SQL Server Management Studio (SSMS) and run a SELECT on the XML column to inspect the actual structure.
  • Check for duplicate or malformed elements that may have been inserted due to upstream application bugs.
  • If using an XML Schema Collection, validate it under Databases > [YourDB] > Programmability > Types > XML Schema Collections in SSMS to ensure it enforces uniqueness constraints where needed.

Step 4: Test in Isolation on a Non-Production Instance

  • Restore a copy of the affected database on a test instance running SQL Server 2025 on Windows Server 2025.
  • Re-run the corrected .modify() statement against sample data to confirm Error 2337 no longer appears.
  • Check SQL Server error logs (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for any residual XML parsing warnings.

Step 5: Deploy the Fix and Monitor

  • Apply the corrected stored procedure or script to production during a maintenance window.
  • Enable SQL Server Agent alerts for Error 2337 to catch any recurrence immediately.
  • Document the XPath change in your change-management system for future reference.

Alternative or Verification Steps

  • Run the corrected query manually against a known multi-node XML sample to confirm it now updates only the intended single node without throwing Error 2337.
  • If the error persists, as a workaround, convert the replace value of logic into a delete followed by an insert operation on the XML node, which bypasses the single-node restriction entirely.

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

Troubleshooting Guide: SQL Server Error 2338 — “The second ‘replace’ operand must contain only nodes”

Why This Error Happens

This error occurs when an XQuery replace value of expression targets an XML node using a path that resolves to a scalar value, attribute, or atomic type instead of a well-formed node set. SQL Server’s XML data type methods (.modify()) strictly enforce that the second operand in a replace operation must reference actual XML nodes, not text, numbers, or concatenated strings. This typically surfaces after a schema change, a malformed XQuery expression in stored procedures, or corrupted XML indexes that misrepresent the underlying node structure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XQuery Statement

  • Review the SQL Server error log or Extended Events session for the exact query triggering Error 2338.
  • Search recent stored procedures, triggers, or application code for .modify('replace value of ...') calls.
  • Use SELECT * FROM sys.dm_exec_query_stats cross-applied with sys.dm_exec_sql_text to locate the query handle if the error was logged asynchronously.

Step 2: Correct the XQuery Node Path Syntax

  • Ensure the path expression inside replace value of (...) resolves to a single node, not a concatenated or computed value.
  • Example of incorrect syntax: .modify('replace value of (/root/@attr)[1] with ("text" + "more")')
  • Correct it to target a proper singleton node: .modify('replace value of (/root/@attr)[1] with ("newvalue")')
  • Validate the XML column’s schema collection (if bound) using SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollection').

Step 3: Rebuild or Repair XML Indexes

  • Open SQL Server Management Studio (SSMS) on your Windows Server 2025 instance.
  • Run: ALTER INDEX ALL ON dbo.YourTable REBUILD; to rebuild any primary or secondary XML indexes.
  • If corruption is suspected, run DBCC CHECKTABLE('dbo.YourTable') WITH ALL_ERRORMSGS, DATA_PURITY;

Step 4: Validate the XML Schema Collection Binding

  • Confirm the column’s XML schema collection matches the document structure being modified.
  • Use sp_help 'dbo.YourTable' to inspect the current XML schema collection binding.
  • Drop and reapply the schema collection if it was altered after data was inserted:
  • ALTER TABLE dbo.YourTable ALTER COLUMN XmlCol XML (DOCUMENT dbo.YourSchemaCollection);

Step 5: Apply the Latest SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog and download the latest CU for SQL Server 2025.
  • Install via Setup.exe /ACTION=Upgrade or through Windows Server Update Services (WSUS).
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER.

Alternative or Verification Steps

  • Re-run the original .modify() statement in a test environment against a sample XML document to confirm Error 2338 no longer appears.
  • If the issue persists, extract the XML column data using SELECT CAST(XmlCol AS NVARCHAR(MAX)) and validate it against an XML validator tool to rule out upstream data corruption before re-importing.

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

Why This Error Happens

Error 2335 with the message “%sNewline in character/string constant” typically occurs when SQL Server’s parser encounters an unterminated string literal, often caused by a stray newline character or carriage return embedded within a quoted string in a T-SQL script. This commonly happens when scripts are copied from external sources (web pages, PDFs, or Unix-based editors) that introduce hidden line-break characters (CR/LF mismatches) inside string constants. Corrupted .sql files or improper encoding (such as UTF-8 without BOM being misread) can also trigger this parsing failure in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Open the .sql file in a plain-text editor like Notepad++ or VS Code rather than SSMS.
  • Enable “Show Line Endings” or “Render Whitespace” to visually inspect for stray \n or \r characters inside quotes.
  • Look specifically at lines surrounding the string literal referenced in the SSMS error output.

Step 2: Correct the String Literal Formatting

  • Ensure every string constant starts and ends on the same line, using a single pair of matching quotes ('...').
  • If a multi-line string is required, use the CHAR(13) + CHAR(10) concatenation method instead of a literal line break, for example:
    SET @msg = 'Line One' + CHAR(13) + CHAR(10) + 'Line Two';
  • Remove any invisible Unicode line separators (U+2028) that may have been pasted in from word processors.

Step 3: Normalize File Encoding and Line Endings

  • In VS Code or Notepad++, convert the file’s line-ending format to CRLF (Windows standard) via Edit > EOL Conversion > Windows (CR LF).
  • Re-save the file explicitly as UTF-8 with BOM to ensure SQL Server 2025’s parser reads it correctly.
  • If using sqlcmd on Windows Server 2025, re-run the script with the -f 65001 flag to force UTF-8 interpretation:
    sqlcmd -S servername -i script.sql -f 65001

Step 4: Re-run the Query in SQL Server Management Studio (SSMS)

  • Close and reopen the query window to clear any cached parse state.
  • Paste the corrected script into a fresh query tab rather than editing in place, as SSMS sometimes retains hidden formatting artifacts.
  • Execute the query again and confirm Error 2335 no longer appears in the Messages pane.

Alternative or Verification Steps

  • Run sp_helptext on the affected stored procedure (if applicable) to confirm the string constants render cleanly without embedded line breaks.
  • As an alternative, use PowerShell’s Get-Content script.sql -Raw combined with -replace "rn", " " to strip problematic line breaks before re-importing the script into SSMS.

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

Why This Error Happens

Error 2336 is thrown by the SQL Server parser (most commonly surfaced through sp_execute_external_script, PolyBase external table definitions, or dynamic T-SQL batches that embed Python/R snippets) when it encounters a numeric literal beginning with a leading zero — such as 0192 — and interprets it as an octal number. Since valid octal digits only range from 0–7, any 8 or 9 in that literal causes the parser to reject it outright. This typically stems from improperly sanitized input strings, copy-pasted configuration values, or auto-generated scripts that preserve zero-padded numbers (e.g., zip codes, IDs, or timestamps) without quoting them as strings.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Check the SQL Server Error Log (Management > SQL Server Logs) or Event Viewer under Applications and Services Logs > Microsoft > SQL Server for the exact batch or script triggering Error 2336.
  • If using sp_execute_external_script, isolate the Python/R block and look for zero-padded numeric values (e.g., area_code = 0752).

Step 2: Correct the Numeric Literal Formatting

  • Wrap the problematic value in quotes to treat it as a string instead of a number: area_code = '0752'.
  • If the value must remain numeric, strip the leading zero or explicitly cast it: CAST('0752' AS INT) in T-SQL, or int("0752") in Python (never leave it as a bare literal).

Step 3: Update External Script Language Extensions

  • Open SQL Server Configuration Manager and confirm the Machine Learning Services / Language Extensions (Python/R) components are updated to the build compatible with SQL Server 2025.
  • Run EXEC sp_configure 'external scripts enabled', 1; RECONFIGURE; to ensure the feature is properly reloaded after any patch.
  • Reinstall or repair the language extension via Add or Remove Programs > Microsoft SQL Server 2025 > Language Extensions if the parser behavior seems inconsistent after updates.

Step 4: Validate Dynamic SQL Generation Logic

  • If the query is dynamically built (e.g., via an ETL tool or ORM), inspect the generation logic in your application code (C#, PowerShell, or SSIS script tasks) to ensure numeric strings aren’t concatenated without proper escaping.
  • Add explicit string delimiters around any field that may contain leading zeros before it reaches the SQL Server parser.

Alternative or Verification Steps

  • Re-run the exact script or stored procedure in SQL Server Management Studio (SSMS) on Windows 11/Windows Server 2025 and confirm Error 2336 no longer appears in the Messages pane.
  • As a quick alternative, temporarily disable octal interpretation by converting all numeric literals to explicit VARCHAR or INT casts throughout the script, then re-enable external scripting (sp_configure 'external scripts enabled') to confirm stability.

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

Troubleshooting Guide: Error 2333 — “Invalid source character 0x%02x”

Why This Error Happens

Error 2333 occurs when SQL Server’s character conversion engine encounters a byte sequence in the source data that does not map to a valid character in the specified codepage or collation. This is typically caused by mismatched encoding between the source file (e.g., a flat file used in BCP, BULK INSERT, or SSIS) and the collation/codepage configured on the destination table or server. It can also result from file corruption, an incorrect -C codepage flag during bulk operations, or binary/non-text data accidentally being parsed as character data.

Step-by-Step Resolution Guide

Step 1: Identify the Actual Source Encoding

  • Open the offending source file in a hex editor (e.g., HxD) or VS Code with encoding detection enabled to confirm whether it is UTF-8, UTF-16LE, ANSI, or a legacy DOS codepage.
  • Check for a Byte Order Mark (BOM) at the start of the file — SQL Server’s bulk tools can misinterpret files with or without an expected BOM.
  • Run file.exe (via WSL or Git Bash) against the file for a quick encoding guess: file -i sourcefile.csv.

Step 2: Correct the Codepage/Collation Mismatch

  • If using BCP, explicitly specify the correct codepage flag, e.g., -C 65001 for UTF-8 or -C RAW to bypass conversion entirely.
  • If using BULK INSERT, set the CODEPAGE option explicitly in T-SQL:
  BULK INSERT dbo.TargetTable
  FROM 'C:\Data\sourcefile.csv'
  WITH (CODEPAGE = '65001', DATAFILETYPE = 'char');
  • Verify the destination column collation matches the expected character set using sp_help 'dbo.TargetTable' or SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('dbo.TargetTable');.

Step 3: Re-save or Convert the Source File

  • Use PowerShell to re-encode the file into a SQL Server–friendly format:
  Get-Content 'C:\Data\sourcefile.csv' -Raw -Encoding UTF8 | Set-Content 'C:\Data\sourcefile_fixed.csv' -Encoding Default
  • If the file originated from a non-Windows system (Linux/macOS export), strip any stray non-ASCII control characters using a text editor’s “Clean” or “Normalize Encoding” function.
  • Re-run the import job after saving the corrected file.

Step 4: Repair or Rebuild the Import Format File (If Applicable)

  • If using a .fmt format file for BCP, confirm the field terminators and row terminators match the actual file structure rather than assumed defaults.
  • Regenerate the format file using: bcp dbo.TargetTable format nul -c -x -f C:\Data\TargetTable.xml -S ServerName -T.
  • Confirm Windows Server 2025 regional settings under Control Panel > Region > Administrative > Change system locale align with the expected source codepage.

Alternative or Verification Steps

  • Re-run the bulk import or SSIS package and confirm Error 2333 no longer appears in the SQL Server Error Log (EXEC sp_readerrorlog 0, 1, '2333';).
  • As an alternative, load the file into a staging table with an NVARCHAR(MAX) catch-all column first, then use TRY_CONVERT in T-SQL to isolate and clean the specific invalid characters before moving data to the final target table.

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

Troubleshooting Guide: SQL Server Error 2334 – “Invalid Source Character”

Why This Error Happens

Error 2334 occurs when SQL Server’s parser encounters a character in a source file, script, or data stream that falls outside the expected character encoding range (typically during BCP operations, bulk inserts, or SSIS data flows). This is most commonly caused by a mismatch between the source file’s actual encoding (e.g., UTF-8 with BOM, UTF-16, or extended ASCII) and the encoding SQL Server expects for that operation. It can also result from corrupted source files, improper collation settings, or binary/null bytes accidentally embedded in a text file.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source File and Operation

  • Check the SQL Server error log or SSMS output pane to confirm which file, column, or import job triggered the error.
  • Note the exact character and hex value reported (e.g., 0x81, 0x8D are common invalid Windows-1252 bytes).
  • Open the source file in a hex editor (like HxD) to locate the offending byte offset.

Step 2: Correct the File Encoding

  • Re-save the source file using the correct encoding expected by your import method:
  • For BCP/BULK INSERT, use -c (char) or -w (wide/Unicode) flags explicitly rather than relying on defaults.
  • Example: bcp YourTable in "C:\Data\source.csv" -c -t, -S YourServer -T
  • If using UTF-8 source files, ensure SQL Server 2025 collation supports UTF-8 (e.g., Latin1_General_100_CI_AS_SC_UTF8).
  • Strip the Byte Order Mark (BOM) if present, as SQL Server’s BULK INSERT can misinterpret it depending on the DATAFILETYPE setting.

Step 3: Update the Format File or Import Definition

  • If using a .fmt format file for BCP, regenerate it against the current table schema:
  • bcp YourDatabase.dbo.YourTable format nul -c -f YourTable.fmt -S YourServer -T
  • In SSIS, set the Flat File Connection Manager’s CodePage property to match the source file (65001 for UTF-8, 1252 for Windows-1252).
  • Verify the DATAFILETYPE parameter in your BULK INSERT statement matches the file (char, native, widechar, or widenative).

Step 4: Sanitize or Filter Invalid Bytes (If Source Cannot Be Changed)

  • Use PowerShell to strip non-printable or out-of-range characters before import:
  • Get-Content "source.csv" -Encoding UTF8 | ForEach-Object { $_ -replace '[^\x09\x0A\x0D\x20-\x7E]', '' } | Set-Content "cleaned.csv"
  • Re-run the import against the cleaned file to confirm the invalid character was the root cause.

Alternative or Verification Steps

  • Run the import again with verbose logging (-e error.log flag in BCP) and confirm no further Error 2334 entries appear in the output log.
  • If the issue persists across multiple files, check the SQL Server instance’s default collation (SELECT SERVERPROPERTY('Collation')) and consider aligning it with your source data’s native encoding to prevent recurring mismatches.

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

Troubleshooting Guide: SQL Server Error 2331 – “Redefinition has to have itself as base type”

Why This Error Happens

This error occurs when SQL Server’s XML schema collection processing encounters a type redefinition that does not properly reference itself as the base type, violating XSD (XML Schema Definition) redefinition rules. It is typically triggered by corrupted or manually edited XML schema collections, incompatible schema imports from legacy applications, or inconsistencies introduced during an in-place upgrade to SQL Server 2025. In some cases, third-party ORM tools or CLR assemblies that generate dynamic XML schemas can also produce malformed <xs:redefine> blocks that fail validation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate schema collections that may be causing validation failures:
  SELECT name, schema_collection_id, xml_schema_namespace 
  FROM sys.xml_schema_collections;
  • Cross-reference the Location path reported in the error message (%ls) with the namespace returned above.
  • Check SQL Server Error Logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full stack trace and timestamp correlation.

Step 2: Validate and Correct the XML Schema Definition

  • Export the schema collection using SQL Server Management Studio (SSMS) 2025 by right-clicking the collection under Databases > Security > XML Schema Collections.
  • Open the exported .xsd file in a validator (such as Visual Studio 2025’s XML Schema Explorer) and manually inspect every <xs:redefine> element.
  • Ensure the redefined complex type explicitly extends or restricts itself, for example:
  <xs:redefine schemaLocation="original.xsd">
    <xs:complexType name="CustomerType">
      <xs:complexContent>
        <xs:extension base="CustomerType">
          <!-- new fields -->
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:redefine>
  • Remove or fix any redefinition where the base type does not match the type being redefined.

Step 3: Drop and Recreate the Schema Collection

  • Drop the corrupted schema collection:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Recreate it using the corrected .xsd file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS 
  'C:\SQLSchemas\corrected_schema.xsd';
  • If the schema is tied to a column or parameter definition, re-link it to the affected table or stored procedure after recreation.

Step 4: Clear Cached Compiled Schema Objects

  • Restart the SQL Server service to flush any cached, invalid schema compilation artifacts:
  Restart-Service -Name "MSSQLSERVER" -Force
  • On Windows Server 2025/Windows 11, confirm the service restarted cleanly via Services.msc or Event Viewer under Applications and Services Logs > MSSQLSERVER.

Alternative or Verification Steps

  • Re-run the original DDL statement or application query that triggered Error 2331 and confirm it completes without exception.
  • If the issue persists, use DBCC CHECKDB on the affected database to rule out underlying page-level corruption that may be affecting system metadata tables storing the schema collections.

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

Troubleshooting Guide: SQL Server Error 2332 – “%s’%ls’ may not be used with an ’empty’ operand”

Why This Error Happens

This error typically occurs during DBCC consistency checks (such as DBCC CHECKDB or DBCC CHECKTABLE) when SQL Server’s internal storage engine encounters a corrupted index or table structure where a page pointer references an “empty” operand that cannot be logically processed. This is often triggered by physical disk corruption, improper shutdowns, or storage subsystem failures that leave allocation structures (IAM pages, index B-trees) in an inconsistent state. In some cases, this also surfaces after a failed or interrupted index rebuild operation on SQL Server 2025 running on Windows Server 2025/Windows 11 environments.

Step-by-Step Resolution Guide

Step 1: Run a Full Consistency Check

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to identify the full scope of corruption.
  • Note the specific object ID and index ID reported alongside Error 2332 in the output.

Step 2: Isolate the Corrupted Object

  • Run DBCC CHECKTABLE ('YourTableName') WITH ALL_ERRORMSGS; against the specific table flagged in Step 1.
  • Cross-reference the object ID using SELECT OBJECT_NAME(object_id) FROM sys.indexes WHERE index_id = <ID>; to confirm the exact index causing the operand conflict.

Step 3: Rebuild or Drop the Affected Index

  • If a non-clustered index is the source, run ALTER INDEX [IndexName] ON [TableName] REBUILD; to force a rebuild and clear the empty operand reference.
  • If the rebuild fails, drop and recreate the index manually using DROP INDEX followed by CREATE INDEX with the original schema definition.

Step 4: Restore from a Verified Backup (If Corruption Persists)

  • Navigate to your backup directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\) and locate the last known good .bak file.
  • Perform a restore using RESTORE DATABASE [YourDatabaseName] FROM DISK = 'C:\Path\To\Backup.bak' WITH REPLACE; to bypass the corrupted data structure entirely.

Step 5: Validate Underlying Storage Health

  • Check the Windows Event Viewer (Application and System logs) for underlying disk I/O errors (Event ID 51 or 153) that may be causing the SQL Server corruption.
  • Run chkdsk C: /f /r via an elevated Command Prompt on Windows Server 2025 to repair the underlying file system if hardware issues are suspected.

Alternative or Verification Steps

  • After applying fixes, re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS; to confirm Error 2332 no longer appears in the results.
  • If the error recurs immediately after an index rebuild, consider running DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS option as a last resort, but only after taking a full backup of the current (corrupted) state first.

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

Troubleshooting Guide: SQL Server Error 2327 – “The content or definition of <%ls> is missing”

Why This Error Happens

Error 2327 typically occurs when SQL Server Setup or a maintenance operation references a configuration file, resource string, or component definition that cannot be located in the expected installation path. This is often caused by a corrupted or incomplete installation media, a missing Setup Resource (.xml or .rll) file, or interference from antivirus/Windows Defender quarantining core SQL Server setup files during installation on Windows Server 2025 or Windows 11. In some cases, this also surfaces when SSIS or SSAS package definitions point to a component that was never properly registered in the local SQL Server instance.

Step-by-Step Resolution Guide

Step 1: Verify Installation Media Integrity

  • Re-download the SQL Server 2025 ISO from the official Microsoft Volume Licensing Center or Evaluation Center to rule out a corrupted download.
  • Mount the ISO and compare the file checksum (SHA256) against the published hash on Microsoft’s documentation page.
  • Avoid extracting the ISO with third-party tools; use native Windows “Mount” functionality instead.

Step 2: Check for Missing Setup Resource Files

  • Navigate to C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\SQL2025\ and confirm the presence of .rll resource files matching your system locale (e.g., 1033 for English).
  • If the folder is empty or files are missing, this confirms antivirus interception — temporarily disable Windows Defender real-time protection via Windows Security > Virus & threat protection > Manage settings.
  • Re-run Setup from an elevated Command Prompt: Setup.exe /ACTION=Install /QS /INDICATEPROGRESS.

Step 3: Repair the SQL Server Instance

  • Open “Programs and Features” in Control Panel, locate “Microsoft SQL Server 2025”, and select Change.
  • Choose Repair from the SQL Server Installation Center wizard rather than a fresh install, as this rebuilds missing component definitions without wiping databases.
  • Monitor the detailed log at C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log\Summary.txt for any secondary errors during the repair.

Step 4: Validate SSIS/SSAS Package References (If Applicable)

  • If the error triggers during package deployment, open the .dtsx or .xmla file in a text editor and confirm all <DTS:Executable> or <Dimension> tags have corresponding definitions.
  • Redeploy the package using SQL Server Data Tools (SSDT) after validating XML schema integrity with dtutil /FILE "package.dtsx" /Y.

Alternative or Verification Steps

  • To verify the fix, restart the SQL Server (MSSQLSERVER) service via services.msc and check the SQL Server Error Log (ERRORLOG file in the Log directory) for a clean startup with no Error 2327 recurrence.
  • If the issue persists after a repair, consider a full uninstall using the SQL Server Uninstall Tool followed by a clean install, ensuring the installation path (C:\Program Files\Microsoft SQL Server\) is manually deleted beforehand to remove orphaned resource references.

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

Troubleshooting Guide: SQL Server Error 2328 — Schema Namespace Mismatch

Why This Error Happens

Error 2328 occurs when SQL Server parses an XML document or schema collection and finds that the namespace declared in the document (or referenced via xmlns) does not match the target namespace defined in the associated XML Schema Collection (XSD). This typically results from a corrupted or outdated XML Schema Collection stored in the database, a mismatched namespace string due to manual editing, or an application sending XML data that references an incorrect or versioned schema URI. It can also surface after a schema collection migration or restore where the namespace binding became stale relative to the application’s directive.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Schema Collection

  • Run the following query to locate the XML Schema Collection tied to the error:
  SELECT name, xml_schema_namespace, create_date, modify_date
  FROM sys.xml_schema_collections
  WHERE schema_id = SCHEMA_ID('dbo');
  • Cross-reference the xml_schema_namespace value with the namespace declared in the incoming XML document (check the xmlns attribute at the root element).
  • Review application logs or the SQL Server ERRORLOG at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full error context, including the two namespace strings reported.

Step 2: Correct the Namespace Mismatch

  • If the application-side XML namespace changed (e.g., versioned schema like http://schemas.company.com/orders/v2), update the XML payload to reference the namespace currently registered in SQL Server, or:
  • Drop and recreate the XML Schema Collection with the updated namespace:
  DROP XML SCHEMA COLLECTION dbo.OrderSchemaCollection;
  GO
  CREATE XML SCHEMA COLLECTION dbo.OrderSchemaCollection
  AS N'<xsd:schema targetNamespace="http://schemas.company.com/orders/v2" ...></xsd:schema>';
  GO
  • Ensure the targetNamespace attribute in the .xsd file matches exactly (case-sensitive) with what the application sends.

Step 3: Rebind Columns and Validate Dependent Objects

  • If any xml typed columns reference the schema collection, verify they aren’t locked to a stale version:
  SELECT c.name, t.name AS schema_collection
  FROM sys.columns c
  JOIN sys.xml_schema_collections t
  ON c.xml_collection_id = t.xml_collection_id;
  • Recompile stored procedures or functions that validate XML against this schema using sp_recompile.
  • Restart the SQL Server service via services.msc or:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Re-test the XML Insert/Validation Operation

  • Re-run the original INSERT/UPDATE statement or application transaction that triggered Error 2328.
  • Confirm no namespace-related errors appear in SSMS or the application’s exception log.

Alternative or Verification Steps

  • Verify the fix by executing a test query that casts a sample XML document against the schema collection: SELECT CAST('<root xmlns="http://schemas.company.com/orders/v2">...</root>' AS XML) and confirm no errors are thrown.
  • If the mismatch persists, consider exporting the schema via sp_help_jobschedule-style scripting tools or SSMS “Generate Scripts” wizard to recreate the XML Schema Collection from a known-good source, ensuring namespace consistency across all environments (Dev/QA/Prod).

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

Why This Error Happens

Error 2329 is thrown by the SQL Server parser when a duration-based configuration value—most commonly the RETENTION_PERIOD clause used in Temporal Table DATA_RETENTION policies, or a duration parameter passed to Resource Governor, Query Store, or Extended Events—does not match the expected <integer> <unit> syntax (e.g., 6 MONTHS, 30 DAYS). This typically occurs because of a typo in the unit keyword, a missing space between the number and unit, localized/regional string formatting (commas vs. periods), or because the string was generated dynamically by an application/ORM that didn’t sanitize the output correctly. It can also occur after a migration from an older SQL Server version where duration syntax rules were less strict or different.

Step-by-Step Resolution Guide

Step 1: Identify the Exact T-SQL Statement Causing the Error

  • Capture the failing statement from SQL Server Management Studio (SSMS), the Agent Job history, or the application log — the error message includes the offending string in %ls.
  • Run the statement manually in a new SSMS query window against a test database to reproduce it safely.
  • Check if the statement involves DATA_RETENTION, ALTER TABLE ... SET, Resource Governor ALTER WORKLOAD GROUP, or an Extended Events session definition.

Step 2: Correct the Duration String Syntax

  • Ensure the value follows the pattern <positive integer><space><unit>, where unit is one of: DAYS, WEEKS, MONTHS, YEARS (for temporal retention) — e.g., use RETENTION_PERIOD = 12 MONTHS instead of RETENTION_PERIOD = "12mo" or RETENTION_PERIOD = 12months.
  • For Resource Governor or Query Store duration settings, confirm the value is expressed in the documented unit (seconds/minutes) without extra symbols, currency formatting, or locale-based decimal separators.
  • If the value is being built dynamically (e.g., via PowerShell, C#, or an ORM), log the raw string right before execution to confirm no hidden characters (tabs, non-breaking spaces) were injected.

Step 3: Validate Server Collation and Regional Settings

  • Run SELECT SERVERPROPERTY('Collation'); to confirm the server collation isn’t causing unexpected string formatting during concatenation.
  • On Windows Server 2025 / Windows 11, open Control Panel > Region > Administrative > Change system locale and verify the OS locale matches the SQL Server instance’s expected locale, especially if the duration string is built using culture-specific number formatting (e.g., 12,0 MONTHS in some European locales).
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after any locale changes to ensure settings are reloaded.

Step 4: Re-run the Corrected Statement

  • Execute the fixed T-SQL statement again in SSMS.
  • If it’s part of an automated script or SQL Agent Job, update the stored procedure/script source and redeploy before re-triggering the job manually.

Alternative or Verification Steps

  • Verify the fix by querying sys.tables or sys.periods (for temporal retention) to confirm the new retention/duration value was applied correctly, e.g.: SELECT name, temporal_type_desc FROM sys.tables WHERE name = 'YourTableName';
  • If the error persists despite correct syntax, check for a corrupted or outdated SQL Server Native Client / OLE DB driver on the client machine, and update to the latest Microsoft ODBC Driver for SQL Server 2025 compatible with Windows Server 2025 / Windows 11.

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

Why This Error Happens

Error 2325 occurs when SQL Server’s XML parser encounters a malformed XML document, typically during operations involving FOR XML, OPENXML, XML schema collections, or when importing/reading XML configuration files (such as SSIS package XML or Policy-Based Management policies). This usually results from manual edits to XML files that introduce mismatched or improperly nested tags, truncated file transfers, or encoding corruption (e.g., a file saved with the wrong UTF-8/UTF-16 encoding). It can also surface when a third-party tool or custom script generates XML output that violates well-formedness rules expected by the SQL Server XML parser (MSXML/System.Xml).

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source

  • Note the exact line number (%u) and tag names (%ls) reported in the error message.
  • Locate the source XML file, stored procedure parameter, or column value being parsed (check SSIS .dtsx files, XML schema collections via sys.xml_schema_collections, or application-submitted XML payloads).
  • Open the file in a text editor that shows line numbers, such as VS Code or Notepad++, on Windows Server 2025 / Windows 11.

Step 2: Validate and Repair the XML Structure

  • Run the XML through a validator (VS Code’s built-in XML extension, xmllint --noout file.xml, or an online XML validator) to pinpoint unclosed or mismatched tags.
  • Check for common issues: self-closing tags written incorrectly (e.g., <Tag> without </Tag> or <Tag/>), case-sensitivity mismatches (<Item> vs </item>), or namespace prefix mismatches (<ns:Tag> closed as </Tag> instead of </ns:Tag>).
  • Manually correct the mismatched tag at the reported line number, ensuring proper nesting order (XML tags must close in reverse order of opening).

Step 3: Check File Encoding and Truncation

  • Confirm the file was saved in a consistent encoding (UTF-8 without BOM issues, or UTF-16 if required by the consuming application).
  • Re-export or re-transfer the file if it was moved via FTP/SFTP in ASCII mode, which can corrupt XML structure mid-document.
  • In PowerShell, verify file integrity with: Get-Content -Path "C:\path\to\file.xml" -Raw | Measure-Object -Line.

Step 4: Re-run the SQL Server Operation

  • If using OPENXML, re-run sp_xml_preparedocument after confirming the corrected XML string.
  • If using an XML Schema Collection, drop and recreate it with DROP XML SCHEMA COLLECTION followed by CREATE XML SCHEMA COLLECTION using the repaired XML.
  • For SSIS packages, reopen the .dtsx file in SQL Server Data Tools (SSDT) to let it auto-validate and resave the XML structure cleanly.

Alternative or Verification Steps

  • Verify the fix by re-running the exact query or import operation that triggered Error 2325; it should complete without the XML parser exception.
  • If the error persists, use SELECT CAST(@xmlVariable AS XML) in a test query to isolate whether the issue lies in the source file or in how the application is submitting the XML to SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 2326 (XML Tag Mismatch)

Why This Error Happens

Error 2326 occurs when SQL Server’s XML parser encounters a malformed XML document where closing tags do not correctly correspond to their matching opening tags, often due to manual edits, truncated files, or encoding corruption. This typically happens during operations involving XML data types, SSIS package imports, policy-based management XML configurations, or when loading XML-formatted configuration files (such as Reporting Services RSReportServer.config or Availability Group XML metadata). The root cause is almost always a structurally invalid XML source file rather than a SQL Server engine defect itself.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Source of the Malformed XML

  • Check the full error message for the line number referenced (e.g., “from line %u”) to pinpoint the exact location in the XML document.
  • If the error originates from a specific query, run SELECT * FROM sys.dm_exec_requests to identify the session and query generating the XML parse call.
  • If it’s a config file issue, locate relevant files such as C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ for SQL error logs or C:\Program Files\Microsoft SQL Server\160\Shared\ for shared XML schemas.

Step 2: Validate and Repair the XML Document

  • Open the XML file in a dedicated XML validator (Visual Studio Code with XML extension, or Notepad++ with the XML Tools plugin) rather than a plain text editor.
  • Search specifically for mismatched tags, especially nested namespaces like <ns:element> that may have been incorrectly closed as </element> instead of </ns:element>.
  • Check for truncation at the end of the file — a common cause is an incomplete file transfer or a process that was killed mid-write, leaving the closing root tag missing entirely.
  • Re-save the file using UTF-8 encoding without BOM to avoid introducing hidden invalid characters that confuse the parser.

Step 3: Restore from a Known-Good Backup or Template

  • If the corrupted XML is a system configuration file (e.g., ReportServer.config or an SSIS .dtsx package), restore a previous version from backup rather than attempting manual repair.
  • For SSIS packages, open the .dtsx file in SQL Server Data Tools (SSDT) and use the designer view to re-save it, which forces SQL Server to regenerate valid XML structure automatically.
  • Replace the corrupted file in its original directory path and restart the associated service (e.g., SQL Server Reporting Services via services.msc).

Step 4: Re-run the Operation and Monitor the Log

  • Re-execute the query, import, or service startup that originally triggered Error 2326.
  • Monitor the SQL Server Error Log in real time using EXEC sp_readerrorlog 0, 1, N'2326'; to confirm the error does not recur.

Alternative or Verification Steps

  • Verify the fix by running the XML through an independent validator (such as xmllint --noout yourfile.xml in a WSL/Linux shell on Windows 11) to confirm zero schema errors before reloading it into SQL Server.
  • If the error persists after XML repair, use SELECT CAST(your_column AS XML) in a test query against the specific data to isolate whether the corruption exists at the database row level rather than in an external file, and restore that specific table from a recent backup if confirmed.

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

Why This Error Happens

Error 2323 occurs when SQL Server’s XML parser encounters a malformed or truncated XML document, typically because the closing tag does not correspond to the most recently opened tag. This is commonly caused by corrupted XML data being passed into functions like OPENXML, sp_xml_preparedocument, or XML-typed columns, often resulting from incomplete file transfers, manual editing errors, or encoding mismatches (such as UTF-8 vs UTF-16 BOM issues). In some cases, this also surfaces when SQL Server Configuration Manager or Policy-Based Management reads a corrupted .xml configuration file on Windows Server 2025 / Windows 11.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Check the application or T-SQL script that generated the XML payload (e.g., FOR XML, OPENXML, or an imported .xml config file).
  • Use SELECT CAST(YourXmlColumn AS XML) in SSMS to isolate the exact row or document causing the parse failure.
  • Note the line number referenced in the error message (from line %u) to pinpoint the exact location in the file.

Step 2: Validate and Repair the XML Structure

  • Open the offending XML file in a validating editor (Visual Studio Code with XML extension, or Notepad++ with XML Tools plugin).
  • Look for unclosed tags, mismatched case sensitivity (XML is case-sensitive, e.g., <Data> vs </data>), or special characters that weren’t properly escaped (&, <, > must use &amp;, &lt;, &gt;).
  • Confirm the file encoding matches what SQL Server expects — re-save as UTF-8 without BOM using:
  notepad.exe file.xml
  File > Save As > Encoding: UTF-8

Step 3: Clear Orphaned XML Document Handles (If Using OPENXML)

  • If the error stems from sp_xml_preparedocument, ensure every call has a matching sp_xml_removedocument to prevent memory corruption that can produce false parsing errors.
  • Example cleanup script:
  EXEC sp_xml_removedocument @hDoc;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator) to clear any cached document handles.

Step 4: Re-import or Re-run the Corrected XML

  • Once the XML passes external validation, re-run the original INSERT, UPDATE, or import job (SSIS package, bulk insert, or application call).
  • If using SQL Server Configuration Manager and the error points to a config file (e.g., SQLServerManager17.msc reading XML), replace the corrupted file with a known-good backup copy from C:\Program Files\Microsoft SQL Server\160\Shared\.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(@xmlVariable AS XML) or re-executing the import — if no error is thrown and the result set displays correctly, the XML is now well-formed.
  • As an alternative, use PowerShell’s built-in validator to pre-check files before passing them to SQL Server:
  [xml](Get-Content "C:\path\to\file.xml")

If this command fails, PowerShell will report the exact line and character causing the mismatch, confirming the fix is needed before SQL Server is engaged again.

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

Why This Error Happens

Error 2324 occurs when SQL Server’s XML parser encounters a malformed XML document, typically during the parsing of XML configuration files, SSIS package definitions, or XML data being inserted into an xml-typed column. The mismatched tag indicates the XML source has been truncated, manually edited incorrectly, or corrupted during transfer (e.g., FTP in ASCII mode instead of binary). This can also surface in SQL Server 2025 when Policy-Based Management or Extended Events XML configuration files are damaged due to a failed disk write or abrupt service termination.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full stack trace accompanying Error 2324.
  • Note the line number (%u) referenced in the error — this points to the exact location of the broken tag in the XML source.
  • Determine whether the source is an SSIS package (.dtsx), an XML column insert statement, or a configuration file like sqlservr.xml or Extended Events .xel/.xml target definitions.

Step 2: Validate and Repair the XML File

  • Open the offending XML file in Visual Studio Code or Notepad++ with “Validate XML” or an XML-aware linter extension enabled.
  • Run the following PowerShell command to quickly test well-formedness:
[xml](Get-Content "C:\Path\To\File.xml")
  • If PowerShell throws a parsing error, it will confirm the exact line/column of the mismatched tag — manually correct the unclosed or mismatched element (common culprits: <Property> without </Property>, or self-closing tags written incorrectly).

Step 3: Re-Deploy or Re-Import the Corrected XML

  • If the issue is with an SSIS package, redeploy the corrected .dtsx file via SQL Server Management Studio (SSMS) using Integration Services Catalogs > SSISDB > Deploy.
  • If the issue is with a configuration file (e.g., Extended Events session definitions), restart the SQL Server service after replacing the file:
Restart-Service -Name "MSSQLSERVER" -Force
  • For XML data columns, re-run the INSERT/UPDATE statement using the corrected, well-formed XML string and confirm no truncation occurred during data transfer (check varchar(max) casting if converting string to XML).

Step 4: Check for File Encoding or Transfer Corruption

  • Confirm the XML file was saved/transferred in UTF-8 or UTF-16 without BOM corruption; re-save using Save with Encoding in your text editor if needed.
  • If the file came from an external system (FTP/SFTP/API), re-transfer it in binary mode rather than ASCII mode to avoid line-ending or encoding truncation.

Alternative or Verification Steps

  • Verify the fix by re-running the operation that originally triggered Error 2324 (SSIS execution, XML insert, or service restart) and confirm no errors appear in the SQL Server Error Log or Windows Event Viewer (Applications and Services Logs > MSSQLSERVER).
  • If the error persists despite a well-formed XML file, use sqlcmd to isolate whether the issue is client-side (application generating bad XML) versus server-side by manually submitting a minimal, known-valid XML payload against the same target.

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

Why This Error Happens

Error 2321 occurs when SQL Server’s XML parser processes an XSD schema (typically during a CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement) that violates W3C XML Schema ordering rules. Specifically, the schema definition contains facet elements (such as <xs:minLength>, <xs:pattern>, or <xs:enumeration>) placed after an <xs:attribute> declaration inside a <xs:restriction> block, when the correct order requires all facets to precede any attribute declarations. This is almost always caused by a manually edited or auto-generated XSD file that wasn’t validated against the schema’s content model before being imported into SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending XSD File

  • Locate the exact .xsd file referenced in the CREATE XML SCHEMA COLLECTION statement that triggered the error.
  • Open the file in a structured XML editor (Visual Studio 2022/2025 or VS Code with the XML extension) rather than a plain text editor to get schema-aware validation.
  • Note the location path reported in the error message (e.g., #/complexType[2]/restriction/attribute[1]) — this tells you exactly which node is malformed.

Step 2: Correct the Facet/Attribute Ordering

  • Within the <xs:complexType> or <xs:simpleType> block identified, move all facet elements (<xs:minLength>, <xs:maxLength>, <xs:pattern>, <xs:enumeration>, <xs:totalDigits>, etc.) so they appear immediately after the <xs:restriction base="..."> opening tag.
  • Ensure <xs:attribute> declarations appear strictly after all facet elements, per the XSD content model: restriction -> (facets)* -> (attribute | attributeGroup)*.
  • Save the corrected file as UTF-8 without BOM to avoid encoding issues on import.

Step 3: Re-import the Schema Collection in SQL Server

  • Drop the broken schema collection if a partial version exists:
DROP XML SCHEMA COLLECTION dbo.MySchemaCollection;
  • Re-run the creation statement pointing to the corrected file:
CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
   -- corrected schema content here
</xs:schema>';
  • Check sys.xml_schema_collections to confirm the object registered successfully.

Step 4: Validate with an External XSD Validator

  • Before re-importing, run the file through xmllint --schema (available via Windows Subsystem for Linux on Windows 11/Server 2025) or the .NET XmlSchemaSet class to catch ordering errors pre-emptively.
  • Example command: xmllint --noout --schema myschema.xsd sample.xml

Alternative or Verification Steps

  • Verify the fix by querying sys.xml_schema_collections and sys.xml_schema_components to confirm the schema loaded without error and that attribute/facet nodes appear in the expected sequence.
  • If the schema is auto-generated (e.g., exported from an ORM or third-party tool), regenerate it using an updated version of that tool, as older generators are known to emit non-compliant facet/attribute ordering that newer XSD 1.1-aware tools correct automatically.

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

Troubleshooting Guide: SQL Server Error 2322 — “The Element Type Is Not a Subclass of the Substitution Group’s Head”

Why This Error Happens

This error occurs when SQL Server’s XML parser validates an XML document or schema collection (XSD) against a substitution group, and encounters an element that is declared as a member of that group but does not actually derive from the designated head element’s type. This typically stems from a corrupted or mismatched XML Schema Collection stored in the database, an outdated schema definition that conflicts with incoming XML data, or manual edits to XML configuration files (such as Policy-Based Management policies or SSIS package XML) that broke the type hierarchy. It can also surface after an in-place upgrade to SQL Server 2025 if legacy schema collections were never revalidated against the newer XML engine.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the XML Validation

  • Check the SQL Server Error Log and Windows Event Viewer (Event ID 2322) to pinpoint which database, schema collection, or service component triggered the error.
  • Run the following query to list affected XML Schema Collections:
SELECT name, xml_collection_id, schema_namespace 
FROM sys.xml_schema_collections;
  • Cross-reference the namespace with any recent application deployments or SSIS/Policy-Based Management changes.

Step 2: Validate and Repair the XML Schema Collection

  • Export the current schema collection to inspect its structure:
SELECT xml_schema_namespace('dbo','YourSchemaCollectionName');
  • Compare the substitution group definitions against the head element’s type using an external XML validator (e.g., Visual Studio XML Schema Explorer or xmllint --schema).
  • Drop and recreate the schema collection with corrected substitution group hierarchy:
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
GO
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS N'<corrected XSD here>';

Step 3: Clear Corrupted Policy or Configuration Files

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ and back up any .xml policy files tied to Policy-Based Management.
  • If the error originates from SSIS packages, open the .dtsx file in a text editor and confirm all <DTS:Executable> elements correctly inherit from their declared base types.
  • Restart the SQL Server service via services.msc or PowerShell:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Reapply Service Packs or Cumulative Updates

  • Confirm you are running the latest Cumulative Update for SQL Server 2025, as early builds had known XML parser inconsistencies.
  • Download and install via Microsoft Update Catalog, then verify the build number:
SELECT @@VERSION;

Alternative or Verification Steps

  • After applying fixes, re-run the original query, SSIS package, or policy evaluation that triggered Error 2322 and confirm no exceptions appear in SQL Server Management Studio’s Messages tab.
  • If the issue persists, use sqlcmd with the -y 0 flag to capture full-length error output, or restore the affected schema collection from a pre-upgrade backup as a fallback.

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

Troubleshooting Guide: SQL Server Error 2319 – “This type may not have a ‘%ls’ facet”

Why This Error Happens

Error 2319 occurs when SQL Server’s XML Schema Collection validation engine encounters a facet (such as maxLength, pattern, or totalDigits) applied to a base type that does not support it according to the W3C XML Schema specification. This typically happens when a custom or imported XSD schema is malformed, was hand-edited incorrectly, or was generated by a third-party tool that does not strictly enforce W3C type-facet compatibility rules. It can also surface after an in-place upgrade to SQL Server 2025, where stricter XML schema validation parsing exposes previously tolerated inconsistencies in existing XML Schema Collections.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate collections and inspect their definitions:
  • SELECT name, xml_schema_namespace, XML_SCHEMA_NAMESPACE('schema_name','collection_name') FROM sys.xml_schema_collections;
  • Note the exact Location path and facet name (%ls) reported in the error message — this points to the specific <xs:restriction> block causing the conflict.

Step 2: Validate the Schema Against W3C XSD Rules

  • Export the schema collection definition to a .xsd file using SSMS (Script Table As > XML Schema Collection).
  • Open the file in Visual Studio 2022+ or an XML validator (e.g., xmllint --noout --schema base.xsd target.xsd) to confirm facet/type compatibility.
  • Common invalid combinations include applying maxLength to xs:decimal or pattern to xs:boolean — remove or correct these facets.

Step 3: Drop and Recreate the Corrected Schema Collection

  • Back up the current collection definition before making changes:
  • SELECT CAST(XML_SCHEMA_NAMESPACE('schema_name','collection_name') AS NVARCHAR(MAX));
  • Drop the invalid collection: DROP XML SCHEMA COLLECTION schema_name.collection_name;
  • Recreate it with the corrected XSD: CREATE XML SCHEMA COLLECTION schema_name.collection_name AS '<corrected XSD content>';

Step 4: Apply Latest Cumulative Update

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as early XML parser builds may misreport facet validation on otherwise valid schemas.
  • Check current build: SELECT @@VERSION;
  • Download and apply the latest CU from the Microsoft Update Catalog if your build is outdated.

Alternative or Verification Steps

  • After recreating the schema collection, re-run any stored procedures or XML column constraints that referenced it to confirm Error 2319 no longer appears.
  • If the error persists, temporarily isolate the schema by testing it in a clean tempdb database using CREATE XML SCHEMA COLLECTION — this confirms whether the issue is schema-specific or related to database-level corruption requiring a DBCC CHECKDB run.

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

Troubleshooting Guide: SQL Server Error 2320 — Duplicate Facet Found

Why This Error Happens

Error 2320 occurs when the Policy-Based Management (PBM) engine encounters two or more facet definitions sharing the same name at the same XML location within the msdb system database’s facet metadata tables. This typically results from a corrupted or incompletely applied Cumulative Update/Service Pack that re-registers facets without first clearing stale entries, or from a botched manual import of policy management XML definitions. It can also surface after an in-place upgrade to SQL Server 2025 where legacy facet metadata from a previous version was not properly migrated or deduplicated.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Facet Entries

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query against msdb to locate duplicates:
SELECT facet_name, COUNT(*) AS occurrences
FROM msdb.dbo.syspolicy_management_facets
GROUP BY facet_name
HAVING COUNT(*) > 1;
  • Note the exact facet_name and location values returned, as these pinpoint the conflict described in the error message.

Step 2: Rebuild the Policy-Based Management Metadata

  • Stop the SQL Server Agent service temporarily via services.msc or net stop SQLSERVERAGENT to prevent policy evaluation jobs from running during cleanup.
  • Back up msdb first:
BACKUP DATABASE msdb TO DISK = 'C:\Backup\msdb_pre2320.bak';
  • Remove the duplicate facet row(s) identified in Step 1 using the sp_syspolicy_delete_policy_management_facet stored procedure (or direct DELETE only if Microsoft Support has confirmed it’s safe for your build).
  • Restart SQL Server and SQL Server Agent services.

Step 3: Reapply the Latest Cumulative Update

  • Download the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Run the installer with repair logging enabled:
Setup.exe /ACTION=Install /QUIET /INSTANCENAME=MSSQLSERVER /IACCEPTSQLSERVERLICENSETERMS /UpdateSource=C:\SQLCU\
  • Verify the installation path C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log\ for any setup errors related to syspolicy objects.

Step 4: Validate Windows Server Environment Integrity

  • Ensure Windows Server 2025 / Windows 11 has no pending reboots from Windows Update, as this can leave SQL Server service files in a partially updated state (Get-WURebootStatus via PowerShell module PSWindowsUpdate).
  • Confirm the SQL Server service account has full read/write permissions on C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Binn\ to rule out metadata file corruption from permission failures.

Alternative or Verification Steps

  • Re-run the duplicate-check query from Step 1 — a clean result set (no rows returned) confirms the fix.
  • Open SSMS → Management → Policy Management → Facets and manually scroll through the list to confirm no duplicate facet names appear; if the error persists, restore the msdb backup taken in Step 2 and engage Microsoft Support with the CU installation logs attached.

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

Troubleshooting Guide: SQL Server Error 2316 – Missing ‘base’ Attribute

Why This Error Happens

Error 2316 occurs when SQL Server 2025 attempts to parse an XML-based configuration file (such as a Policy-Based Management policy, an XML Schema Collection, or an SSIS package XML) and encounters a node that references inheritance or extension without defining the mandatory base attribute. This typically results from a corrupted or manually edited XML file where the schema structure was altered incorrectly, often after an in-place upgrade or a failed deployment. In Windows Server 2025 environments, this can also surface when Group Policy-deployed configuration templates overwrite SQL Server’s internal XML definitions with incompatible versions.

Step-by-Step Resolution Guide

Step 1: Identify the Exact XML Source File

  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the full Location: path included in the error message.
  • Note whether the file is a Policy-Based Management policy (.xml), an XML Schema Collection stored in a database, or an SSIS .dtsx package.
  • Run Get-Content <path> | Select-String "base" in PowerShell to locate the malformed node.

Step 2: Validate and Repair the XML Structure

  • Open the file in a dedicated XML editor (Visual Studio 2022/2025 or VS Code with XML extension) rather than Notepad to preserve encoding.
  • Locate <xs:extension> or <xs:restriction> tags missing the base="..." attribute and manually restore the correct type reference (commonly xs:string, xs:int, or a custom schema type).
  • If the file is a Policy-Based Management export, re-export a clean copy from a working SQL Server instance using:
  EXEC msdb.dbo.sp_syspolicy_export_policy @policy_name = 'YourPolicyName', @file_name = 'C:\Temp\CleanPolicy.xml';

Step 3: Replace or Re-import the Corrected Configuration

  • Stop the SQL Server service via services.msc or net stop MSSQLSERVER.
  • Replace the corrupted file at its original path with the validated/repaired version.
  • Restart the SQL Server service with net start MSSQLSERVER and monitor the ERRORLOG for recurrence of Error 2316.

Step 4: Rebuild the XML Schema Collection (If Database-Level)

  • If the error originates from a database XML Schema Collection rather than a file, drop and recreate it using:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollection AS N'<corrected XML content>';
  • Ensure the corrected XML includes all base attributes required by any xs:extension or xs:restriction elements before re-running the CREATE statement.

Alternative or Verification Steps

  • Verify the fix by querying sys.messages for Error 2316 occurrences and confirming the SQL Server Agent/Policy Management jobs complete without triggering the XML parse failure.
  • If the issue persists, restore the entire msdb database (if policy-related) from a last-known-good backup, since corrupted system metadata can sometimes bypass file-level fixes.

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

Troubleshooting Guide: SQL Server Error 2317 – XSD Base Type Not a Simple Type

Why This Error Happens

This error occurs when SQL Server’s XML schema collection parser encounters an XSD element that references a complex type as its base type, where a simple type (such as xs:string, xs:integer, or a user-defined simple type) is required. This typically happens during CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION operations when a <xs:simpleContent> or <xs:restriction> element incorrectly points to a <xs:complexType> definition instead of a <xs:simpleType>. It can also surface due to a corrupted or manually edited XSD file, or when schemas imported from third-party tools don’t strictly adhere to W3C XSD simple-type derivation rules.

Step-by-Step Resolution Guide

Step 1: Locate and Isolate the Offending XSD Element

  • Open the XSD file referenced in the CREATE XML SCHEMA COLLECTION statement that triggered the error.
  • Search for the exact element name reported in the error message (the %ls placeholder in the output).
  • Check whether this element uses <xs:simpleContent> with a base= attribute — this is the most common trigger point.
  • Confirm whether the base attribute value points to a <xs:complexType> definition elsewhere in the same schema or an imported schema.

Step 2: Correct the Type Derivation in the XSD

  • Change the base attribute to reference a valid simple type, such as xs:string, xs:decimal, or a custom <xs:simpleType> defined via <xs:restriction base="xs:string">.
  • If the intention was to extend a complex type, replace <xs:simpleContent> with <xs:complexContent> instead, since <xs:complexContent> is valid for extending/restricting complex types.
  • Validate the corrected XSD using an external validator (e.g., Visual Studio’s XML Schema Explorer or xmllint --schema) before re-importing it into SQL Server.

Step 3: Drop and Recreate the XML Schema Collection

  • Run the following in SQL Server Management Studio (SSMS) on SQL Server 2025:
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
GO
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName
AS N'<paste corrected XSD content here>';
GO
  • If the schema collection is referenced by existing tables or columns of type xml, you may need to temporarily drop the column constraint or use ALTER XML SCHEMA COLLECTION instead of DROP/CREATE to add the corrected complex/simple type definitions without breaking dependencies.

Step 4: Check for Nested or Imported Schema Conflicts

  • If the XSD uses <xs:import> or <xs:include> to pull in external schemas, verify that those external files also comply with simple/complex type separation rules.
  • Re-check namespace declarations (targetNamespace, xmlns) to ensure the base type reference isn’t accidentally resolving to the wrong namespace’s complex type due to a naming collision.

Alternative or Verification Steps

  • After recreating the schema collection, test it by inserting a sample XML document that conforms to the schema using INSERT INTO YourTable (XmlColumn) VALUES ('<sample XML>') — if no errors are thrown, the schema is valid.
  • If the issue persists and you cannot modify the source XSD (e.g., it’s vendor-supplied), use WITH XMLNAMESPACES and a modified local copy of the schema with the type reference corrected, then import that revised copy instead of the original file.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 2314

Why This Error Happens

Error 2314 occurs when a numeric attribute within an SSIS package, SQL Server Analysis Services (SSAS) cube property, or a database configuration setting (such as file growth size, max degree of parallelism, or buffer size) is set to a negative integer where only zero or positive values are permitted. This typically results from a misconfigured XML/JSON property file, a corrupted package deployment, or manual editing of configuration values outside of valid boundaries. In some cases, this is triggered programmatically when an application passes a calculated negative value (due to a logic error or overflow) to a SQL Server object property via API or T-SQL script.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Attribute

  • Check the full error message text for the specific attribute name referenced in the “%ls” placeholder (e.g., “FileGrowth,” “MaxSize,” or “Timeout”).
  • Open SQL Server Management Studio (SSMS) and review the Activity Log or SSIS execution report under Integration Services Catalogs > SSISDB > Reports > All Executions.
  • Cross-reference the attribute name with the relevant configuration file or stored procedure parameter.

Step 2: Correct the Configuration Value

  • Navigate to the specific database property causing the issue. For file-based errors, right-click the database in SSMS, select Properties > Files, and ensure “Autogrowth” values are set to a positive number (e.g., 10% or 64MB, not -1).
  • For SSAS or SSIS package properties, open the project in SQL Server Data Tools (SSDT) and locate the .dtsx or .xml file manually if the GUI is inaccessible.
  • Search for the attribute tag (e.g., <DTS:Property Name="MaxBufferSize">) and replace the negative integer with a valid positive value or 0.

Step 3: Validate Server-Level Configuration Settings

  • Open a new query window in SSMS and run sp_configure to check global server settings like ‘max server memory’ or ‘cost threshold for parallelism’.
  • Ensure no advanced options have been inadvertently set to a negative value via a legacy sqlcmd script:
 EXEC sp_configure 'show advanced options', 1;
 RECONFIGURE;
 EXEC sp_configure;
  • If a negative value is found, reset it using EXEC sp_configure 'attribute_name', 0; followed by RECONFIGURE WITH OVERRIDE;.

Step 4: Redeploy or Restart the Service

  • Save the corrected configuration file or script and redeploy the SSIS package to the SSISDB catalog.
  • Restart the SQL Server (MSSQLSERVER) service via the Services app (services.msc) on Windows Server 2025 to ensure the corrected cached configuration is loaded into memory.

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific job, package, or query that triggered Error 2314 via SQL Server Agent or SSDT; check the Execution Results tab for a “Success” status with no attribute-related warnings.
  • Alternative Solution: If the configuration file remains corrupted or inaccessible, delete the specific SSIS project from the SSISDB catalog and redeploy a clean backup version of the .ispac file to bypass the corrupted attribute entirely.

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

Troubleshooting Guide: SQL Server Error 2315 — “The attribute “”%ls”” should have a string value.”

Why This Error Happens

Error 2315 occurs when the SQL Server Windows Installer (MSI) or an internal configuration reader encounters an attribute in the installer database, configuration file, or XML-based setup manifest that is malformed, non-string, or null where a string value is strictly expected. This typically stems from a corrupted installer cache file, a damaged .msi/.msp patch, or improperly edited configuration XML (such as ConfigurationFile.ini or setup manifest attributes) during an upgrade or repair operation on SQL Server 2025. It can also surface when third-party deployment tools inject invalid registry or property values into the Windows Installer transaction.

Step-by-Step Resolution Guide

Step 1: Verify and Repair the Windows Installer Cache

  • Navigate to C:\Windows\Installer and confirm the cached .msi files referenced by SQL Server setup are not zero-byte or missing.
  • Run msiexec /unreg followed by msiexec /regserver in an elevated Command Prompt to re-register the Windows Installer service.
  • Use the SQL Server Installation Center to run a Repair operation: Setup.exe /ACTION=Repair /INSTANCENAME=MSSQLSERVER.

Step 2: Validate the Setup Configuration File

  • Open the ConfigurationFile.ini (typically found in %ProgramFiles%\Microsoft SQL Server\160\Setup Bootstrap\Log\<timestamp>\) and check for blank, null, or numeric values assigned to attributes expecting strings (e.g., INSTANCENAME, FEATURES, SQLSYSADMINACCOUNTS).
  • Remove any malformed or duplicate key-value pairs and ensure all string attributes are wrapped in quotes where required.
  • Save the file in ANSI/UTF-8 encoding (not UTF-16) to avoid parser misreads.

Step 3: Clear Corrupted Setup Bootstrap Cache

  • Delete temporary bootstrap cache at %ProgramFiles%\Microsoft SQL Server\160\Setup Bootstrap\Cache\ (back up first if needed).
  • Clear the %TEMP% directory for the account running setup to eliminate stale installer fragments.
  • Re-launch Setup.exe as Administrator to force regeneration of a clean cache.

Step 4: Check Windows Registry for Invalid Installer Properties

  • Open regedit and navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\.
  • Locate the GUID associated with your SQL Server 2025 instance and inspect the InstallProperties key for any non-string (REGDWORD/REGBINARY) values mistakenly placed where REG_SZ is expected.
  • Correct the data type via right-click → Modify, ensuring the value type matches REG_SZ.

Alternative or Verification Steps

  • After applying fixes, re-run setup with verbose logging: Setup.exe /ACTION=Install /INDICATEPROGRESS /Log "C:\SQLLogs\setup_verbose.log" and confirm Error 2315 no longer appears in the generated log.
  • If the issue persists, download a fresh copy of the SQL Server 2025 installation media (the current ISO may be corrupted) and re-attempt setup from a new mounted drive letter.

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

Troubleshooting Guide: SQL Server Error 2312 – XML Schema Attribute Type Mismatch

Why This Error Happens

Error 2312 occurs when SQL Server’s XML parser validates an XML document or instance against a registered XML Schema Collection (XSD) and finds that an attribute’s value does not match its declared data type (e.g., a non-numeric string assigned to an xs:integer or an invalid date format assigned to xs:dateTime). This is typically caused by malformed source data being inserted into a typed xml column, a mismatched or outdated XML Schema Collection definition, or data corruption introduced during an ETL/import process. It can also surface after an application update changes the XML payload structure without updating the corresponding schema collection in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Attribute and Value

  • Capture the full error message text, including the %ls placeholders, which will reveal the exact attribute name, the expected XML Schema type (e.g., dateTime, int, boolean), and the invalid value.
  • Run the failing INSERT or UPDATE statement in isolation using SQL Server Management Studio (SSMS) on Windows Server 2025 to reproduce the error in a controlled session.
  • Use SELECT xml_column.query('.') on the staging data (if available) to inspect the raw XML before it is cast to the typed column.

Step 2: Validate the XML Schema Collection Definition

  • Query the current schema collection definition to confirm expected data types:
SELECT xsc.name, xsc.xml_schema_namespace, 
       CAST(xml_schema_namespace AS xml) AS schema_definition
FROM sys.xml_schema_collections xsc
WHERE xsc.name = 'YourSchemaCollectionName';
  • Compare the attribute type (e.g., xs:decimal, xs:boolean) in the schema against the actual value being passed in the XML payload.
  • Check for locale-related formatting issues, such as decimal separators (, vs .) or date formats (MM/DD/YYYY vs ISO 8601 YYYY-MM-DDTHH:MM:SS), which commonly cause type mismatches on Windows Server 2025 with regional settings differences.

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

  • If the source application is sending malformed data, correct the data generation logic (e.g., ensure integers are not passed with leading zeros as strings, or booleans use true/false/0/1 strictly).
  • If the schema itself is outdated, alter the XML Schema Collection to reflect the correct type:
ALTER XML SCHEMA COLLECTION YourSchemaCollectionName ADD
'<xs:schema>... updated type definition ...</xs:schema>';
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER if the schema cache appears stale after the update.

Step 4: Test with a Minimal XML Sample

  • Strip the XML payload down to a single attribute/value pair that matches the error and test it against the schema collection using sys.xml_schema_collections validation in a sandbox table.
  • Incrementally add back attributes until the error reproduces, isolating exactly which field is non-compliant.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement after correcting the data or schema; confirm no Error 2312 is raised and verify data integrity with SELECT * FROM YourTable WHERE xml_column IS NOT NULL.
  • If the issue persists intermittently, consider relaxing strict typing by temporarily using an untyped xml column for ingestion, then validating and casting to the typed column only after a successful TRY_CAST or schema validation pass in a staging procedure.

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

Troubleshooting Guide: Error 2313 – Invalid Attribute Value

Why This Error Happens

Error 2313 occurs when the SQL Server 2025 installer or Windows Installer (MSI) engine encounters an attribute in the installation package that contains a value outside its accepted range or format. This is typically triggered by a corrupted installation cache file, a malformed registry entry left over from a previous install/uninstall, or an incompatible configuration property being passed during a command-line (unattended) installation. In most cases, the root cause is a damaged .msi package or stale Windows Installer cache data stored under the C:\Windows\Installer directory.

Step-by-Step Resolution Guide

Step 1: Clear the Windows Installer Cache

  • Open Command Prompt as Administrator.
  • Run msizap.exe TWG {Product-GUID} if you have the Windows SDK tools installed, or manually clear orphaned entries via C:\Windows\Installer.
  • Navigate to C:\ProgramData\Package Cache and rename the folder to Package Cache.old to force a clean rebuild on next install attempt.
  • Restart the Windows Installer service: net stop msiserver followed by net start msiserver.

Step 2: Validate the SQL Server 2025 Setup Media

  • Re-download the SQL Server 2025 ISO from the official Microsoft Volume Licensing or Evaluation Center to rule out a corrupted source file.
  • Mount the ISO and verify checksum integrity using Get-FileHash .\SQLServer2025-x64-ENU.iso -Algorithm SHA256 in PowerShell.
  • If running an unattended install, inspect your ConfigurationFile.ini for malformed string values (e.g., invalid characters in INSTANCENAME or SQLSYSADMINACCOUNTS).

Step 3: Repair or Reset the Registry Keys for SQL Server Components

  • Open regedit and navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server.
  • Look for any orphaned or duplicate keys referencing a previous SQL Server 2025 CTP/RC build.
  • Export the key as a backup, then delete any entries with blank or null-terminated attribute values that could be triggering the 2313 validation failure.
  • Reboot Windows Server 2025 / Windows 11 before attempting the installation again.

Step 4: Run the Installer with Verbose Logging

  • Execute the setup with full logging enabled to pinpoint the exact attribute causing the failure:
  • Setup.exe /Action=Install /QUIET /IACCEPTSQLSERVERLICENSETERMS /Log="C:\SQLLogs\sql_install_log.log"
  • Open the generated log and search for the string "Error 2313" to identify the specific property name listed in the %ls placeholder.

Alternative or Verification Steps

  • To verify the fix, re-run the SQL Server 2025 setup wizard and confirm it progresses past the Feature Selection screen without triggering the MSI validation error.
  • If the error persists, use the Microsoft Program Install and Uninstall Troubleshooter tool to fully purge remnants of SQL Server before attempting a fresh installation.

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

Troubleshooting Guide: SQL Server Error 2310 – “The attribute ‘%ls’ is declared more than once”

Why This Error Happens

This error occurs when SQL Server 2025 parses an XML Schema Collection, XML document, or SSIS/DACPAC metadata file (such as a .dacpac, .bacpac, or XSD-based schema) that contains a duplicate attribute definition within the same element or complex type. This is typically caused by a corrupted or manually edited XML/schema file, a flawed schema merge during an upgrade from a previous SQL Server version, or a third-party tool generating malformed XML with redundant attribute declarations. Because the XML parser enforces strict uniqueness constraints on attribute names within a given scope, it rejects the entire schema or document load, halting the associated operation (e.g., CREATE XML SCHEMA COLLECTION, SSDT deployment, or Service Broker message validation).

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source

  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full error context, including the schema collection name or file path.
  • If triggered by a deployment, inspect the .dacpac/.bacpac file by renaming it to .zip and extracting it to review model.xml for duplicate attributes (e.g., search for repeated Name= entries within the same <Element> tag).
  • Run the following to identify the schema collection in question:
  SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;

Step 2: Correct the Duplicate Attribute in the Source File

  • Open the identified XML/XSD file in a validating editor (Visual Studio 2025 or VS Code with the XML extension installed).
  • Locate the element flagged in the error message and remove or rename the duplicate attribute so each attribute name appears only once per element scope.
  • Save the file with UTF-8 encoding to avoid introducing hidden byte-order-mark (BOM) corruption that can also trigger parser errors.

Step 3: Re-register or Re-import the Corrected Schema

  • If the error originates from a schema collection, drop and recreate it:
  DROP XML SCHEMA COLLECTION dbo.MySchemaCollection;
  GO
  CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'<corrected XML content>';
  GO
  • For DACPAC/BACPAC deployments, re-zip the corrected model.xml back into the package and redeploy using SqlPackage.exe from an elevated PowerShell prompt on Windows Server 2025.
  • Clear any cached deployment artifacts in %TEMP%\SqlPackageTemp before retrying.

Step 4: Validate Upstream Tooling

  • If the file was auto-generated (e.g., via SSDT, SSIS, or a CI/CD pipeline), update the generating tool to the latest version, as older versions are known to emit duplicate attribute nodes during schema merges.
  • Re-run the generation process and re-diff the output XML against the previous corrupted version.

Alternative or Verification Steps

  • Validate the fix by re-running the original failing command (schema creation, deployment, or Service Broker message send) and confirming Error 2310 no longer appears in the Error Log or SSMS output pane.
  • As an alternative, use an XSD validation tool (e.g., xmllint --noout --schema or Visual Studio’s “Validate XML” feature) against the corrected file before reloading it into SQL Server to catch any remaining structural issues proactively.

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

Why This Error Happens

Error 2311 occurs when SQL Server attempts to parse or register an XML Schema Collection that contains a duplicate attribute declaration within the same complex type or scope. This typically happens when an XSD file is manually edited, merged from multiple sources, or generated by a third-party tool that duplicates attribute nodes during export. SQL Server’s XML parser strictly enforces W3C schema rules, so any redundant <xs:attribute> definition inside the same <xs:complexType> or <xs:attributeGroup> will cause the schema registration (via CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION) to fail immediately.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Check the SQL Server error log or SSMS output for the exact schema collection name referenced in the error message (the %ls placeholders will show the attribute name and containing type).
  • Run the following query to locate schema collections in the affected database:
  SELECT name, schema_id, create_date 
  FROM sys.xml_schema_collections 
  WHERE name NOT IN ('sys', 'INFORMATION_SCHEMA');
  • Export the raw XSD content using xml_schema_namespace function or extract it from the original deployment script/DACPAC.

Step 2: Locate and Remove the Duplicate Attribute

  • Open the XSD file in a text editor or XML-aware IDE (Visual Studio, VS Code with XML extension).
  • Search for the specific attribute name mentioned in the error (e.g., id, version, lang) within the named complex type.
  • Delete the redundant <xs:attribute name="..."> declaration, keeping only one instance per complex type/attribute group.
  • Validate the corrected XSD locally using a standalone validator (e.g., xmllint --noout --schema file.xsd) before attempting to re-import it.

Step 3: Re-register the Corrected Schema Collection

  • Drop the broken schema collection if it exists in a partially registered state:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Re-create it using the cleaned XSD file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS 
  N'<cleaned XSD content here>';
  • If deploying via DACPAC or a Database Project in Visual Studio 2022/2025, rebuild the project after saving the corrected .xsd file to ensure the duplicate isn’t reintroduced from cached build artifacts.

Step 4: Clear Cached Build Artifacts (If Using CI/CD or SSDT)

  • Delete the bin and obj folders in your SQL Server Database Project (SSDT) to remove stale XSD copies.
  • Re-run the build/publish pipeline to regenerate the deployment script from the corrected source file.

Alternative or Verification Steps

  • Confirm the fix by querying sys.xml_schema_collections again and running a test INSERT or CAST operation against an XML column that references the schema, ensuring no errors are thrown.
  • If the schema is deployed via a third-party application (e.g., SharePoint, BizTalk, or a vendor ERP system), check for a newer vendor-supplied patch, as duplicate attributes are often introduced by outdated export templates rather than manual edits.

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

Troubleshooting Guide: SQL Server Error 2308 – Undefined Name Reference Within Namespace

Why This Error Happens

Error 2308 occurs when SQL Server’s XML Schema Collection validator encounters a reference to an element, attribute, or type that has not been defined within the specified XML namespace. This typically happens due to a malformed or incomplete XSD schema being registered via CREATE XML SCHEMA COLLECTION, a missing <xs:import> statement for an external namespace, or schema component ordering issues where a type is referenced before it is declared. It can also surface after an in-place upgrade to SQL Server 2025 if legacy schema collections relied on deprecated XQuery/XSD parsing behaviors no longer tolerated by the updated engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection

  • Run the following query to locate schema collections in the affected database:
  SELECT name, schema_id, xml_schema_namespace 
  FROM sys.xml_schema_collections;
  • Cross-reference the namespace reported in the error message (%ls) with the output to isolate the exact collection causing the failure.
  • Check SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the full stack trace and timestamp correlating to the failure.

Step 2: Validate the XSD Source File

  • Export the schema definition using xml_schema_namespace and open it in an XML editor (Visual Studio or VS Code with XML extension).
  • Confirm every <xs:element> or <xs:complexType> referenced via ref= or type= attributes has a matching top-level declaration in the same or an explicitly imported namespace.
  • Verify that any external namespace dependencies include a proper import statement:
  <xs:import namespace="http://example.com/external" schemaLocation="external.xsd"/>
  • Use a standalone XSD validator (e.g., xmllint --schema on Windows via WSL, or the .NET XmlSchemaSet class) to confirm the file is well-formed outside of SQL Server before re-importing.

Step 3: Drop and Recreate the Schema Collection

  • Since XML Schema Collections cannot be altered to remove a broken component, drop the collection entirely:
  DROP XML SCHEMA COLLECTION [SchemaCollectionName];
  • Recreate it with the corrected XSD content:
  CREATE XML SCHEMA COLLECTION [SchemaCollectionName]
  AS N'<corrected XSD content here>';
  • Ensure the SQL Server service account has read permissions on any network path if the schema is loaded via OPENROWSET(BULK...).

Step 4: Rebuild Dependent Objects

  • Any tables, stored procedures, or XML-typed columns bound to the dropped schema collection will need to be re-associated.
  • Re-run ALTER TABLE statements to reapply the xml (SchemaCollectionName) typed column binding where applicable.
  • Restart the SQL Server service via Services.msc or PowerShell to clear cached execution plans:
  Restart-Service -Name MSSQLSERVER -Force

Alternative or Verification Steps

  • Confirm the fix by re-running the original DML/DDL statement that triggered Error 2308; it should now execute without referencing an undefined namespace.
  • If the error persists, use sys.dm_exec_describe_first_result_set or enable Extended Events (xml_deadlock_report class filtered for schema validation) to trace exactly which query or application call is invoking the broken schema collection.

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

Troubleshooting Guide: SQL Server Error 2309 – “The value of ‘%ls’ is not a valid number”

Why This Error Happens

This error typically occurs when SQL Server Setup or a configuration script encounters a parameter value that is expected to be numeric (such as a port number, instance ID, or memory allocation value) but instead receives a blank, corrupted, or non-numeric string. This is commonly caused by malformed command-line arguments passed during an unattended installation, corrupted entries in the ConfigurationFile.ini, or locale/regional settings on Windows Server 2025 / Windows 11 that use a different decimal or thousands separator than SQL Server expects. In rare cases, it can also stem from a corrupted registry key under the SQL Server instance hive that stores a numeric configuration value.

Step-by-Step Resolution Guide

Step 1: Validate the Configuration File or Command-Line Parameters

  • Open the ConfigurationFile.ini typically located at C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log\<timestamp>\ConfigurationFile.ini.
  • Check numeric fields such as SQLSVCINSTANTFILEINIT, TCPPORT, NPENABLED, ASCOLLATION, and SQLBACKUPDIR sizing values for stray spaces, quotation marks, or non-numeric characters.
  • If running from PowerShell or CMD, re-verify any /PORT=, /INSTANCEID=, or /SQLBACKUPDIR= switches do not contain accidental text or environment variable expansion errors.
  • Example: setup.exe /ACTION=Install /TCPPORT=1433 instead of /TCPPORT="1433 ".

Step 2: Check Regional and Language Settings

  • Go to Control Panel > Region > Formats and confirm the decimal symbol is set to a period (.) if SQL Server Setup expects US-style numeric formatting.
  • Navigate to Administrative > Change system locale and ensure it matches the supported locale for your SQL Server 2025 build.
  • Restart the server after changing locale settings to ensure the change propagates to the SQL Server Setup process.

Step 3: Inspect and Repair Registry Numeric Keys

  • Open regedit and navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\<InstanceID>\MSSQLServer\Parameters.
  • Look for any parameter value (such as SQLArg0, SQLArg1) that should be numeric but shows blank, text, or unexpected characters.
  • Correct the value manually or restore it from a known-good backup of the registry hive, then restart the SQL Server (MSSQLSERVER) service.

Step 4: Re-run Setup with Logging Enabled

  • Launch Setup with verbose logging: setup.exe /ACTION=Install /INDICATEPROGRESS /QUIET /FEATURES=SQL /SkipRules=RebootRequiredCheck /ENU.
  • Review the detailed log at Summary.txt and Detail.txt in the Setup Bootstrap Log folder to pinpoint exactly which numeric parameter triggered Error 2309.
  • Correct the identified parameter and re-run the installation.

Alternative or Verification Steps

  • After applying fixes, re-run setup.exe /ACTION=Install and confirm no Error 2309 appears in the Setup Summary log; successful completion should show “Setup completed successfully” status.
  • As an alternative, use SQL Server Configuration Manager to manually set affected numeric properties (e.g., TCP port under SQL Server Network Configuration > Protocols) instead of relying on the installer-provided values.

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

Why This Error Happens

This error occurs when SQL Server’s XML parser encounters a qualified name (a name containing a colon, such as ns:ElementName) in an XML instance or schema location where the XML specification strictly requires an NCName (Non-Colonized Name). This typically happens during XML Schema Collection (XSD) validation when an attribute of type ID, IDREF, or NCName contains a namespace-prefixed value instead of a simple, colon-free identifier. It is almost always a data/schema authoring issue rather than a SQL Server engine fault, often surfacing after migrating XSDs or XML data types from older collations or third-party XML generators.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Schema Collection

  • Run the following query to locate schema collections in use on the affected database:
  SELECT name, xml_schema_namespace, schema_id 
  FROM sys.xml_schema_collections;
  • Cross-reference the schema collection against the table/column reported in the error stack trace from SQL Server ERRORLOG (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Confirm which XSD defines elements/attributes typed as xs:ID, xs:IDREF, or xs:NCName.

Step 2: Inspect and Correct the XML Instance Data

  • Open the XML payload being inserted/validated and search for attribute values containing a colon (:) inside fields typed as NCName, ID, or IDREF.
  • Example of invalid value: id="ns:Record001" — the colon makes this a qualified name, not an NCName.
  • Correct it to a colon-free identifier: id="Record001".
  • If the XML is generated by an external ETL tool or application, update its XML serializer configuration to strip namespace prefixes from ID-typed fields before transmission.

Step 3: Validate and Re-register the XML Schema Collection

  • Drop and recreate the schema collection with the corrected XSD:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;
  GO
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollection AS 
  N'<your corrected XSD content>';
  • Re-run the original INSERT/UPDATE statement that triggered Error 2306 to confirm the schema accepts the corrected XML.

Step 4: Patch and Restart the SQL Server Instance (If Persistent)

  • Ensure SQL Server 2025 has the latest Cumulative Update applied via SQL Server Installation Center or Setup.exe /Action=Patch.
  • Restart the SQL Server service from Services.msc (SQL Server (MSSQLSERVER)) on Windows Server 2025/Windows 11 to clear any cached, malformed schema validation plans.

Alternative or Verification Steps

  • Validate the corrected XML against the XSD independently using PowerShell: [xml]$doc = Get-Content "file.xml"; $doc.Schemas.Add($null, "schema.xsd"); $doc.Validate($null) — no exceptions confirms the fix.
  • If the error persists despite clean XML, isolate whether it is a third-party application (e.g., SSIS package or ORM tool) generating malformed XML by testing a manually crafted minimal XML sample directly in SQL Server Management Studio (SSMS).

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

Troubleshooting Guide: SQL Server Error 2307 — “Reference to an undefined name”

Why This Error Happens

Error 2307 typically occurs when a Transact-SQL batch, stored procedure, view, or function references an object, column, alias, or variable name that SQL Server cannot resolve within the current scope or schema context. This is commonly caused by a missing or mistyped identifier, a schema binding mismatch, or a database object that was dropped or renamed after a dependent module was compiled. On Windows Server 2025 / Windows 11 deployments, this can also surface after an in-place upgrade to SQL Server 2025 if deprecated syntax or deferred name resolution behaves differently under the new compatibility level.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Object or Name Causing the Conflict

  • Open the full error message in SQL Server Management Studio (SSMS) — the %ls placeholder will show the specific undefined name.
  • Run sp_helptext 'YourProcedureName' to review the full definition of the failing module.
  • Check for typos in table names, column names, aliases, or variable declarations (e.g., @VarName missing a DECLARE statement).

Step 2: Validate Schema and Object Dependencies

  • Execute SELECT * FROM sys.sql_expression_dependencies WHERE referencing_id = OBJECT_ID('YourProcedureName'); to confirm all referenced objects still exist.
  • Confirm the correct schema prefix is used (e.g., dbo.TableName instead of just TableName) to avoid ambiguous resolution.
  • If the object was recently renamed or dropped, use sp_refreshsqlmodule 'YourProcedureName' to force SQL Server to recompile and re-validate references.

Step 3: Check Database Compatibility Level

  • Run SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase'; to verify the current setting.
  • If the database was upgraded to SQL Server 2025, deferred name resolution rules may have changed; test by temporarily setting compatibility level back one version using ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 160;
  • Re-run the failing script to see if the error persists under the older compatibility level, which helps isolate whether this is a syntax deprecation issue.

Step 4: Rebuild or Recreate the Affected Object

  • Script out the object definition (right-click → Script as → CREATE) in SSMS.
  • Drop and recreate the object using DROP PROCEDURE IF EXISTS YourProcedureName; followed by a corrected CREATE PROCEDURE statement.
  • Ensure all referenced temp tables, table variables, and CTEs are declared before use within the same batch scope.

Alternative or Verification Steps

  • After applying fixes, run the object manually (EXEC YourProcedureName;) and confirm it executes without raising Error 2307 in the SSMS Messages tab.
  • If the error persists, check Windows Event Viewer (Applications and Services Logs → MSSQLSERVER) for additional context, and consider restoring the object from a known-good backup or source control version.

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

Troubleshooting Guide: SQL Server Error 2301 – “The element has already been defined”

Why This Error Happens

Error 2301 is a schema validation error that occurs when SQL Server parses an XML document, XSD schema, or SSIS package configuration file and encounters a duplicate element definition within the same namespace scope. This typically happens due to a corrupted or manually-edited XML/XSD file, a flawed merge between two configuration files that introduced duplicate nodes, or a third-party tool/deployment script that appended schema definitions without checking for existing entries. It can also surface during DACPAC/BACPAC deployments or SSIS package validation when the underlying .dtsx or .xsd file has been corrupted during source control merges.

Step-by-Step Resolution Guide

Step 1: Identify the Source File Triggering the Error

  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full error context, including the file path or package name referenced alongside Error 2301.
  • If the error occurs during SSIS execution, check the SSIS catalog logs via SSMS: Integration Services Catalogs > SSISDB > All Executions.
  • Note the exact element name (%ls) reported — this is the duplicate node you need to locate.

Step 2: Inspect and Validate the XML/XSD File

  • Open the offending file (.dtsx, .xsd, or .xml) in Visual Studio or a dedicated XML editor like Notepad++ with the XML Tools plugin.
  • Use Ctrl+F to search for every instance of the duplicate element name identified in Step 1.
  • Confirm whether two identical <xs:element> or <xs:complexType> definitions exist within the same <xs:schema> block.
  • Remove or rename the duplicate definition, ensuring referential integrity is preserved (check for ref= or type= attributes pointing to the removed node).

Step 3: Validate the Schema Using a Clean Environment

  • Run the following command-line validation using msxsl.exe or PowerShell to confirm the corrected file parses cleanly:
[xml]$xmlDoc = Get-Content "C:\Path\To\File.xsd"
  • If the command completes without throwing an exception, the duplicate has been successfully resolved.
  • For SSIS packages, re-open the .dtsx file in SQL Server Data Tools (SSDT) and check the Error List pane for residual validation warnings.

Step 4: Redeploy and Restart the Affected Service

  • Redeploy the corrected package or schema to the target instance using dtutil (for SSIS) or SqlPackage.exe (for DACPAC deployments):
dtutil /FILE "C:\Path\To\CorrectedPackage.dtsx" /COPY FILE;"C:\Deploy\CorrectedPackage.dtsx"
  • Restart the SQL Server Agent service via services.msc or PowerShell:
Restart-Service -Name SQLSERVERAGENT -Force

Alternative or Verification Steps

  • Re-run the original job, deployment, or query that triggered Error 2301 and confirm it completes without throwing the duplicate element exception; cross-check the SSISDB execution report for a “Success” status.
  • If the error persists, restore the XML/XSD/DTSX file from the last known-good version in source control (Git/TFS) rather than manually editing, as hand-edited XML often introduces secondary namespace conflicts.

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

Troubleshooting Guide: Error 2302 — “The name “”%ls”” has already been defined in this scope.”

Why This Error Happens

This error occurs when SQL Server’s parser detects a duplicate identifier—such as a variable, parameter, cursor, or label—declared twice within the same batch, procedure, or scope. It is typically caused by copy-paste mistakes in T-SQL scripts, poorly merged source control changes, or dynamically generated SQL that redeclares a variable without checking for prior existence. In some cases, it can also surface when a script is re-executed in the same session without properly clearing previously declared session-scoped objects (like temp tables or table variables in certain nested contexts).

Step-by-Step Resolution Guide

Step 1: Identify the Duplicate Declaration

  • Open the script in SQL Server Management Studio (SSMS) and locate the exact object name referenced in the error message (replacing the %ls placeholder).
  • Use Ctrl+F to search for all instances of DECLARE @VariableName or DECLARE CursorName within the batch.
  • Pay close attention to nested BEGIN...END blocks, as variables declared inside a block are still scoped to the entire batch in T-SQL, not just the block.

Step 2: Consolidate or Rename Conflicting Declarations

  • If the same variable is declared twice unintentionally, delete the redundant DECLARE statement.
  • If two distinct variables require the same name in different logical sections, rename one of them (e.g., @OrderID to @OrderID_Temp) to avoid scope collision.
  • For dynamic SQL blocks, ensure that EXEC sp_executesql strings are not concatenating a static declaration block multiple times into the final executed string.

Step 3: Check Batch Separators (GO Statements)

  • Insert a GO statement between logical sections of a large script to force SQL Server to treat them as separate batches, effectively resetting the variable scope.
  • Note: This is useful only if the variables are genuinely meant to be independent and are not required to pass values between the sections.

Step 4: Validate Stored Procedure and Trigger Definitions

  • If the error originates from a specific stored procedure, use sp_helptext 'YourProcedureName' to review the full definition for duplicate parameter names in the procedure header.
  • Check for duplicate column aliases in SELECT statements if the error relates to a derived table or Common Table Expression (CTE) rather than a variable.

Alternative or Verification Steps

  • Verify the Fix: Execute the script again in a new query window in SSMS; if the batch compiles and runs without halting on the parsing stage, the scope conflict has been resolved.
  • Alternative Check: If the error persists despite a clean script, restart the SQL Server Management Studio session entirely, as cached execution plans or IntelliSense metadata can occasionally cause false-positive highlighting of this error in the editor (though this rarely affects actual execution).

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

Why This Error Happens

Error 2305 is thrown by the MSXML parser when it encounters an XML document containing a duplicate attribute or element definition within the same node—something the XML schema explicitly disallows. In SQL Server 2025 environments, this typically surfaces when the Setup engine, Policy-Based Management, SSIS package metadata, or the Reporting Services rsreportserver.config file reads a configuration XML that has been manually edited, merged incorrectly, or corrupted during a failed save operation. It can also occur after an interrupted Windows Update or antivirus quarantine action that partially rewrites the XML file, leaving duplicate type or similarly named attributes in the markup.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML File

  • Check the full error text for the Location: '%ls' value — this points to the exact file path and line/column reference.
  • Common culprits on Windows Server 2025 / Windows 11 include:
  • C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log\<timestamp>\ConfigurationFile.ini (if converted/wrapped in XML by custom automation)
  • C:\Program Files\Microsoft SQL Server\MSRS16.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config
  • SSIS project .dtsx or .params files under C:\Program Files\Microsoft SQL Server\160\DTS\Packages
  • Open the file in a text editor (Notepad++ or VS Code) rather than Notepad to preserve encoding.

Step 2: Locate and Remove the Duplicate Attribute/Element

  • Use Ctrl+F to search for the attribute name mentioned in the error (often type=).
  • Inspect the specific XML node referenced in the error location — look for two instances of the same attribute inside a single opening tag, e.g.:
  • <Setting name="Logging" type="File" type="Console" />
  • Delete the redundant attribute/element, keeping only one valid instance.
  • Validate the file structure using an XML validator or PowerShell:
  • [xml](Get-Content "C:\path\to\file.config")
  • If the command throws no error, the XML is now well-formed.

Step 3: Restore From Backup if Manual Edit Fails

  • If the file is too damaged to repair manually, restore a known-good version:
  • For rsreportserver.config, copy from C:\Program Files\Microsoft SQL Server\MSRS16.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config.bak (if present) or reinstall the Reporting Services feature via SQL Server Installation Center.
  • For SSIS packages, redeploy the .dtsx file from source control or the original project deployment file (.ispac).
  • Restart the associated service after replacing the file:
  • Restart-Service -Name "ReportServer" or Restart-Service -Name "MSSQLSERVER"

Step 4: Re-run the Failed Operation

  • Re-trigger the SQL Server Setup, SSIS execution, or Reporting Services configuration task that originally threw Error 2305.
  • Monitor the Windows Event Viewer (Application log, source: MSSQLSERVER or ReportServer) to confirm the XML parse step completes without re-raising Event ID 2305.

Alternative or Verification Steps

  • Verify the fix by running [xml](Get-Content "<file path>") in PowerShell — a clean return with no red error text confirms the XML is valid and parsable.
  • If the error persists after cleanup, run sfc /scannow and check for corrupted system components, then fully uninstall and reinstall the affected SQL Server feature (e.g., Reporting Services or SSIS) to regenerate default, schema-compliant configuration files.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 2299

Why This Error Happens

Error 2299 occurs when SQL Server attempts to parse an XML document against its associated XSD (XML Schema Definition) but finds that a mandatory attribute defined in the schema is absent from the instance document. This typically results from a corrupted or truncated XML payload, a mismatch between an application’s XML output and an updated schema collection, or manual edits to XML configuration files (such as Policy-Based Management policies or SSIS package XML) that stripped out required metadata. It can also surface after an in-place upgrade to SQL Server 2025 if legacy XML schema collections were not validated against the new, stricter XSD parser.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Source and Schema Collection

  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact timestamp and query context that triggered Error 2299.
  • Run the following query to locate custom XML Schema Collections tied to the affected database:
  SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;
  • Note the specific element and attribute name mentioned in the error message (e.g., "%ls"), as this tells you exactly which XSD definition is being violated.

Step 2: Validate and Repair the XML Instance Document

  • Extract the raw XML causing the failure (common sources include SSIS .dtsx package files, Policy-Based Management XML exports, or application-submitted XML data columns).
  • Open the file in a validating XML editor (e.g., Visual Studio 2022/2025 or VS Code with an XML extension) and run “Validate XML” against the linked XSD.
  • Manually re-insert the missing required attribute, ensuring correct casing and namespace prefix (XSD attribute names are case-sensitive).
  • If the XML originates from an SSIS package, re-deploy the package from the original project source in SSDT rather than editing the .dtsx file by hand.

Step 3: Verify the XSD Schema Collection Integrity

  • If the schema itself was altered during a migration, re-import the original, unmodified XSD using:
  CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS '<schema content>';
  • If upgrading from an older version (SQL Server 2019/2022), confirm compatibility level using:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the service account running the SQL Server instance (via services.msc on Windows Server 2025) has Read/Write access to any network share or folder where the XML/XSD source files are stored.

Step 4: Restart the SQL Server Service and Clear Cached Plans

  • Open SQL Server Configuration Manager, restart the SQL Server (MSSQLSERVER) service to clear any cached invalid XML schema metadata.
  • Alternatively, run DBCC FREEPROCCACHE; in SSMS to force re-compilation of stored procedures that reference the XML schema collection.

Alternative or Verification Steps

  • Re-run the original query or application process that threw Error 2299; if successful, query sys.dm_exec_query_stats to confirm no residual errors are logged against the affected object.
  • If the error persists, bypass strict schema validation temporarily by casting the column as untyped XML instead of a schema-bound type, then isolate the problematic attribute by comparing it against a known-good XML sample using diff or a text comparison tool.

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

Troubleshooting Guide: SQL Server Error 2300 – Missing Required XSD Sub-Element

Why This Error Happens

This error occurs when SQL Server 2025 attempts to validate an XML configuration file (such as a Policy-Based Management policy, SSIS package manifest, or Database Mail configuration) against its XML Schema Definition (XSD), but the file is missing a mandatory child element. This typically results from a corrupted or manually edited XML file, an incomplete export/import operation, or a version mismatch between the XML schema bundled with SQL Server 2025 and the XML file generated by an older or third-party tool. In rarer cases, file corruption during disk I/O or antivirus interference on Windows Server 2025 can truncate the XML content before SQL Server reads it.

Step-by-Step Resolution Guide

Step 1: Identify the Source XML File and Element

  • Check the full error message for the specific %ls placeholders — these indicate the exact missing sub-element and parent XSD element name (e.g., Operator, Condition, Policy).
  • Locate the source file, typically found in paths like C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ or wherever the policy/package was exported (e.g., .xml files for Policy-Based Management or .dtsx for SSIS).
  • Open the file in a text editor (Notepad++ or VS Code) and search for the parent element mentioned in the error.

Step 2: Validate and Repair the XML Structure

  • Compare the XML file against the reference schema located in C:\Program Files\Microsoft SQL Server\170\Tools\Binn\schemas\sqlserver\ (adjust version path as needed for SQL Server 2025).
  • Manually insert the missing required sub-element with a valid default value, ensuring correct nesting and closing tags.
  • If the file originated from an export, re-run the export process from the original source (e.g., SQL Server Management Studio’s “Export Policy” wizard) instead of manually editing.

Step 3: Re-import or Re-register the Corrected File

  • In SQL Server Management Studio (SSMS), navigate to Management > Policy Management > Import Policy (or the equivalent SSIS/Database Mail import dialog depending on context).
  • Select the corrected XML file and confirm no validation errors appear in the import log.
  • Restart the SQL Server Agent service via services.msc or PowerShell:
  Restart-Service -Name "SQLSERVERAGENT"

Step 4: Check for Antivirus or Permission Interference

  • Verify that Windows Defender or third-party antivirus on Windows Server 2025 is not quarantining or altering XML files in the SQL Server directories.
  • Confirm the SQL Server service account has full read/write permissions on the folder containing the XML file via Properties > Security tab.

Alternative or Verification Steps

  • Re-run the operation that triggered Error 2300 (policy evaluation, package execution, or mail configuration) and confirm no XSD-related errors appear in the SQL Server Error Log (ERRORLOG file) or Windows Event Viewer.
  • If the issue persists, generate a fresh XML file from a known-working SQL Server 2025 instance using the same feature (Policy-Based Management, SSIS, etc.) and compare it side-by-side with the corrupted file to pinpoint structural differences.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 2297

Why This Error Happens

Error 2297 occurs when SQL Server’s XML parser encounters an element that does not conform to the expected schema definition at a specific location within an XML document. This typically happens when XML data being imported, processed via FOR XML/OPENXML, or used in configuration files (such as SSIS packages, Policy-Based Management policies, or Extended Events sessions) contains malformed tags, elements placed out of sequence, or references a corrupted or outdated XSD schema. In some cases, this is triggered by a damaged system catalog XML schema collection after an in-place upgrade to SQL Server 2025 on Windows Server 2025 or Windows 11.

Step-by-Step Resolution Guide

Step 1: Identify the Source XML and Validate Its Structure

  • Locate the exact XML document or configuration file referenced in the full error message (check the %ls placeholders in the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Open the file in a validating XML editor (e.g., Visual Studio Code with XML extension) and run a well-formedness check.
  • Look for mismatched tags, missing closing elements, or elements inserted outside their defined parent-child hierarchy.

Step 2: Verify the Associated XML Schema Collection

  • Run the following query to inspect registered schema collections tied to the database in question:
SELECT name, xml_schema_namespace FROM sys.xml_schema_collections;
  • Compare the schema collection definition against the XML instance causing the error to confirm element names, order, and nesting match exactly.
  • If the schema collection is outdated or corrupted, drop and recreate it:
DROP XML SCHEMA COLLECTION dbo.YourSchemaCollection;
CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollection AS '<schema XML content here>';

Step 3: Repair or Replace Corrupted Configuration XML (SSIS/PBM/Extended Events)

  • If the error originates from an SSIS package (.dtsx) or Policy-Based Management policy, open the file in SQL Server Management Studio (SSMS) 2025 and use Validate under the XML menu.
  • Navigate to C:\Program Files\Microsoft SQL Server\160\DTS\Packages\ (or your custom deployment path) to confirm the package file has not been truncated by a failed disk write or antivirus interference.
  • Re-export or regenerate the XML/configuration file from its original source rather than manually editing it, as manual edits commonly introduce location-order errors.

Step 4: Apply the Latest Cumulative Update

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as early releases have known XML parser edge-case bugs.
  • Check your current build with:
SELECT @@VERSION;
  • Download and install the latest CU from the Microsoft Update Catalog, then restart the SQL Server (MSSQLSERVER) service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator).

Alternative or Verification Steps

  • Re-run the original operation (import, SSIS package execution, or policy evaluation) and confirm Error 2297 no longer appears in the SQL Server Error Log or Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, strip the XML down to a minimal valid sample matching the schema, confirm it processes successfully, then incrementally reintroduce elements to isolate exactly which node triggers the invalid-location error.

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

Troubleshooting Guide: Error 2298 – “Attribute ‘%ls’ is not valid at location ‘%ls'”

Why This Error Happens

Error 2298 typically occurs when SQL Server 2025 parses an XML-based configuration or schema file (such as an XML schema collection, SSIS package, or Policy-Based Management policy) and encounters an attribute that is not permitted in that specific XML element context. This is most often caused by a corrupted or manually edited XML file, a mismatch between the XML schema definition and the document instance, or an incompatible attribute introduced by a third-party tool or an incomplete upgrade from a previous SQL Server version. It can also surface when Windows Server 2025 security policies or file corruption alter the structure of configuration files read by the Database Engine at startup.

Step-by-Step Resolution Guide

Step 1: Identify the Source File Triggering the Error

  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact timestamp and context of Error 2298.
  • Cross-reference the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for Event ID 2298 to determine which XML document or schema collection is involved.
  • Note whether the error originates from an SSIS package (.dtsx), an XML Schema Collection, or a Policy-Based Management policy file (.xml).

Step 2: Validate the XML Structure Against Its Schema

  • Open the offending XML file in a validating editor (e.g., Visual Studio or VS Code with an XML extension) and run schema validation against the associated .xsd file.
  • Remove or correct any attribute flagged as invalid at its current element location — pay attention to namespace prefixes, as a missing xmlns declaration often causes attributes to appear “invalid.”
  • If the file is an SSIS package, open it in SQL Server Data Tools (SSDT) and allow it to auto-repair the package format.

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

  • Run the following T-SQL to inspect existing schema collections:
SELECT * FROM sys.xml_schema_collections;
  • Drop and recreate the affected schema collection using a clean, validated XML source:
DROP XML SCHEMA COLLECTION dbo.MySchemaCollection;
CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'<validated XML content>';
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator).

Step 4: Check for Incomplete Upgrade or Corrupted Installation Files

  • Run sqlservr.exe -c -m from an elevated Command Prompt to start SQL Server in single-user maintenance mode and check for additional startup errors.
  • Use SFC /scannow on Windows Server 2025 to confirm no underlying OS file corruption is affecting the XML parser libraries (msxml6.dll).
  • If corruption is found, repair the SQL Server 2025 instance via the Installation Center: Maintenance > Repair.

Alternative or Verification Steps

  • Verify the fix by re-running the operation that triggered Error 2298 (e.g., redeploying the SSIS package or re-importing the policy) and confirming no entry appears in the ERRORLOG afterward.
  • If the issue persists, restore the XML-dependent object (schema collection, package, or policy) from a known-good backup taken prior to the corruption, then reapply any recent legitimate changes manually.

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

Troubleshooting Guide: SQL Server Error 2293 – “Choice cannot be empty unless minOccurs is 0”

Why This Error Happens

Error 2293 typically occurs when SQL Server attempts to parse an XML schema collection (XSD) or an XML-based configuration file (such as a Policy-Based Management policy, SSIS package manifest, or Report Definition Language file) that contains a malformed <xs:choice> element lacking any child particles. This is often caused by a corrupted or incompletely written XML file, a botched upgrade/migration process that truncated schema definitions, or manual edits to system XML metadata that violate the W3C XML Schema structural rules. Because SQL Server 2025 enforces stricter schema validation against XSD definitions during startup and query execution, even a single empty <xs:choice> block will trigger a hard parsing failure at the location specified in the error message.

Step-by-Step Resolution Guide

Step 1: Identify the Exact XML Source Causing the Failure

  • Open the SQL Server Error Log via SQL Server Management Studio (SSMS) or navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Locate the full error text, paying close attention to the Location: '%ls' value, which points to the specific XML namespace or file path.
  • Cross-reference the location string with known XML schema collections using the query: SELECT * FROM sys.xml_schema_collections;

Step 2: Validate and Repair the XML Schema File

  • Extract the suspect schema using: SELECT xml_schema_namespace('dbo','YourSchemaCollectionName');
  • Open the extracted XML in Visual Studio 2022+ or a dedicated XML editor and run XML > Validate to pinpoint the broken <xs:choice> block.
  • Manually correct the schema by either adding required child elements inside <xs:choice> or explicitly setting minOccurs="0" if the choice is intentionally optional.
  • Re-import the corrected schema using CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION.

Step 3: Check for Corrupted Installation or Configuration Files

  • Navigate to C:\Program Files\Microsoft SQL Server\170\Shared\ and inspect any .xsd files tied to Policy-Based Management or Replication components.
  • Run sfc /scannow from an elevated Command Prompt on Windows Server 2025 to rule out OS-level file corruption affecting shared XML parser libraries (msxml6.dll).
  • If the issue stems from a recent SQL Server Cumulative Update, reapply the latest CU package from the Microsoft Download Center to restore clean baseline XML definitions.

Step 4: Rebuild Affected SSIS Packages or Reports (If Applicable)

  • If the error originates from an SSIS package (.dtsx) or SSRS report (.rdl), open the file in SQL Server Data Tools (SSDT) and check the underlying XML via a text editor for stray <xs:choice> tags.
  • Remove or reconfigure any custom XML schema references embedded in the package’s connection manager or data flow components.
  • Redeploy the corrected package to the SSIS Catalog or Report Server.

Alternative or Verification Steps

  • Verify the fix by restarting the SQL Server service (net stop MSSQLSERVER && net start MSSQLSERVER) and confirming the ERRORLOG no longer reports Event ID 2293 on startup.
  • If the problem persists, restore the affected database or msdb system database from a last-known-good backup taken prior to the schema corruption, then reapply any schema changes incrementally while validating XML syntax at each step.

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

Troubleshooting Guide: SQL Server Error 2294 – Invalid XML Processing Instruction Target

Why This Error Happens

This error occurs when SQL Server’s XML parser encounters a processing instruction (PI) that uses the reserved target name “xml” (in any case variation), which violates the W3C XML specification. The XML 1.0 standard explicitly reserves names matching the pattern [Xx][Mm][Ll] for the XML declaration itself, so using it as a custom processing instruction target—such as <?xml-stylesheet?> being malformed into <?xml ...?>—triggers a parse failure. This typically happens due to malformed XML data being inserted into an xml typed column, corrupted import files, or improperly generated XML from third-party ETL tools or legacy applications feeding data into SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Malformed XML

  • Locate the specific INSERT, UPDATE, or BULK IMPORT statement that triggered Error 2294 by checking SQL Server Error Logs via C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Run SELECT * FROM sys.dm_exec_requests WHERE session_id = <SPID> to correlate the failing session with the query text.
  • Export the raw XML payload to a .xml file for manual inspection using Notepad++ or VS Code on Windows 11/Windows Server 2025.

Step 2: Correct the XML Processing Instruction

  • Open the offending XML file and search for any instance of <?xml that is NOT the first line of the document (valid XML declarations must only appear once, at position 0).
  • Rename any erroneous processing instructions—for example, change <?xml-data version="1.0"?> back to a properly namespaced PI like <?xmldata version="1.0"?> or <?custom-xml version="1.0"?>.
  • Validate the corrected file using PowerShell: [xml](Get-Content "C:\temp\yourfile.xml") — if no error is thrown, the XML is well-formed.

Step 3: Patch or Update the Source Application

  • If the XML is being generated programmatically (e.g., via SSIS packages or a .NET application), check the XmlWriterSettings configuration and ensure WriteProcessingInstruction() calls never pass “xml” as the target parameter.
  • Update SSIS packages stored in C:\Program Files\Microsoft SQL Server\170\DTS\Packages\ to sanitize XML output before it reaches the xml data type column.
  • Apply the latest Cumulative Update for SQL Server 2025 via Setup.exe, as parser edge-case handling may be refined in later builds.

Step 4: Re-Run the Import or Transaction

  • Re-execute the original INSERT/UPDATE statement or BULK INSERT job using the corrected XML file.
  • Monitor sys.messages for Error 2294 recurrence: SELECT * FROM sys.messages WHERE message_id = 2294 AND language_id = 1033.

Alternative or Verification Steps

  • Verify the fix: Run SELECT CAST('<root><?validpi data="test"?></root>' AS XML) in SSMS—if it returns successfully without Error 2294, your XML parsing pipeline is now compliant.
  • Alternative workaround: If you cannot modify the source XML generator immediately, pre-process incoming XML strings using REPLACE() or a regex-based cleansing step in SSIS to strip any <?xml occurrences beyond the first line before casting the data to the xml type in SQL Server.