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

Troubleshooting Guide: SQL Server Error 6544 – Malformed or Non-Pure .NET Assembly

Why This Error Happens

This error occurs when SQL Server’s CLR integration attempts to load an assembly that is either corrupted, compiled as a mixed-mode assembly (containing both managed and unmanaged code), or targets an incompatible .NET runtime version. SQL Server 2025 strictly requires pure MSIL (Microsoft Intermediate Language) assemblies for CREATE ASSEMBLY or ALTER ASSEMBLY operations, so any unmanaged dependencies, native code references, or build corruption will trigger this failure. Additionally, file transfer corruption (e.g., binary files moved in ASCII/text mode) or assemblies compiled with an unsupported /platform switch (like x86 on an x64 instance) can also produce this error.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly Is Pure MSIL

  • Locate the compiled .dll file on disk, typically under your project’s bin\Release or bin\Debug folder.
  • Open a Visual Studio Developer Command Prompt and run corflags YourAssembly.dll.
  • Check the output: the ILONLY flag must be set to 1. If it reads 0, the assembly contains native code and must be recompiled.
  • If using C++/CLI, recompile with the /clr:pure or /clr:safe flag instead of standard /clr.

Step 2: Recompile Targeting a Compatible .NET Version

  • Open the project in Visual Studio 2022 or later.
  • Set the Target Framework to a version supported by SQL Server 2025’s CLR host (typically .NET Framework 4.8.x or the designated .NET 8/9 compatibility layer, depending on your CLR strict security mode).
  • Ensure the build configuration is set to “Any CPU” rather than a specific architecture like x86, unless your SQL Server instance specifically requires it.
  • Rebuild the solution and confirm zero build warnings related to platform targets.

Step 3: Check for File Transfer Corruption

  • If the DLL was copied from a Linux container, Git repository, or email attachment, verify it wasn’t altered by line-ending conversion (CRLF/LF) settings.
  • Re-copy the file using binary transfer mode (e.g., scp -B or FTP in Binary mode, not ASCII).
  • Compare file hash checksums (CertUtil -hashfile YourAssembly.dll SHA256) between source and destination to confirm integrity.

Step 4: Re-run the CREATE ASSEMBLY Command

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Execute the command using the validated binary path:
CREATE ASSEMBLY YourAssemblyName
FROM 'C:\SQLAssemblies\YourAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • If loading via FROM (binary), ensure the hex string wasn’t truncated during copy-paste in the query window.

Step 5: Confirm CLR Strict Security Settings

  • Since SQL Server 2017+ (and enforced further in 2025), CLR Strict Security requires assemblies to be signed or added to a trusted assemblies list if not signed by a trusted certificate.
  • Run the following to check trust status:
SELECT * FROM sys.trusted_assemblies;
  • If missing, add the assembly hash using sp_add_trusted_assembly to bypass unnecessary signature validation errors that sometimes manifest alongside Error 6544.

Alternative or Verification Steps

  • Verification: After re-running CREATE ASSEMBLY, query sys.assemblies to confirm the new entry exists with the correct clr_name and permission_set_desc.
  • Alternative: If recompiling isn’t possible (third-party DLL), try loading the assembly on a non-production SQL Server instance with PERMISSION_SET = UNSAFE and TRUSTWORTHY ON temporarily to isolate whether the issue is a security block or a genuine binary corruption issue.

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

Troubleshooting Guide: SQL Server Error 6545 — “Enabling of Execution Statistics SET Options Not Allowed Within CLR Procedure or Function”

Why This Error Happens

This error occurs because SQL Server’s CLR integration does not permit changes to execution statistics SET options (such as STATISTICS XML, STATISTICS PROFILE, or STATISTICS IO) to be toggled from inside managed code running in a CLR stored procedure, function, trigger, or user-defined type. These SET options are session-level diagnostic switches that SQL Server manages internally through the Tabular Data Stream (TDS) protocol, and the CLR execution context runs in a sandboxed environment that does not have authority to alter them. Essentially, the error is a design restriction rather than a configuration failure — the managed code is attempting an operation that is architecturally off-limits within the SQLCLR hosting environment.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Code

  • Review the assembly source code deployed to SQL Server 2025 and search for any SqlCommand or ADO.NET calls that issue SET STATISTICS XML ON, SET STATISTICS PROFILE ON, or SET STATISTICS IO ON from within the managed procedure/function body.
  • Use sys.assembly_modules and sys.assemblies to map the failing object back to its source .dll and corresponding .cs or .vb file.
  • Check Application Event Viewer (Windows Logs > Application) for Event ID 6545 correlated with the SPID and timestamp to pinpoint the exact call stack.

Step 2: Remove or Relocate the SET Statement

  • Delete the SET STATISTICS ... command from inside the CLR procedure/function code entirely, since it cannot execute in that context.
  • If statistics capture is required for performance analysis, move the SET STATISTICS XML ON command to the calling T-SQL batch that invokes the CLR object, not inside the managed code itself.
  • Recompile the assembly using Visual Studio or csc.exe, then redeploy via CREATE ASSEMBLY or ALTER ASSEMBLY in SSMS.

Step 3: Adjust CLR Integration and Permission Settings

  • Open SQL Server Management Studio (SSMS) and run:
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Verify the assembly’s PERMISSION_SET is not set to UNSAFE unnecessarily — use SAFE or EXTERNAL_ACCESS unless cross-API access is explicitly required:
  ALTER ASSEMBLY YourAssemblyName WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via services.msc on Windows Server 2025 or Windows 11 to ensure the CLR host environment reloads cleanly after permission changes.

Step 4: Test the Corrected Procedure

  • Deploy the updated assembly to a non-production instance first.
  • Execute the CLR stored procedure/function manually in SSMS using EXEC dbo.YourCLRProcedure; and confirm Error 6545 no longer appears in the Messages tab or Event Viewer.

Alternative or Verification Steps

  • Run SET STATISTICS XML ON; directly in the SSMS query window before calling the CLR procedure (not inside the CLR code) to confirm execution statistics now render correctly without triggering the error.
  • If the error persists, drop and recreate the assembly entirely using DROP ASSEMBLY followed by a fresh CREATE ASSEMBLY to rule out a corrupted or stale metadata registration in sys.assemblies.

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

Troubleshooting Guide: SQL Server Error 6541 – ALTER ASSEMBLY Failed Due to Multiple Associated Files

Why This Error Happens

This error occurs because the target assembly in SQL Server has multiple files associated with it (the main DLL plus additional files such as debug symbols or dependent modules), but the ALTER ASSEMBLY statement you’re attempting only supports modifying a single-file assembly structure directly. SQL Server’s CLR integration tracks each file added to an assembly via CREATE ASSEMBLY ... FROM (file1, file2, ...) as separate entries in sys.assembly_files, and ALTER ASSEMBLY cannot implicitly overwrite or ignore the extras. This typically happens after a .pdb file or an additional resource file was bundled in during initial deployment and was never cleaned up.

Step-by-Step Resolution Guide

Step 1: Identify the Extra Files Associated with the Assembly

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to list all files tied to the problematic assembly:
SELECT af.file_id, af.name, a.name AS assembly_name
FROM sys.assembly_files af
JOIN sys.assemblies a ON af.assembly_id = a.assembly_id
WHERE a.name = 'YourAssemblyName';
  • Note the file_id values greater than 1 (file_id = 1 is typically the primary DLL).

Step 2: Drop the Extra Files Using ALTER ASSEMBLY DROP FILE

  • Execute the ALTER ASSEMBLY ... DROP FILE command for each extra file identified in Step 1.
ALTER ASSEMBLY YourAssemblyName DROP FILE FROM FILE_ID = 2;
  • Repeat this command sequentially for any remaining file_id entries (3, 4, etc.) until only file_id = 1 remains.
  • If the extra file is a .pdb (debug symbol file), confirm with your development team that removing it won’t impact debugging CLR stored procedures in production.

Step 3: Re-run the Original ALTER ASSEMBLY Command

  • Once extra files are removed, re-attempt your original update command.
ALTER ASSEMBLY YourAssemblyName
FROM 'C:\SQLAssemblies\YourAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • Verify the path is accessible by the SQL Server service account, especially on Windows Server 2025 where enhanced file system ACLs may restrict access to folders outside default SQL Server directories (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\).

Step 4: Check Assembly Dependencies Before Finalizing

  • Query sys.assembly_references to ensure no other assemblies depend on the file you just dropped.
SELECT * FROM sys.assembly_references WHERE referenced_assembly_id = (SELECT assembly_id FROM sys.assemblies WHERE name = 'YourAssemblyName');
  • If dependencies exist, update or redeploy dependent assemblies after confirming the primary assembly altered successfully.

Alternative or Verification Steps

  • Verify the fix by re-running the Step 1 query against sys.assembly_files; a successful fix will show only one row (file_id = 1) for the assembly.
  • If ALTER ASSEMBLY DROP FILE continues to fail due to permission issues, drop the entire assembly using DROP ASSEMBLY YourAssemblyName (ensure you have a backup of the DLL) and recreate it fresh using a single-file CREATE ASSEMBLY statement instead of altering the existing multi-file structure.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 6542

Why This Error Happens

Error 6542 (“Cannot create object because %ls is a generic type”) occurs when SQL Server’s CLR integration attempts to instantiate a .NET assembly type that is defined as an open generic type rather than a fully constructed, closed type. This typically happens after upgrading to SQL Server 2025 when a legacy CLR assembly compiled against an older .NET Framework or runtime attempts to register generic classes, methods, or interfaces that SQL Server’s SQLCLR hosting environment cannot bind to because it requires concrete, non-generic type definitions for objects like UDTs, UDFs, or stored procedures. It can also surface when an assembly is corrupted during deployment or when metadata in sys.assembly_types references a stale or mismatched type signature.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Type

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to locate CLR-based objects tied to generic types:
  SELECT a.name AS assembly_name, t.name AS type_name
  FROM sys.assembly_types t
  JOIN sys.assemblies a ON t.assembly_id = a.assembly_id;
  • Cross-reference the %ls placeholder from the error message with the type_name output to pinpoint the exact generic type causing the failure.

Step 2: Remove and Rebuild the CLR Assembly

  • Drop the problematic assembly and any dependent objects (UDTs, functions, procedures) using:
  DROP ASSEMBLY [YourAssemblyName] WITH NO DEPENDENTS;
  • In Visual Studio (2022 or later, targeting .NET 8/9 compatible with SQL Server 2025 CLR hosting), locate the source project and refactor any generic class/method declarations (e.g., public class MyType<T>) into closed, non-generic equivalents.
  • Recompile the DLL and verify no Generic<T> signatures remain in the public API surface exposed to SQL Server.

Step 3: Re-register the Assembly with Correct Permission Set

  • Re-deploy the corrected assembly using:
  CREATE ASSEMBLY [YourAssemblyName]
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Ensure clr strict security is properly configured via sp_configure and that the assembly is signed/trusted if running under PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE.
  • Re-create any dependent UDTs or functions that reference the assembly’s types.

Step 4: Validate .NET Runtime Compatibility

  • Confirm that the Windows Server 2025 / Windows 11 host has the correct .NET CLR version installed that SQL Server 2025 expects (check via SELECT SERVERPROPERTY('BuildClrVersion')).
  • Update or reinstall the .NET runtime components under Control Panel > Programs > Programs and Features if version mismatches are found, then restart the SQL Server service.

Alternative or Verification Steps

  • Verify the fix by re-running the original operation (e.g., CREATE TYPE, CREATE FUNCTION) that triggered Error 6542 and confirm it completes without exception.
  • If the error persists, run DBCC CHECKDB on the affected database to rule out metadata corruption, and consider using sp_refresh_parameter_encryption or redeploying the assembly from a clean DACPAC export as a fallback.

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

Troubleshooting Guide: Error 6539 – Invalid Serialization Format (Format.Unknown)

Why This Error Happens

Error 6539 occurs when SQL Server encounters a CLR (Common Language Runtime) user-defined type (UDT) or user-defined aggregate whose serialization metadata has become corrupted, mismatched, or was improperly registered during an assembly deployment. This typically happens after an in-place upgrade, a restored database from an incompatible SQL Server version, or when the assembly DLL on disk does not match the version cataloged in sys.assembly_files. It can also surface when the Format.Native or Format.UserDefined attribute on the type’s SqlUserDefinedType declaration is missing or was altered after compilation, leaving the engine unable to determine how to serialize/deserialize the object.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Type and Assembly

  • Run the following query to extract the exact type and schema from the error message:
SELECT t.name AS TypeName, a.name AS AssemblyName, t.is_binary_ordered
FROM sys.types t
JOIN sys.assemblies a ON t.assembly_id = a.assembly_id;
  • Cross-reference the %.*ls.%.*ls placeholders in the error log (found in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) against this result set.
  • Confirm whether the type is a system CLR type or a custom deployed assembly.

Step 2: Re-register the CLR Assembly

  • Drop the corrupted assembly binding using:
DROP TYPE IF EXISTS [SchemaName].[TypeName];
DROP ASSEMBLY [AssemblyName];
  • Re-deploy the original .dll file using CREATE ASSEMBLY with the WITH PERMISSION_SET = SAFE clause.
  • Ensure the DLL version on disk (usually under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\) matches the compiled version used during the original database build.

Step 3: Validate Database Compatibility Level

  • Check the current compatibility level, as Format.Unknown often appears when a database is left at a legacy compatibility level after migrating to SQL Server 2025:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Update it to the correct level for SQL Server 2025 (170 or higher) if it has not been upgraded:
ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;

Step 4: Rebuild Corrupted System Metadata (If Required)

  • If the error persists on system tables rather than custom types, run DBCC CHECKDB with the data purity check enabled:
DBCC CHECKDB ('YourDatabaseName') WITH DATA_PURITY, ALL_ERRORMSGS;
  • Review the output for allocation or metadata corruption flags tied to the serialized type pages.
  • If corruption is confirmed, restore the affected database from the last known good backup rather than attempting a repair, as REPAIR_ALLOW_DATA_LOSS does not resolve CLR serialization metadata issues.

Alternative or Verification Steps

  • After re-registering the assembly, verify the fix by executing a SELECT or INSERT statement against a table using the affected UDT column; a successful read/write with no 6539 error confirms resolution.
  • If the error reoccurs intermittently, enable Trace Flag 902 at SQL Server startup (via SQL Server Configuration Manager) to bypass version-check validation on legacy CLR types while you plan a permanent assembly migration.

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

Troubleshooting Guide: SQL Server Error 6540

Why This Error Happens

This error occurs when attempting to register a CLR (Common Language Runtime) assembly in SQL Server using a name that is reserved by one of SQL Server’s built-in system assemblies, such as Microsoft.SqlServer.Types, System, Microsoft.VisualBasic, or mscorlib. SQL Server protects these system assembly names to prevent naming collisions that could corrupt internal CLR integration functionality. This typically happens when a developer or deployment script inadvertently names a custom assembly identically to a system reserved name, or when a third-party library bundles a dependency that conflicts with these protected names.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Assembly Name

  • Review the full error message text in SQL Server Management Studio (SSMS) or the SQL Server Error Log to capture the exact assembly name flagged in the %.*ls placeholder.
  • Run the following query to check existing system assemblies and compare names:
SELECT name, is_user_defined FROM sys.assemblies WHERE is_user_defined = 0;
  • Confirm whether your deployment script or CREATE ASSEMBLY statement uses this exact reserved name.

Step 2: Rename the Custom Assembly

  • Open the Visual Studio project or source DLL metadata and rename the assembly to something unique, such as prefixing it with your company or project name (e.g., MyCompany.CustomTypes instead of Microsoft.SqlServer.Types).
  • Rebuild the .dll file to ensure the new assembly name is embedded in the file manifest.
  • Update any CREATE ASSEMBLY or ALTER ASSEMBLY T-SQL scripts to reference the new name:
CREATE ASSEMBLY MyCompany_CustomTypes
FROM 'C:\SQLAssemblies\MyCompany.CustomTypes.dll'
WITH PERMISSION_SET = SAFE;

Step 3: Clear Cached Deployment Artifacts

  • If deploying via SQL Server Data Tools (SSDT) or a .dacpac file, delete the old build output folder (typically bin\Debug or bin\Release) to remove stale assembly references.
  • Re-publish the database project in Visual Studio or redeploy the .dacpac using SqlPackage.exe to ensure the corrected assembly name is used.

Step 4: Validate CLR Integration Settings

  • Confirm CLR integration is properly enabled on the instance using:
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
  • On Windows Server 2025 instances using CLR strict security, verify the assembly is signed or added to the trusted assemblies list via sys.sp_add_trusted_assembly.

Alternative or Verification Steps

  • After renaming and redeploying, run SELECT name FROM sys.assemblies; to confirm the new assembly name appears without triggering Error 6540.
  • If the error persists despite renaming, check for cached builds in the Global Assembly Cache (GAC) on the Windows Server 2025 host by running gacutil /l and removing any duplicate-named entries with gacutil /u <AssemblyName>.

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

Troubleshooting Guide: SQL Server Error 6537 — “The .NET Framework Common Language Runtime Was Shut Down by User Code”

Why This Error Happens

This error occurs when a SQLCLR (SQL Common Language Runtime) integration — such as a CLR stored procedure, trigger, or function — calls Environment.FailFast() or encounters an unhandled critical exception that forces the AppDomain to terminate abruptly. This is often triggered by corrupted CLR assemblies, outdated .NET Framework dependencies conflicting with SQL Server 2025’s updated CLR host, or custom assembly code that intentionally terminates the runtime after detecting an unrecoverable state. In rare cases, it stems from insufficient TRUSTWORTHY or permission set configurations (SAFE, EXTERNAL_ACCESS, UNSAFE) assigned to the assembly on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly

  • Check the SQL Server Error Log (Management Studio > Management > SQL Server Logs) for the exact assembly name tied to Error 6537.
  • Run the query: SELECT * FROM sys.assemblies WHERE is_user_defined = 1; to list all custom CLR assemblies.
  • Cross-reference the timestamp of the error with recent deployment or update logs for that assembly.

Step 2: Validate and Repair CLR Permission Sets

  • Open a query window and run: sp_configure 'clr enabled', 1; RECONFIGURE; to confirm CLR integration is active.
  • Verify the assembly’s permission level using: SELECT name, permission_set_desc FROM sys.assemblies;
  • If the assembly requires external resources (file I/O, network calls), ensure it is set to EXTERNAL_ACCESS or UNSAFE rather than SAFE, and confirm the database has TRUSTWORTHY ON only if absolutely necessary.

Step 3: Re-register or Replace the Corrupted Assembly

  • Drop the faulty assembly using: DROP ASSEMBLY [YourAssemblyName];
  • Recompile the source DLL against the correct .NET Framework version compatible with SQL Server 2025 (ensure target framework matches the CLR host version, typically .NET Framework 4.8.1 or later).
  • Re-import the assembly with: CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\Path\To\Assembly.dll' WITH PERMISSION_SET = SAFE;

Step 4: Apply Windows Server 2025 and SQL Server Patches

  • Navigate to Windows Update > Advanced Options and install all pending .NET Framework and Cumulative Updates (CU) for SQL Server 2025.
  • Restart the SQL Server service via services.msc (locate “SQL Server (MSSQLSERVER)”) after patching to flush any cached CLR host states.

Step 5: Restart the SQL Server CLR Host

  • Restart the entire SQL Server instance to force a clean reload of the CLR AppDomain.
  • Monitor the SQL Server Error Log immediately after restart for any recurrence of Error 6537 during the next assembly invocation.

Alternative or Verification Steps

  • Execute the stored procedure or function that previously failed and confirm no AppDomain unload messages appear in the Error Log; a clean execution with returned data confirms resolution.
  • If the error persists, isolate the assembly in a sandboxed .NET console test harness outside SQL Server to catch the specific unhandled exception before re-deploying it as a CLR object.

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

Troubleshooting Guide: SQL Server Error 6538 – .NET Framework Stack Overflow

Why This Error Happens

This error occurs when a SQLCLR (SQL Common Language Runtime) integration object—such as a user-defined function, stored procedure, or trigger—exceeds the thread stack size allocated by SQL Server’s hosting environment. This is typically caused by uncontrolled recursion in managed code, overly complex object graphs being serialized/deserialized, or large local variables (such as big arrays or structs) being allocated on the stack within a CLR routine. Because SQL Server imposes a much smaller stack size per thread (to support high concurrency) compared to a standalone .NET application, code that runs fine outside SQL Server can overflow the stack when executed as a CLR integration object inside SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Object

  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full text of Error 6538, which includes the assembly and method name (%.*ls placeholder).
  • Run the following query to list all CLR assemblies currently loaded and their associated modules:
SELECT a.name, m.assembly_class, m.assembly_method 
FROM sys.assembly_modules m 
JOIN sys.assemblies a ON m.assembly_id = a.assembly_id;
  • Cross-reference the method name from the error log with your deployed assembly source code to pinpoint the recursive or stack-heavy function.

Step 2: Refactor the Managed Code to Reduce Stack Usage

  • Open the source project in Visual Studio 2025 and locate the flagged method.
  • Convert deep or unbounded recursive calls into iterative loops using an explicit Stack<T> or Queue<T> collection instead of native call-stack recursion.
  • Reduce the size of stack-allocated structures (avoid large struct arrays or stackalloc blocks); move large data to heap-allocated objects (e.g., List<T> or byte[] via new).
  • Rebuild the assembly (.dll) and re-sign it if it uses strict security permissions.

Step 3: Redeploy the Assembly with Updated Permission Set

  • Drop and re-register the updated assembly in SQL Server:
ALTER ASSEMBLY YourAssemblyName 
FROM 'C:\Deploy\YourAssembly.dll' 
WITH PERMISSION_SET = SAFE;
  • Ensure clr strict security is correctly configured in sp_configure for SQL Server 2025, and that the assembly is signed with a certificate or asymmetric key mapped to a login with UNSAFE ASSEMBLY permission if elevated trust is required.
  • Restart the SQL Server service via services.msc or PowerShell:
Restart-Service -Name MSSQLSERVER -Force

Step 4: Adjust Workload or Isolate High-Risk Procedures

  • If recursion depth is data-dependent and cannot be fully eliminated, add an explicit recursion-depth counter in code that throws a controlled SqlException before approaching the stack limit (typically before 100-150 nested calls, depending on frame size).
  • Consider isolating heavy CLR workloads into an external .NET service (via Service Broker or an API call) rather than executing them in-process within SQL Server.

Alternative or Verification Steps

  • Re-run the original query or application workload that triggered Error 6538 and confirm no new entries appear in the SQL Server error log; monitor using sys.dm_os_ring_buffers for any CLR-related exceptions.
  • If the error persists despite code changes, use WinDbg with the SOS debugging extension (!clrstack) attached to the sqlservr.exe process to capture a live stack trace during execution and confirm the exact recursive call pattern or allocation causing the overflow.

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

Troubleshooting Guide: SQL Server Error 6535 — AppDomain Unloaded Due to Conflicting Query

Why This Error Happens

This error occurs when SQL CLR (Common Language Runtime) integration terminates an AppDomain because another concurrent query triggered a resource conflict, memory pressure event, or unhandled exception within the same AppDomain. SQL Server isolates CLR assemblies inside AppDomains per database, so when one query forces an unload (due to timeout, fatal error, or excessive memory consumption), all other sessions sharing that AppDomain have their .NET execution aborted mid-transaction. This is often a symptom of poorly optimized CLR stored procedures, assembly instability, or insufficient memory allocation for the CLR host environment on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Assembly

  • Check the SQL Server Error Log and Windows Event Viewer (Application Log) for the full text of Error 6535, which usually names the specific assembly or database involved.
  • Run the following query to correlate recent CLR activity:
  SELECT * FROM sys.dm_clr_appdomains;
  SELECT * FROM sys.dm_os_memory_clerks WHERE type = 'MEMORYCLERK_SQLCLR';
  • Review sys.dm_exec_requests for any long-running or resource-intensive queries executing CLR functions at the time of the error.

Step 2: Review and Patch the CLR Assembly Code

  • Open the source project for the implicated assembly (commonly found under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ references or your deployment solution).
  • Look for unbounded loops, missing try/catch blocks, or unthrown exceptions that could cause runaway memory use.
  • Rebuild the assembly targeting .NET Framework compatibility mode supported by SQL Server 2025, then redeploy using:
  ALTER ASSEMBLY YourAssemblyName
  FROM 'C:\Deploy\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;

Step 3: Adjust SQL Server Memory and CLR Configuration

  • Open SQL Server Management Studio (SSMS) and navigate to Server Properties > Memory.
  • Ensure “Max Server Memory” is not set too restrictively, as this can starve the CLR host and force AppDomain unloads under load.
  • Enable CLR integration explicitly if disabled, via:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Restart the SQL Server service (services.msc on Windows Server 2025) to apply configuration changes cleanly.

Step 4: Isolate High-Risk CLR Objects

  • If multiple databases share a common assembly, consider isolating CLR routines into a dedicated database to prevent cross-query AppDomain contention.
  • Use WITH PERMISSION_SET = SAFE wherever possible instead of UNSAFE or EXTERNAL_ACCESS to reduce the chance of destabilizing shared AppDomains.

Alternative or Verification Steps

  • Re-run the previously failing workload under a SQL Server Profiler trace or Extended Events session filtered on clr_virtual_machine_errors to confirm the AppDomain no longer unloads unexpectedly.
  • If the error persists, as a temporary workaround, disable CLR strict security (sp_configure 'clr strict security', 0;) only in a controlled test environment to determine if security policy enforcement is contributing to the instability, then re-enable it once root cause is resolved.

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

Troubleshooting Guide: SQL Server Error 6536 — Fatal CLR Error

Why This Error Happens

Error 6536 occurs when the .NET Framework Common Language Runtime (CLR) hosted inside SQL Server 2025 encounters an unrecoverable fault, forcing SQL Server to shut down to protect data integrity. This is typically caused by a corrupted or outdated .NET runtime installation, memory corruption triggered by a faulty SQLCLR assembly (custom stored procedures, functions, or triggers), or resource exhaustion (such as thread pool starvation or virtual memory fragmentation) on the host OS. It can also surface after incomplete Windows updates that leave CLR binaries mismatched with the version SQL Server expects.

Step-by-Step Resolution Guide

Step 1: Review SQL Server Error Logs and Windows Event Viewer

  • Open SQL Server Management Studio (SSMS) and check SQL Server Logs under Management for the exact timestamp of Error 6536.
  • Cross-reference with Windows Event Viewer (eventvwr.msc) under Application and System logs for correlating .NET Runtime or SQLDUMPER entries.
  • Locate the generated SQL Server memory dump file, usually found in:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\LOG\SQLDump*.mdmp
  • Note any referenced assembly names or module paths in the log for Step 2.

Step 2: Repair or Reinstall the .NET Framework / CLR Components

  • Run sfc /scannow from an elevated Command Prompt to repair corrupted system files.
  • Use the Windows Features dialog (optionalfeatures.exe) to disable and re-enable .NET Framework 4.8/4.8.1 Advanced Services.
  • Alternatively, run the .NET Repair Tool from Microsoft’s official download page to fix runtime inconsistencies.
  • Reboot the server after repair completes, then restart the SQL Server (MSSQLSERVER) service via services.msc.

Step 3: Audit and Disable Problematic SQLCLR Assemblies

  • Run the following query to list all CLR assemblies currently loaded in your databases:
  SELECT * FROM sys.assemblies WHERE is_user_defined = 1;
  • If a specific assembly correlates with the crash timestamp, disable CLR integration temporarily to isolate the cause:
  EXEC sp_configure 'clr enabled', 0;
  RECONFIGURE;
  • Drop or update the faulty assembly using DROP ASSEMBLY [AssemblyName]; once identified, then re-enable CLR integration.

Step 4: Check for Resource Exhaustion and Memory Pressure

  • Open Task Manager or Performance Monitor (perfmon.exe) and monitor SQLServr.exe for excessive memory/page file usage.
  • Verify that Max Server Memory in SQL Server is configured correctly (right-click server in SSMS → Properties → Memory) to leave adequate headroom for the OS and CLR threads.
  • Increase the Windows page file size temporarily (Control Panel → System → Advanced System Settings → Performance Settings → Advanced → Virtual Memory) if memory starvation is suspected.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Verify current build version with:
  SELECT @@VERSION;
  • Restart the SQL Server service and confirm the build number matches the latest CU release notes.

Alternative or Verification Steps

  • After applying fixes, restart SQL Server and monitor the error log for 24–48 hours using xp_readerrorlog to confirm Error 6536 does not recur.
  • If the issue persists, isolate the workload by running SQLCLR-dependent objects in a test/staging instance with CLR strict security enabled (sp_configure 'clr strict security', 1;) to catch unsafe assembly permissions before they impact production.

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

Troubleshooting Guide: SQL Server Error 6533 (AppDomain Unloaded Due to Memory Pressure)

Why This Error Happens

This error occurs when SQL Server’s CLR (Common Language Runtime) integration runs out of memory while executing a .NET assembly, triggering the escalation policy to forcibly unload the AppDomain to protect server stability. This is typically caused by excessive memory consumption from CLR-based stored procedures, functions, or triggers, often combined with insufficient memory allocation to SQL Server or competing memory pressure from other processes on the Windows Server 2025 host. In some cases, memory fragmentation within the CLR heap or a memory leak in custom assembly code can also trigger this escalation even when overall system memory appears sufficient.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Configuration

  • Open SQL Server Management Studio (SSMS) and run EXEC sp_configure 'max server memory' to check current allocation.
  • Ensure “max server memory” leaves adequate headroom for the OS (typically reserve 4-8 GB for Windows Server 2025 itself).
  • Check Windows Task Manager or Performance Monitor (perfmon.exe) for overall system memory pressure during the error timeframe.

Step 2: Review and Isolate the Offending CLR Assembly

  • Query sys.dm_clr_loaded_assemblies and sys.dm_clr_appdomains to identify which AppDomain and assembly triggered the unload.
  • Check SQL Server error logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the specific assembly name referenced in the %.*ls placeholders.
  • Review the custom .NET code for unmanaged memory leaks, large object allocations, or missing Dispose() calls on IDisposable objects.

Step 3: Adjust SQL Server Memory and CLR Settings

  • Increase “max server memory” via: EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'max server memory', <value_in_MB>; RECONFIGURE;
  • Enable “clr strict security” validation by confirming assemblies are signed and trusted: EXEC sp_configure 'clr strict security', 1; RECONFIGURE;
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER to apply changes.

Step 4: Patch or Update the CLR Assembly

  • Recompile the assembly targeting the latest .NET runtime compatible with SQL Server 2025.
  • Redeploy using CREATE ASSEMBLY with the WITH PERMISSION_SET = SAFE clause unless EXTERNAL_ACCESS is explicitly required.
  • Test the assembly under load using SQL Server Profiler or Extended Events to monitor memory consumption patterns.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Run the installer with administrative privileges and follow the setup wizard to patch known CLR memory management bugs.
  • Reboot the Windows Server 2025 instance if prompted post-installation.

Alternative or Verification Steps

  • To verify the fix, re-run the workload that previously triggered the error and monitor sys.dm_os_memory_clerks for the MEMORYCLERK_SQLCLR clerk to confirm memory usage remains stable.
  • If the error persists, consider disabling CLR integration entirely as a temporary workaround via EXEC sp_configure 'clr enabled', 0; RECONFIGURE; while a permanent code fix is developed.

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

Troubleshooting Guide: Error 6534 – AppDomain Unloaded by Escalation Policy

Why This Error Happens

This error occurs when SQL Server’s CLR integration detects that a managed lock (such as a Monitor or Mutex held within a SQLCLR assembly) was not released properly before the hosting AppDomain was torn down. SQL Server’s reliability escalation policy treats this as a potential threat to transactional and memory consistency, forcing an unload of the entire AppDomain to prevent deadlocks or corruption. This is typically caused by poorly written CLR stored procedures/triggers that use lock() statements, Monitor.Enter(), or threading primitives without a guaranteed finally block to release them, especially when an exception or thread abort interrupts execution mid-lock.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly

  • Check the SQL Server Error Log (Management > SQL Server Logs in SSMS) for the full text of the 6534 message, which names the specific AppDomain and database.
  • Cross-reference the AppDomain ID with sys.dm_clr_appdomains to identify which database and assembly triggered the unload.
  • Run the following query to pinpoint active CLR assemblies in the suspect database:
  SELECT * FROM sys.dm_clr_appdomains WHERE appdomain_name LIKE '%YourDBName%';

Step 2: Audit and Patch the Source Code

  • Locate the .cs or .vb source files for the SQLCLR object (Stored Procedure, Trigger, or UDT) identified in Step 1.
  • Search for instances of Monitor.Enter, lock (object), Mutex, or ReaderWriterLockSlim within the code.
  • Ensure every lock acquisition is wrapped in a try...finally block where Monitor.Exit() or the dispose method is called unconditionally, even if an exception occurs.
  • Recompile the assembly into a new .dll file using Visual Studio or csc.exe.

Step 3: Redeploy the Corrected Assembly

  • Connect to the instance via SSMS and alter the existing assembly to point to the fixed binary:
  ALTER ASSEMBLY YourAssemblyName 
  FROM 'C:\Deployments\YourAssembly_Fixed.dll';
  • If the assembly is locked due to active sessions, you may need to restart the specific database (not the whole instance) to clear the hung AppDomain:
  ALTER DATABASE YourDBName SET OFFLINE WITH ROLLBACK IMMEDIATE;
  ALTER DATABASE YourDBName SET ONLINE;

Step 4: Review CLR Strict Security Settings

  • In SQL Server 2025, verify that clr strict security is enabled (default) to ensure the assembly is signed and trusted, which prevents partially trusted code from causing erratic threading behavior.
  • Run this command to check current configuration:
  EXEC sp_configure 'clr strict security';
  • If the assembly is unsigned, create an asymmetric key and a corresponding login with UNSAFE ASSEMBLY permissions rather than disabling strict security globally.

Alternative or Verification Steps

  • Verify the Fix: Run a load test against the specific stored procedure that triggered the error. Monitor sys.dm_clr_appdomains during the test to ensure the state remains stable (not showing “Unloading”) after the procedure completes execution multiple times in a row.
  • Alternative Workaround: If recompiling the source code is not immediately possible, consider migrating the specific logic out of SQLCLR and into a native T-SQL stored procedure or an external microservice called via sp_invoke_external_rest_endpoint, removing the dependency on the CLR threading model entirely.

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

Troubleshooting Guide: SQL Server Error 6531 — CLR Trigger Parameter Mismatch

Why This Error Happens

This error occurs because SQL Server’s CLR trigger implementation strictly requires the target method to have zero parameters, since triggers are invoked internally by the Database Engine without any argument-passing mechanism. When a developer defines a CLR method tied to a trigger but includes one or more parameters in the method signature, the assembly binding validation fails at creation time. This is almost always a code-level mismatch between the managed assembly and the CREATE TRIGGER statement referencing it, rather than a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Method in the Assembly

  • Open the Visual Studio (or VS Code with C# Dev Kit) project that generated the DLL referenced by the assembly.
  • Search for the method name shown in the error message (the %ls placeholder for function name).
  • Confirm whether the method signature includes parameters, e.g. public static void MyTrigger(int orderId).

Step 2: Modify the Method Signature to Accept No Parameters

  • Change the method definition to a parameterless void method, e.g. public static void MyTrigger().
  • If the method needs contextual data (such as inserted/deleted rows), use SqlContext.TriggerContext inside the method body instead of passing parameters:
public static void MyTrigger()
{
    SqlTriggerContext tContext = SqlContext.TriggerContext;
    // Access tContext.TriggerAction, columns, etc.
}
  • Rebuild the project to generate an updated DLL.

Step 3: Redeploy the Assembly to SQL Server

  • Drop the existing assembly if it is already registered:
DROP TRIGGER IF EXISTS dbo.MyCLRTrigger;
DROP ASSEMBLY IF EXISTS MyAssemblyName;
  • Re-import the corrected DLL:
CREATE ASSEMBLY MyAssemblyName
FROM 'C:\SQLAssemblies\MyAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • Ensure the file path is accessible to the SQL Server service account on Windows Server 2025 (check NTFS permissions on the C:\SQLAssemblies\ folder).

Step 4: Recreate the CLR Trigger

  • Re-issue the CREATE TRIGGER statement pointing to the corrected, parameterless method:
CREATE TRIGGER trg_MyCLRTrigger
ON dbo.MyTable
AFTER INSERT, UPDATE
AS EXTERNAL NAME MyAssemblyName.TriggerClass.MyTrigger;
  • Confirm no syntax errors are returned and the trigger object appears in sys.triggers.

Step 5: Validate CLR Integration Settings

  • Run sp_configure 'clr enabled' to confirm CLR integration is turned on (value should be 1).
  • If disabled, enable it:
EXEC sp_configure 'clr strict security', 1;
RECONFIGURE;

Alternative or Verification Steps

  • Test the trigger by performing an INSERT/UPDATE/DELETE operation on the target table and confirm no Error 6531 is raised in SQL Server Management Studio’s Messages pane.
  • If the error persists, use SELECT * FROM sys.assembly_modules to verify the assembly-to-method binding matches the corrected parameterless signature, and check Windows Event Viewer (Application log) on Windows Server 2025 for any additional CLR loading exceptions.

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

Troubleshooting Guide: SQL Server Error 6532 — CLR Out of Memory Escalation

Why This Error Happens

Error 6532 occurs when the SQL Server CLR (Common Language Runtime) host environment runs out of memory while executing a .NET Framework assembly, triggering SQL Server’s internal escalation policy to forcibly abort the process to protect the Database Engine. This is typically caused by memory pressure from the max server memory setting being too restrictive, poorly optimized CLR integration code (such as unmanaged memory leaks in SQLCLR assemblies), or excessive multi-AppDomain usage consuming the CLR virtual address space. On Windows Server 2025 and Windows 11 hosts, this can also be exacerbated by other memory-intensive services competing for system RAM alongside the SQL Server instance.

Step-by-Step Resolution Guide

Step 1: Review and Adjust SQL Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Right-click the server instance, select Properties > Memory, and verify the Maximum server memory (MB) value is not set too low relative to available physical RAM.
  • Alternatively, run the following T-SQL to check current settings:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max server memory';
  • Increase the value if it is constraining the CLR’s memory allocation needs, leaving at least 2-4 GB for the OS on Windows Server 2025.

Step 2: Identify and Isolate the Problematic CLR Assembly

  • Query sys.dm_clr_loaded_assemblies and sys.dm_os_memory_clerks (filter on %CLR%) to identify which assembly or AppDomain is consuming excessive memory.
  SELECT * FROM sys.dm_os_memory_clerks WHERE type LIKE '%CLR%';
  • Review the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the specific assembly name referenced alongside Error 6532.
  • Update or recompile the offending SQLCLR assembly to fix unmanaged resource leaks (e.g., ensure IDisposable objects are properly disposed and connections/streams are closed).

Step 3: Enable CLR Strict Security and Validate AppDomain Usage

  • Confirm clr strict security is enabled (default in SQL Server 2017+) to ensure assemblies run with proper permission sets:
  EXEC sp_configure 'clr strict security', 1;
  RECONFIGURE;
  • Reduce the number of distinct AppDomains by consolidating assemblies under the same owner and permission set, since each unique combination spawns a new AppDomain consuming additional memory.
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear any lingering CLR memory fragmentation.

Step 4: Monitor System-Level Memory Pressure

  • Use Performance Monitor (PerfMon) on Windows Server 2025 to track SQLServer:Memory Manager\Total Server Memory and Process\Private Bytes for sqlservr.exe.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for correlating out-of-memory warnings at the OS level.

Alternative or Verification Steps

  • After applying fixes, re-run the CLR-dependent stored procedures or functions and confirm no Error 6532 entries appear in the ERRORLOG for at least one full business cycle.
  • If the issue persists, consider disabling CLR integration temporarily (EXEC sp_configure 'clr enabled', 0; RECONFIGURE;) and migrating the logic to a native T-SQL or external service to permanently eliminate CLR memory contention.

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

Troubleshooting Guide: Error 6529 – ALTER ASSEMBLY Failed Due to Identity Mismatch

Why This Error Happens

This error occurs when the .NET assembly file (.dll) referenced by your ALTER ASSEMBLY statement has been recompiled or modified since it was first registered in SQL Server 2025, causing a mismatch in its strong-name identity (version, culture, or public key token). SQL Server performs a strict identity check using the assembly’s metadata, and even a minor recompilation without an explicit version change can alter the internal MVID (Module Version ID), triggering this conflict. This is frequently seen after a developer rebuilds a CLR assembly project in Visual Studio without updating the AssemblyVersion attribute, while the database still expects the original binary signature.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly Identity Mismatch

  • Open SQL Server Management Studio (SSMS) and run a query against sys.assemblies to check the clr_name and current version hash.
  • Compare this against the actual file properties of the .dll on disk (right-click the file in Windows 11/Server 2025 File Explorer > Properties > Details tab) to confirm a version discrepancy exists.

Step 2: Drop and Re-Create the Assembly (Rather Than Alter)

  • Since ALTER ASSEMBLY fails on identity changes, you must remove the old reference entirely first.
  • Execute DROP ASSEMBLY [YourAssemblyName]; in a query window (ensure no dependent objects like Stored Procedures are blocking this).
  • Re-import the new binary using CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\Path\To\New\Assembly.dll' WITH PERMISSION_SET = SAFE;.

Step 3: Synchronize Version Numbers in Visual Studio

  • Open the AssemblyInfo.cs file in your Visual Studio project.
  • Manually increment the [assembly: AssemblyVersion("1.0.0.0")] tag to match a new build number before recompiling.
  • Rebuild the solution to ensure the output .dll in the bin/Debug or bin/Release folder has a fresh, consistent GUID that matches your intended deployment.

Step 4: Clear Visual Studio and SQL Server Caches

  • On the Windows Server 2025 host, stop the SQL Server service via services.msc.
  • Navigate to the project’s obj and bin folders and delete them to force a clean rebuild, preventing “stale” DLLs from being accidentally deployed.
  • Restart the SQL Server service and attempt the assembly import again.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM sys.assembly_files; to confirm the content hash length matches the new file size, and test the stored procedures that rely on this assembly to ensure they execute without throwing a “CLR object does not exist” error.
  • Alternative: If dropping the assembly is blocked by dependencies, use ALTER ASSEMBLY ... WITH UNCHECKED DATA to bypass dependency checks temporarily, though this should only be used in a development environment due to potential data integrity risks in production.

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

Troubleshooting Guide: SQL Server Error 6530 – “Cannot Perform Alter on Incompatible Object Type”

Why This Error Happens

Error 6530 occurs when a T-SQL ALTER statement is executed against a database object using the wrong syntax context, such as attempting to ALTER TABLE on a view, synonym, or system object that does not support that DDL operation. This is typically a code-level issue rather than a server configuration fault, often arising from deployment scripts that reference the wrong object name, naming collisions between a table and a view, or stale metadata in the system catalog after a botched schema migration. In rarer cases, metadata corruption in sys.objects on SQL Server 2025 can cause the engine to misidentify an object’s type, triggering this error even when the syntax is technically correct.

Step-by-Step Resolution Guide

Step 1: Identify the Actual Object Type

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to the affected instance.
  • Run the following query to confirm what the object actually is:
  SELECT name, type, type_desc 
  FROM sys.objects 
  WHERE name = 'YourObjectName';
  • Check the type_desc column — if it returns VIEW but your script uses ALTER TABLE, this confirms a syntax/object mismatch.

Step 2: Correct the DDL Statement to Match the Object Type

  • If the object is a VIEW, change your script to use ALTER VIEW instead of ALTER TABLE.
  • If the object is a SYNONYM, remember synonyms cannot be altered — drop and recreate using:
  DROP SYNONYM dbo.YourSynonym;
  CREATE SYNONYM dbo.YourSynonym FOR dbo.TargetObject;
  • For system or service broker objects (e.g., QUEUE, TYPE), consult the specific ALTER syntax required for that object class in SQL Server 2025 Books Online.

Step 3: Check for Naming Conflicts in the Schema

  • Run this query to check if multiple object types share the same name in different schemas:
  SELECT s.name AS SchemaName, o.name, o.type_desc 
  FROM sys.objects o
  JOIN sys.schemas s ON o.schema_id = s.schema_id
  WHERE o.name = 'YourObjectName';
  • If duplicates exist across schemas (e.g., dbo.Customers as a table and sales.Customers as a view), explicitly qualify the schema name in your ALTER statement to avoid resolution ambiguity.

Step 4: Rebuild System Metadata Cache (If Corruption Is Suspected)

  • Clear the procedure cache to rule out stale execution plans referencing an outdated object type:
  DBCC FREEPROCCACHE;
  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to check for catalog corruption.
  • If corruption is confirmed, restore the affected database from the last known good backup rather than attempting an in-place repair on system tables.

Step 5: Validate Permissions and Re-run the Script

  • Ensure the executing login has ALTER permission on the schema (not just the object), since SQL Server 2025 enforces stricter schema-level checks:
  GRANT ALTER ON SCHEMA::dbo TO [YourLoginName];
  • Re-run the corrected ALTER statement in a test environment before deploying to production.

Alternative or Verification Steps

  • Verify the fix by re-running the original failing script in a non-production database copy and confirming it completes with Command(s) completed successfully instead of Error 6530.
  • As an alternative, use sp_help 'YourObjectName' to get a full metadata report (including type, columns, and dependencies) if sys.objects queries are inconclusive or you suspect deeper catalog inconsistency.

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

Troubleshooting Guide: SQL Server Error 6527 — “.NET Framework Runtime Has Been Stopped”

Why This Error Happens

This error typically occurs when SQL Server’s CLR (Common Language Runtime) integration encounters a corrupted or mismatched .NET Framework assembly, often triggered by an incomplete Windows Update or a conflicting side-by-side .NET installation. It can also result from insufficient permissions on the SQL Server service account to access CLR-hosted assemblies, or from the clr enabled configuration being improperly toggled during a failed patch cycle. In some cases, a corrupted mscorwks.dll or clr.dll reference within the SQL Server instance causes the runtime host to forcibly halt execution to prevent instance instability.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Status

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check CLR status:
  sp_configure 'clr enabled';
  • If the run_value is 0, CLR integration is disabled; proceed to re-enable it in Step 2.

Step 2: Re-enable and Reconfigure CLR

  • Execute the following commands in a new query window:
  sp_configure 'show advanced options', 1;
  RECONFIGURE;
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Restart the SQL Server service via SQL Server Configuration Manager (not just the Services app) to ensure the CLR host reinitializes cleanly.

Step 3: Repair the .NET Framework Installation

  • Navigate to Control Panel > Programs > Programs and Features.
  • Select Microsoft .NET Framework 4.8.1 (or the version listed) and choose Repair rather than Uninstall.
  • On Windows Server 2025 / Windows 11, also run:
  DISM /Online /Cleanup-Image /RestoreHealth
  sfc /scannow
  • Reboot the server after the repair completes.

Step 4: Validate SQL Server Service Account Permissions

  • Open services.msc and confirm the account running MSSQLSERVER (or named instance) has local permissions to:
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
  • The SQL Server binaries directory (typically C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Binn\)
  • Grant Read & Execute permissions if missing, then restart the SQL Server service.

Step 5: Rebuild Corrupted CLR Assemblies (If Applicable)

  • If a custom CLR assembly caused the crash, identify it using:
  SELECT * FROM sys.assemblies WHERE is_user_defined = 1;
  • Drop and re-deploy the assembly:
  DROP ASSEMBLY [YourAssemblyName];
  • Redeploy the assembly from a verified, uncorrupted .dll source file.

Alternative or Verification Steps

  • To verify the fix, check the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for the absence of Error 6527 after a service restart, and confirm CLR functions execute successfully by running a test CLR stored procedure.
  • If the issue persists, consider performing an in-place repair of the SQL Server 2025 instance using the original setup media (Setup.exe /ACTION=REPAIR), which resets core engine files without affecting databases.

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

Troubleshooting Guide: SQL Server Error 6528 – Assembly Not Found in SQL Catalog

Why This Error Happens

Error 6528 occurs when SQL Server attempts to execute a CLR (Common Language Runtime) object—such as a stored procedure, function, or trigger—that references an assembly which no longer exists in the sys.assemblies catalog of the target database. This typically happens because the assembly was dropped manually, the database was restored from a backup that predates the assembly registration, or metadata became desynchronized during a database migration or replication process. In some cases, this also occurs when a user attempts to call a CLR object across database contexts where the assembly was never registered in the current database scope.

Step-by-Step Resolution Guide

Step 1: Identify the Missing Assembly and Affected Object

  • Run the following query to capture the exact error context from SQL Server logs:
  EXEC sp_readerrorlog 0, 1, 'Assembly';
  • Note the exact assembly name and database name reported in the error text (%.*ls placeholders will be populated with real values here).
  • Cross-reference the object (procedure/function/trigger) that triggered the call using:
  SELECT * FROM sys.objects WHERE type IN ('PC', 'FN', 'TR');

Step 2: Verify Assembly Registration in the Catalog

  • Check whether the assembly actually exists in the current database:
  SELECT name, clr_name, permission_set_desc FROM sys.assemblies;
  • If the assembly is missing, confirm you are connected to the correct database context (USE [YourDatabaseName];) since CLR assemblies are database-scoped, not server-scoped.
  • On Windows Server 2025 / Windows 11, also confirm the original .dll source file still exists on disk (commonly under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ or your custom deployment path).

Step 3: Re-register the Missing Assembly

  • If the .dll file is available, re-create the assembly manually:
  CREATE ASSEMBLY [YourAssemblyName]
  FROM 'C:\Path\To\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • If the .dll is unavailable, extract it from a known-good backup or source control repository, then redeploy via SQL Server Data Tools (SSDT) or sqlcmd.
  • Ensure the SQL Server service account has read permissions on the folder containing the .dll file (right-click folder → Properties → Security → add NT SERVICE\MSSQLSERVER).

Step 4: Rebuild Dependent CLR Objects

  • Drop and recreate any stored procedures, functions, or triggers that reference the reinstated assembly to force SQL Server to refresh its internal metadata links:
  DROP PROCEDURE [dbo].[YourCLRProcedure];
  CREATE PROCEDURE [dbo].[YourCLRProcedure]
  AS EXTERNAL NAME [YourAssemblyName].[ClassName].[MethodName];
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear any cached execution plans referencing the old assembly ID.

Alternative or Verification Steps

  • Confirm the fix by executing the previously failing stored procedure/function directly and checking for successful completion without Error 6528.
  • If the assembly keeps disappearing after restores, check your backup/restore scripts or replication jobs for DROP ASSEMBLY statements, and consider enabling TRUSTWORTHY or using a Certificate-Signed Assembly to prevent unintended removal during security-policy-driven cleanups.

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

Troubleshooting Guide: SQL Server Error 6525 — Invalid Constraint in Streaming Table-Valued Function

Why This Error Happens

This error occurs because SQL Server 2025’s streaming user-defined function (UDF) engine does not permit certain table constraints — such as PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK — to be defined directly on the result table returned by a streaming table-valued function (TVF). Streaming TVFs are designed to return row sets on the fly without materializing intermediate storage, so the query optimizer cannot enforce or validate constraints against a result set that isn’t persisted. This typically happens when a developer migrates logic from a multi-statement TVF or a standard table definition and mistakenly carries over constraint syntax into the RETURNS TABLE (...) clause of an inline streaming function.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Definition

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to locate the function raising error 6525 by checking the error log context or correlating with recent CREATE FUNCTION / ALTER FUNCTION statements:
  SELECT object_name(object_id), definition 
  FROM sys.sql_modules 
  WHERE definition LIKE '%RETURNS TABLE%';
  • Review the RETURNS TABLE (...) clause for any embedded constraint keywords like PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK.

Step 2: Remove Unsupported Constraints from the Function Signature

  • Edit the function using ALTER FUNCTION and strip out the constraint clause from the table definition.
  • Example of invalid syntax to fix:
  RETURNS TABLE (ID INT PRIMARY KEY, Name NVARCHAR(50))
  • Corrected streaming-compatible syntax:
  RETURNS TABLE (ID INT, Name NVARCHAR(50))
  • If uniqueness or integrity enforcement is required, move that logic to the consuming table (via INSERT INTO a properly constrained table) rather than the function’s return definition.

Step 3: Convert to a Multi-Statement TVF (If Constraints Are Mandatory)

  • If your business logic truly requires constraint enforcement at the function level, convert the inline streaming TVF into a multi-statement table-valued function, which uses a DECLARE @ReturnTable TABLE (...) structure that does support constraints like PRIMARY KEY and UNIQUE.
  • Example:
  CREATE FUNCTION dbo.GetFilteredData()
  RETURNS @ReturnTable TABLE (ID INT PRIMARY KEY, Name NVARCHAR(50))
  AS
  BEGIN
      INSERT INTO @ReturnTable
      SELECT ID, Name FROM dbo.SourceTable WHERE Active = 1;
      RETURN;
  END;
  • Note: this approach sacrifices streaming performance benefits, so use it only when constraint enforcement is non-negotiable.

Step 4: Redeploy and Validate the Function

  • Drop and recreate the function on the target database using DROP FUNCTION IF EXISTS followed by the corrected CREATE FUNCTION statement.
  • Confirm the deployment script runs cleanly against both Windows Server 2025 and Windows 11 client environments without triggering Error 6525.

Alternative or Verification Steps

  • Run SELECT * FROM dbo.YourFunctionName() (or invoke it in a sample query) to confirm it executes without error and returns expected rows.
  • If the error persists, check SQL Server’s compatibility level (SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';) and ensure it is set to the SQL Server 2025 level (170 or higher), as older compatibility modes may handle streaming TVF parsing differently.

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

Troubleshooting Guide: SQL Server Error 6526 — Invalid Constraint in Streaming Table-Valued Function Result Table

Why This Error Happens

This error occurs because SQL Server 2025’s streaming table-valued function (TVF) engine does not permit certain constraint types—such as PRIMARY KEY, UNIQUE, FOREIGN KEY, DEFAULT, or CHECK constraints—to be defined directly on columns in the RETURNS TABLE clause. Streaming TVFs are designed to execute inline as a single SELECT statement, and the query optimizer cannot resolve constraint enforcement against a result set that is generated on-the-fly rather than materialized. This typically surfaces when a developer migrates logic from a multi-statement TVF or a regular table definition into a streaming (inline) TVF without stripping out the incompatible schema definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Definition

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the function throwing Error 6526.
  • Run the following query to pull the exact definition and inspect the RETURNS TABLE clause:
SELECT OBJECT_DEFINITION(OBJECT_ID('YourSchema.YourFunctionName'));
  • Look specifically for PRIMARY KEY, UNIQUE, DEFAULT, CHECK, or FOREIGN KEY keywords inside the parentheses of the RETURNS TABLE (...) definition.

Step 2: Remove Unsupported Constraints from the TABLE Declaration

  • Edit the CREATE FUNCTION or ALTER FUNCTION script to strip out the constraint syntax.
  • Example of the problematic code:
RETURNS TABLE (ID INT PRIMARY KEY, Name NVARCHAR(50))
  • Replace it with a plain column list, as streaming TVFs only support column name and data type definitions:
RETURNS TABLE (ID INT, Name NVARCHAR(50))
  • If you require key enforcement, apply it at the application layer or handle it within the underlying base table rather than the function’s return schema.

Step 3: Convert to a Multi-Statement TVF (If Constraints Are Mandatory)

  • If your business logic strictly requires a constrained table structure (e.g., to force uniqueness within the function’s temporary result), refactor the inline function into a multi-statement TVF.
  • Multi-statement TVFs use a BEGIN...END block and a declared @ReturnTable variable, which does support constraints:
CREATE FUNCTION dbo.GetData() 
RETURNS @ReturnTable TABLE (ID INT PRIMARY KEY, Name NVARCHAR(50))
AS
BEGIN
    INSERT INTO @ReturnTable
    SELECT ID, Name FROM dbo.SourceTable;
    RETURN;
END;
  • Be aware that multi-statement TVFs do not “stream” and may incur a performance penalty on large datasets compared to inline functions.

Step 4: Redeploy and Clear the Procedure Cache

  • Once the script is corrected, run the ALTER FUNCTION statement to update the object in the database.
  • Clear the plan cache for the specific database to ensure Windows Server 2025 does not attempt to execute a stale, cached execution plan referencing the old schema:
DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Verification: Execute a simple SELECT * FROM dbo.YourFunctionName() test query in SSMS; if the Error 6526 message no longer appears in the Messages tab and data returns successfully, the fix is confirmed.
  • Alternative: If performance is a concern after converting to a multi-statement TVF, consider replacing the function call entirely with a standard VIEW or a CROSS APPLY subquery, which can achieve similar filtering logic while maintaining the “streaming” optimization benefits of inline T-SQL.

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

Troubleshooting Guide: SQL Server Error 6523 (“Method… Getting Data”)

Why This Error Happens

Error 6523 in Microsoft SQL Server 2025 typically occurs when a CLR (Common Language Runtime) integration object — such as a SQLCLR assembly, trigger, or user-defined type — throws an unhandled .NET exception during execution, often while a method is actively retrieving or streaming data. This is frequently caused by a corrupted or outdated assembly reference, a broken connection stream mid-retrieval, or permission restrictions (EXTERNAL_ACCESS / UNSAFE) that block the CLR object from completing its data access operation. In some cases, this also surfaces due to mismatched .NET Framework/Core runtime versions between the SQL Server host and the deployed assembly on Windows Server 2025 or Windows 11.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Status

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to confirm CLR is enabled:
sp_configure 'clr enabled';
  • If the value is 0, enable it:
sp_configure 'clr enabled', 1;
RECONFIGURE;

Step 2: Check Assembly Permissions and Trust Level

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Assemblies.
  • Right-click the relevant assembly and verify its PERMISSION_SET (should be EXTERNAL_ACCESS or UNSAFE if it performs data retrieval).
  • If permissions are insufficient, alter the assembly:
ALTER ASSEMBLY [YourAssemblyName]
WITH PERMISSION_SET = EXTERNAL_ACCESS;
  • Ensure the database has TRUSTWORTHY set appropriately or the assembly is signed with a valid certificate.

Step 3: Re-deploy or Repair the Corrupted Assembly

  • Drop and re-register the assembly to rule out file corruption:
DROP ASSEMBLY [YourAssemblyName];
CREATE ASSEMBLY [YourAssemblyName]
FROM 'C:\SQLAssemblies\YourAssembly.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;
  • Confirm the .dll file path exists and is not blocked by Windows (right-click the file > Properties > Unblock).

Step 4: Validate .NET Runtime Compatibility

  • On Windows Server 2025 / Windows 11, open Control Panel > Programs > Programs and Features and confirm the installed .NET runtime matches the version SQL Server 2025 expects (typically .NET 8.0+ for CLR integration).
  • Update or repair the .NET runtime via:
winget upgrade Microsoft.DotNet.Runtime.8
  • Restart the SQL Server (MSSQLSERVER) service after the update.

Step 5: Review SQL Server Error Logs

  • Open SQL Server Configuration Manager > SQL Server Logs or check:
C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG
  • Look for stack trace details immediately preceding Error 6523 to identify the exact method and assembly causing the failure.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure that triggered the error and confirm no exception is thrown; check sys.assemblies to ensure the status shows as valid and loaded.
  • If the issue persists, as a fallback, disable CLR strict security (sp_configure 'clr strict security', 0;) temporarily to isolate whether the issue is permission-based versus code-based — but re-enable it once resolved, as this is a security-sensitive setting.

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

Troubleshooting Guide: Error 6524 – Cannot Use Computed Column in Streaming Table-Valued Function Result Table

Why This Error Happens

This error occurs because SQL Server 2025 does not support computed columns in the RETURNS TABLE clause of a streaming (inline) user-defined function. The query optimizer cannot resolve the expression-based column definition when the function is designed to return results as a streaming rowset rather than a materialized table variable. This limitation is by design in the SQL Server engine and typically surfaces when a developer migrates logic from a multi-statement table-valued function (MSTVF) to an inline table-valued function (iTVF) without adjusting the column definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Definition

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run sp_helptext 'YourFunctionName' to review the full T-SQL definition.
  • Locate the RETURNS TABLE (...) clause and check for any column defined using an expression (e.g., TotalPrice AS (Price * Quantity)), which is the specific trigger for Error 6524.

Step 2: Remove the Computed Column Definition

  • Edit the function script to eliminate the inline computed column syntax from the RETURNS TABLE schema declaration.
  • Move the calculation logic directly into the SELECT statement within the function body instead of defining it in the table schema.
  • Example fix: Change RETURNS TABLE (ID int, Total AS (Price*Qty)) to RETURNS TABLE (ID int, Total int) and ensure the SELECT statement calculates Price * Qty AS Total.

Step 3: Convert to a Multi-Statement Function (If Required)

  • If the computed logic is too complex to resolve in the SELECT statement alone, refactor the Inline Table-Valued Function (iTVF) into a Multi-Statement Table-Valued Function (MSTVF).
  • Use the BEGIN...END block syntax and define the table variable explicitly, as MSTVFs support computed columns within the @ReturnTable TABLE variable definition.
  • Re-deploy the function using CREATE OR ALTER FUNCTION to apply the schema changes in Windows Server 2025 environment.

Step 4: Clear the Execution Plan Cache

  • Once the function is altered, flush the specific stale plans to ensure Error 6524 does not persist due to cached execution metadata.
  • Run DBCC FREEPROCCACHE (Use with caution in production; prefer DBCC FLUSHPROCINDB (db_id) for a single database context).
  • Restart the “SQL Server (MSSQLSERVER)” service via services.msc if the error persists after the cache clear.

Alternative or Verification Steps

  • Verification: Execute the function manually using SELECT * FROM dbo.YourFunctionName() to confirm the query returns data successfully without throwing Error 6524.
  • Alternative: If refactoring is not immediately possible, wrap the streaming function call inside a standard SELECT statement from an external scope and perform the computation (e.g., Price * Qty) in that outer query instead of inside the function’s return schema.

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

Troubleshooting Guide: SQL Server Error 6521

Why This Error Happens

Error 6521 occurs when a SQLCLR (.NET Common Language Runtime) integration object—such as a CLR stored procedure, function, trigger, or user-defined type—throws an unhandled .NET exception during execution. This is typically caused by a corrupted or outdated CLR assembly, a mismatch between the assembly’s target framework and the .NET runtime installed on Windows Server 2025 / Windows 11, or insufficient PERMISSION_SET (SAFE, EXTERNAL_ACCESS, UNSAFE) rights granted to the assembly. It can also result from null reference exceptions or type casting errors within the custom .NET code itself that SQL Server surfaces as a generic CLR fault.

Step-by-Step Resolution Guide

Step 1: Identify the Faulting Assembly and Exception Details

  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the full exception stack trace following Error 6521.
  • Run SELECT * FROM sys.assemblies; and SELECT * FROM sys.assembly_modules; to identify which CLR object triggered the failure.
  • Note the exact .NET Framework error message text (e.g., NullReferenceException, InvalidCastException) for targeted debugging.

Step 2: Verify CLR Integration and Runtime Configuration

  • Confirm CLR is enabled by running sp_configure 'clr enabled'; — it should return a value of 1.
  • If disabled, execute:
  sp_configure 'show advanced options', 1;
  RECONFIGURE;
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Verify the correct .NET runtime version is installed by checking C:\Windows\Microsoft.NET\Framework64\ and ensure it aligns with the assembly’s compiled target framework.

Step 3: Rebuild and Re-Register the Assembly

  • Recompile the source .dll project ensuring the target framework matches what SQL Server 2025 supports.
  • Drop the corrupted assembly: DROP ASSEMBLY YourAssemblyName;
  • Re-add it with correct permissions:
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • If the code requires file or network access, use EXTERNAL_ACCESS instead, and ensure the assembly is signed and trusted via sys.sp_add_trusted_assembly if strict security is enabled.

Step 4: Check Database and Server Trustworthy Settings

  • Run SELECT is_trustworthy_on FROM sys.databases WHERE name = 'YourDatabase';
  • If required for EXTERNAL_ACCESS or UNSAFE assemblies without strong-name signing, set:
  ALTER DATABASE YourDatabase SET TRUSTWORTHY ON;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear any cached CLR AppDomain state.

Alternative or Verification Steps

  • Re-execute the original query or stored procedure that triggered Error 6521 and confirm no exception appears in the SQL Server Error Log.
  • If the error persists, isolate the issue by testing the compiled .dll independently in a standalone .NET console app to catch the exception outside of SQL Server before re-deploying.

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

Troubleshooting Guide: SQL Server Error 6522 — .NET Framework Error in User-Defined Routine or Aggregate

Why This Error Happens

Error 6522 occurs when a CLR (Common Language Runtime) integration object—such as a user-defined function, stored procedure, trigger, or aggregate—throws an unhandled .NET exception during execution inside SQL Server’s hosted CLR environment. This is typically caused by corrupted or outdated assembly DLLs, insufficient CLR permission sets (SAFE, EXTERNAL_ACCESS, UNSAFE) assigned to the assembly, missing dependent assemblies, or incompatible .NET runtime versions following a SQL Server 2025 or Windows Server 2025 update. It can also surface due to broken trust chains when assemblies are registered with PERMISSION_SET = UNSAFE but the database owner lacks the required UNSAFE ASSEMBLY permission.

Step-by-Step Resolution Guide

Step 1: Enable and Review Detailed CLR Error Output

  • Run sp_configure 'clr enabled', 1; RECONFIGURE; to confirm CLR integration is active.
  • Enable sp_configure 'clr strict security', 0; temporarily (only for diagnostics) to see if strict security is blocking execution.
  • Check the SQL Server Error Log (Management > SQL Server Logs) and Windows Event Viewer (Applications and Services Logs > Microsoft > Windows > .NET Runtime) for the inner exception stack trace referenced by %ls in the error message.

Step 2: Validate and Re-register the Assembly

  • Query the assembly’s current state and permission set:
  SELECT name, permission_set_desc, is_visible FROM sys.assemblies;
  • Drop and re-add the problematic assembly to rule out file corruption:
  ALTER ASSEMBLY MyAssembly FROM 'C:\Assemblies\MyAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Verify the DLL file itself isn’t blocked by Windows (right-click the file in File Explorer → Properties → Unblock, since Windows Server 2025 enforces stricter Mark-of-the-Web policies).

Step 3: Check Trust and Permission Configuration

  • If using EXTERNAL_ACCESS or UNSAFE, ensure the database has TRUSTWORTHY ON or the assembly is signed and registered via sys.sp_add_trusted_assembly.
  • Confirm the SQL Server service account (not just sa or sysadmin login) has NTFS read permissions on the assembly file path.
  • For UNSAFE assemblies, verify the login executing the routine has been granted the UNSAFE ASSEMBLY permission explicitly.

Step 4: Update .NET Runtime and SQL Server Cumulative Updates

  • Confirm the .NET Framework/CLR version bundled with SQL Server 2025 matches the version the assembly was compiled against (check via SELECT SERVERPROPERTY('ProductVersion'); and assembly metadata).
  • Apply the latest Cumulative Update (CU) for SQL Server 2025, since CLR hosting fixes are frequently bundled in CU patches.
  • Reboot Windows Server 2025 after patching to fully reload the CLR hosting environment.

Alternative or Verification Steps

  • After applying fixes, re-execute the failing routine directly (e.g., EXEC MyCLRProcedure;) and confirm no exception is thrown; also check sys.dm_clr_loaded_assemblies to verify the assembly loaded successfully into the CLR AppDomain.
  • If the error persists, as a fallback, rewrite the critical logic in T-SQL instead of CLR, or isolate the assembly in a dedicated low-trust database with PERMISSION_SET = SAFE to eliminate external dependency failures.

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

Troubleshooting Guide: SQL Server Error 6519 — “Type ‘%.*ls’ is not yet supported for CLR operations”

Why This Error Happens

This error occurs when SQL Server’s CLR integration attempts to marshal a SQL data type to or from a .NET CLR type that is not supported in the current mapping layer, often involving newer or deprecated types like sql_variant, geography, geometry, or large user-defined types passed as parameters. It can also surface after an in-place upgrade to SQL Server 2025 where assemblies were compiled against an older SqlTypes library version that doesn’t recognize updated type definitions. Additionally, this can be triggered when CLR integration is disabled or when the clr strict security setting blocks proper type resolution for unsigned assemblies.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration is Enabled

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following T-SQL to check CLR status:
  sp_configure 'clr enabled';
  • If the run_value is 0, enable it:
  sp_configure 'clr enabled', 1;
  RECONFIGURE;

Step 2: Check the Data Type Compatibility of the Assembly

  • Identify which function, trigger, or stored procedure is throwing the error by checking the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Review the parameter and return types used in the CLR assembly source code (common offenders: SqlGeography, SqlHierarchyId, SqlFileStream, or custom CLR UDTs).
  • Replace unsupported types with native SQL types (e.g., NVARCHAR(MAX), VARBINARY(MAX)) where possible, or recompile the assembly against the updated Microsoft.SqlServer.Types.dll shipped with SQL Server 2025.

Step 3: Re-register and Rebuild the CLR Assembly

  • Drop the outdated assembly:
  DROP ASSEMBLY YourAssemblyName;
  • Rebuild the project in Visual Studio targeting .NET Framework/CLR version compatible with SQL Server 2025 (check release notes for the required runtime version).
  • Re-deploy using:
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\Path\To\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;

Step 4: Validate CLR Strict Security Settings

  • Check if clr strict security is interfering with type loading:
  sp_configure 'clr strict security';
  • If enabled (default in modern SQL Server versions) and your assembly is unsigned, either sign the assembly with a certificate and create a login mapped to it with UNSAFE ASSEMBLY permission, or add the assembly to the trusted assemblies list:
  EXEC sp_add_trusted_assembly @hash = 0x<YourAssemblyHash>, @description = N'Trusted CLR Assembly';

Step 5: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to ensure the updated assembly and configuration settings take effect.

Alternative or Verification Steps

  • Run a test query or execute the stored procedure/function that previously failed to confirm the error no longer appears in SSMS or the ERRORLOG.
  • If the issue persists, use SELECT * FROM sys.assembly_types; to confirm the type mappings are correctly registered, and consider rewriting the CLR object using only natively supported SQL Server data types as a permanent workaround.

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

Troubleshooting Guide: SQL Server Error 6520 – .NET Framework Error During Statement Execution

Why This Error Happens

Error 6520 occurs when a SQLCLR (SQL Common Language Runtime) integration — such as a CLR stored procedure, function, trigger, or user-defined type — throws an unhandled .NET exception during execution. This is typically caused by corrupted or outdated CLR assemblies, a mismatch between the SQL Server CLR runtime version and the .NET Framework version installed on Windows Server 2025 / Windows 11, or insufficient PERMISSION_SET rights (SAFE, EXTERNAL_ACCESS, UNSAFE) assigned to the assembly. It can also surface due to resource exhaustion (memory pressure) within the CLR host, causing managed code to fail mid-execution.

Step-by-Step Resolution Guide

Step 1: Identify the Failing Assembly and Capture the Inner Exception

  • Query sys.assemblies and sys.assembly_modules to locate the CLR object referenced in the error message.
  • Enable detailed error capture by running the failing statement with SET XACT_ABORT ON; to surface the full .NET stack trace.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the underlying System.Exception type (e.g., NullReferenceException, OutOfMemoryException).

Step 2: Verify and Repair the .NET Framework / CLR Configuration

  • Confirm CLR integration is enabled by running:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • On Windows Server 2025 / Windows 11, open Control Panel > Programs > Turn Windows features on or off and ensure .NET Framework 4.8.x (or the version SQL Server 2025 requires) is fully enabled, not just partially installed.
  • Run sfc /scannow from an elevated Command Prompt to repair corrupted system/.NET binaries that may be causing the managed exception.

Step 3: Re-register and Rebuild the Problematic Assembly

  • Drop and re-add the assembly with correct permissions:
  ALTER ASSEMBLY [YourAssemblyName]
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = EXTERNAL_ACCESS;
  • If the assembly uses UNSAFE, confirm the database has TRUSTWORTHY ON or that the assembly is properly signed with a certificate/asymmetric key, since Windows Server 2025 enforces stricter CLR strict security by default.
  • Rebuild the DLL against the exact .NET Framework version matching the SQL Server 2025 CLR host.

Step 4: Allocate Sufficient Memory for the CLR Host

  • Open SQL Server Management Studio (SSMS), right-click the instance, and go to Properties > Memory.
  • Increase Maximum server memory to leave adequate headroom for the CLR virtual machine, especially if running on a shared Windows Server 2025 host with limited RAM.
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER to apply changes.

Alternative or Verification Steps

  • Re-execute the original failing statement/stored procedure in SSMS and confirm no Error 6520 is raised; check sys.dm_exec_requests to ensure the session completes without rollback.
  • If the issue persists, as a fallback, rewrite the CLR logic as a native T-SQL procedure/function to eliminate the .NET dependency entirely.

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

Troubleshooting Guide: Error 6516 – “There is no collection ‘%.ls’ in metadata ‘%.ls'”

Why This Error Happens

This error occurs in SQL Server 2025 when a query references an XML or JSON schema collection that does not exist within the specified metadata (schema/database) context, typically due to a naming mismatch, incorrect schema qualification, or the collection having been dropped. It can also surface after a database restore or migration where schema collections were not included in the backup, or when permissions prevent the session from resolving the collection within sys.xml_schema_collections. In multi-schema environments, this frequently happens when the collection exists under a different schema than the one implied in the T-SQL statement.

Step-by-Step Resolution Guide

Step 1: Verify the Schema Collection Exists

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to confirm the collection is present:
  SELECT s.name AS SchemaName, xsc.name AS CollectionName
  FROM sys.xml_schema_collections xsc
  JOIN sys.schemas s ON xsc.schema_id = s.schema_id;
  • If the collection is missing, check recent deployment scripts or migration logs for accidental DROP XML SCHEMA COLLECTION statements.

Step 2: Correct the Schema Qualification in Your Query

  • Ensure the T-SQL statement explicitly references the correct schema, e.g., dbo.MyCollection instead of just MyCollection.
  • Update any stored procedures, views, or application connection strings (found typically in C:\inetpub\wwwroot\<App>\web.config or C:\Program Files\<App>\appsettings.json on Windows Server 2025) that hardcode the collection path.
  • Re-run the query after correcting the fully qualified name.

Step 3: Recreate the Missing XML/JSON Schema Collection

  • If the collection was lost during a restore, re-import it using the original .xsd definition file:
  CREATE XML SCHEMA COLLECTION dbo.MyCollection AS 
  N'<schema definition here>';
  • Store the source .xsd file in a version-controlled location such as C:\SQLSchemas\Collections\ to prevent future loss.

Step 4: Validate Permissions on the Metadata

  • Confirm the executing user has REFERENCES permission on the XML schema collection:
  GRANT REFERENCES ON XML SCHEMA COLLECTION::dbo.MyCollection TO [YourUser];
  • Check Windows Server 2025 Local Security Policy (secpol.msc) to ensure the SQL Server service account hasn’t been restricted from accessing the database metadata catalog.

Alternative or Verification Steps

  • Re-execute the original failing query or stored procedure and confirm Error 6516 no longer appears in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • As an alternative, if the collection is non-critical, modify the application logic to validate collection existence via OBJECT_ID or catalog views before execution, preventing the error from being thrown in future runtime calls.

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

Troubleshooting Guide: SQL Server Error 6517 – “Failed to create AppDomain”

Why This Error Happens

Error 6517 occurs when SQL Server’s CLR (Common Language Runtime) integration fails to initialize a new AppDomain, typically because the SQL Server service account lacks the necessary permissions on the .NET Framework/CoreCLR directories or registry hives. This can also stem from corrupted CLR assemblies, incompatible .NET runtime versions bundled with SQL Server 2025, or insufficient memory/resources preventing the AppDomain sandbox from being allocated. In some cases, security software or restrictive Windows Defender Application Control (WDAC) policies on Windows Server 2025 block the dynamic loading of CLR libraries.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration and Service Account Permissions

  • Confirm CLR is enabled by running: sp_configure 'clr enabled', 1; RECONFIGURE;
  • Check that the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read & Execute permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and the .NET runtime folder under C:\Program Files\dotnet\.
  • Use icacls to grant access if missing: icacls "C:\Program Files\dotnet" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)RX

Step 2: Repair or Reinstall the .NET Runtime Dependency

  • SQL Server 2025 relies on a specific CoreCLR version; validate it matches the required build listed in SQL Server Setup logs (Summary.txt in %ProgramFiles%\Microsoft SQL Server\170\Setup Bootstrap\Log\).
  • Run sfc /scannow on Windows Server 2025 to repair corrupted system files that may affect the CLR host.
  • If corruption is confirmed, repair the SQL Server instance via Control Panel > Programs > Microsoft SQL Server 2025 > Repair.

Step 3: Check Security Policies and Antivirus Exclusions

  • Review Windows Defender Application Control (WDAC) or AppLocker policies that may block dynamic assembly loading from the SQL Binn directory.
  • Add exclusions in your antivirus/EDR software for sqlservr.exe and the Binn folder to prevent real-time scanning from locking DLLs during AppDomain creation.
  • Restart the SQL Server service after applying exclusions: Restart-Service MSSQLSERVER

Step 4: Review Memory and Resource Allocation

  • Check if the server is under memory pressure using Performance Monitor (Memory\Available MBytes).
  • Ensure “max server memory” in SQL Server is not configured too restrictively, starving the CLR host of resources needed to spin up AppDomains.
  • Adjust via: EXEC sp_configure 'max server memory (MB)', 8192; RECONFIGURE; (adjust value based on available RAM).

Alternative or Verification Steps

  • To verify the fix, execute a simple CLR-based stored procedure or query sys.dm_clr_appdomains to confirm the AppDomain now initializes without error.
  • If the issue persists, enable SQL Server CLR diagnostic logging via Extended Events (XML Deadlock Report session modified to capture clr_virtual_machine events) to capture a deeper stack trace for Microsoft support escalation.

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

Troubleshooting Guide: SQL Server Error 6518 — “Could not open system assembly”

Why This Error Happens

Error 6518 occurs when SQL Server’s CLR integration engine cannot locate, read, or validate one of the internal system assemblies (such as Microsoft.SqlServer.Types or System.Data) that are required for SQL CLR execution. This is typically caused by a corrupted or missing SQL Server installation file, an interrupted patch/upgrade process, mismatched .NET runtime versions bundled with SQL Server 2025, or restrictive NTFS/file permissions on the Binn directory that prevent the Database Engine service account from reading the assembly files. In some cases, antivirus or endpoint protection software may also be quarantining or locking these DLLs, triggering the same failure.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Open File Explorer and navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ (adjust instance folder name as needed for SQL Server 2025).
  • Right-click the folder, go to Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read & Execute permissions.
  • If permissions are missing, click Edit, add the service account, and grant Read & Execute access, then click Apply.

Step 2: Check for Corrupted or Quarantined Assembly Files

  • Open Windows Security > Virus & Threat Protection > Protection History and check if any .dll files under the SQL Server Binn directory were quarantined or deleted.
  • Restore any quarantined files and add an exclusion rule for the SQL Server installation directory to prevent future interference.
  • Run sfc /scannow from an elevated Command Prompt to repair corrupted Windows system files that may affect the .NET runtime dependencies.

Step 3: Rebuild or Repair the SQL Server CLR Assemblies

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following command to identify the problematic assembly:
    SELECT name, clr_name FROM sys.assemblies WHERE is_user_defined = 0;
  • If a specific system assembly is corrupted, launch the SQL Server 2025 Setup Wizard, select Repair, and choose the affected instance to restore the original Binn files.

Step 4: Validate .NET Framework / Runtime Compatibility

  • Confirm that the correct .NET runtime version required by SQL Server 2025 is installed via Control Panel > Programs > Programs and Features.
  • If missing or outdated, download and install the required .NET Desktop Runtime version from the official Microsoft Download Center.
  • Restart the SQL Server (MSSQLSERVER) service from services.msc after installation completes.

Alternative or Verification Steps

  • After applying fixes, restart the SQL Server service and run sp_configure 'clr enabled', 1; followed by RECONFIGURE;, then execute a test CLR function to confirm Error 6518 no longer appears in the SQL Server Error Log.
  • If the issue persists, perform a full uninstall and clean reinstall of the SQL Server instance using the official ISO, ensuring no leftover files remain in the Binn directory beforehand.

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

Troubleshooting Guide: SQL Server Error 6514 — Streaming User-Defined Function Column Restriction

Why This Error Happens

This error occurs because SQL Server’s streaming table-valued function (TVF) feature has strict restrictions on the data types permitted in its result set, and the specified column uses an unsupported type such as timestamp, sql_variant, CLR user-defined types, or large object (LOB) types in certain configurations. Streaming TVFs are compiled and optimized differently than standard multi-statement functions, so the query processor rejects columns that cannot be reliably “streamed” without materialization. This typically surfaces after migrating T-SQL code to SQL Server 2025 or after converting a multi-statement TVF into a streaming (inline-style) function where the underlying schema was not validated against streaming constraints.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Function

  • Capture the full error text; the %.*ls placeholder resolves to the actual column name and the %s placeholder identifies the unsupported data type.
  • Run sp_helptext 'YourFunctionName' in SSMS to review the full definition of the streaming UDF.
  • Cross-reference the column against SQL Server 2025’s documented list of unsupported streaming TVF types (notably timestamp/rowversion, sql_variant, and CLR UDTs).

Step 2: Modify the Column Definition or Query Logic

  • Open the function definition in SQL Server Management Studio (SSMS 21 or later, compatible with SQL Server 2025).
  • Cast the offending column to a supported type directly in the SELECT statement, for example: CAST(YourColumn AS VARBINARY(8)) for a timestamp column.
  • If the column is a CLR UDT, convert it explicitly using .ToString() or an equivalent serialization method before returning it in the result set.
  • Save and redeploy the function using ALTER FUNCTION.

Step 3: Disable Streaming Behavior as a Workaround

  • Navigate to the function’s WITH clause and remove or adjust any hints forcing streaming execution (e.g., OPTION (USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION')) is unrelated, but check for WITH SCHEMABINDING combined with streaming-specific hints).
  • Convert the inline TVF to a multi-statement TVF temporarily by wrapping logic in BEGIN...RETURN blocks, which bypasses the streaming execution path entirely.
  • Test the function in isolation: SELECT * FROM dbo.YourFunction(@param).

Step 4: Update Database Compatibility Level

  • Check the current compatibility level: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the database was upgraded from an older version, ensure it is set correctly for SQL Server 2025 features: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025/Windows 11 if compatibility changes do not take effect immediately.

Step 5: Apply the Latest Cumulative Update

  • Open PowerShell as Administrator and check your current build: SELECT @@VERSION;
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as streaming TVF type-handling bugs are periodically patched.
  • Reboot Windows Server 2025 after installation and re-run the function to confirm the fix.

Alternative or Verification Steps

  • Verify the fix by executing the function directly with representative test data and confirming no Error 6514 appears in the SSMS results pane or the SQL Server Error Log (EXEC xp_readerrorlog).
  • As an alternative, re-architect the function as a stored procedure instead of a streaming TVF if the unsupported column type is a hard business requirement, since stored procedures do not enforce the same streaming restrictions.

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

Troubleshooting Guide: SQL Server Error 6515 – Schema Collection Database Does Not Exist

Why This Error Happens

Error 6515 occurs when a WSDL or SOAP endpoint, or an XML schema collection operation, references a database context that SQL Server cannot locate or access under the current security context. This typically happens because the database was renamed, dropped, or detached after the schema collection or endpoint was created, leaving a stale reference. It can also occur when the login executing the query lacks the necessary permissions (such as REFERENCES or VIEW DEFINITION) on the target database or schema collection.

Step-by-Step Resolution Guide

Step 1: Verify the Target Database Exists

  • Open SQL Server Management Studio (SSMS) and expand Databases in Object Explorer.
  • Run the following query to confirm the database is present and online:
SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the database is missing, restore it from the most recent backup using RESTORE DATABASE or reattach the .mdf/.ldf files via Tasks > Attach.

Step 2: Check and Repair Permissions on the Schema Collection

  • Confirm the login/user has VIEW DEFINITION and REFERENCES permissions on the XML schema collection:
GRANT REFERENCES ON XML SCHEMA COLLECTION::[SchemaCollectionName] TO [UserOrLogin];
  • Validate the schema collection actually exists in the correct database:
SELECT * FROM sys.xml_schema_collections WHERE name = 'SchemaCollectionName';
  • If it is missing, recreate it using CREATE XML SCHEMA COLLECTION with the original XSD definition.

Step 3: Validate the Database Context in Connection Strings and Endpoints

  • Check any SOAP/WSDL endpoints or application connection strings that may be hardcoded to an old database name:
SELECT name, type_desc FROM sys.endpoints;
  • Update the connection string or endpoint definition (via ALTER ENDPOINT) to point to the correct, currently active database.
  • On Windows Server 2025/Windows 11, also verify ODBC/DSN entries in Control Panel > Administrative Tools > ODBC Data Sources reference the correct database.

Step 4: Restart SQL Server Services and Clear Cached Plans

  • Open SQL Server Configuration Manager, right-click the SQL Server (MSSQLSERVER) service, and select Restart.
  • Clear the procedure cache to remove stale metadata references:
DBCC FREEPROCCACHE;
  • Re-run the failing query or application call to confirm the error no longer appears.

Alternative or Verification Steps

  • Run sp_helpdb 'YourDatabaseName' to confirm the database is online and accessible to the current login.
  • If the issue persists, use sqlcmd -S servername -d YourDatabaseName -Q "SELECT DB_NAME()" from Command Prompt to verify connectivity and permissions outside of SSMS.

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

Troubleshooting Guide: SQL Server Error 6512 — CLR Initialization Failure

Why This Error Happens

Error 6512 occurs when SQL Server 2025 cannot load the Common Language Runtime (CLR) hosting components, typically because the .NET runtime files required by SQL Server are missing, corrupted, or mismatched in version. This often happens after a Windows Update, a .NET runtime patch, or an incomplete SQL Server service pack installation disrupts the binding between sqlservr.exe and the CLR host (mscoree.dll or clrhost.dll). It can also result from insufficient permissions on the SQL Server service account to access the .NET Framework/Runtime installation directories, or from clr strict security and clr enabled configuration conflicts introduced in newer SQL Server builds.

Step-by-Step Resolution Guide

Step 1: Verify CLR Is Enabled and Check Current Configuration

  • Open SQL Server Management Studio (SSMS) and run the following to confirm CLR integration is turned on:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'clr enabled';
  • If the run_value is 0, enable it:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Note the exact HRESULT value in the error log (e.g., 0x80131701) — this pinpoints whether it’s a missing assembly, access denial, or version mismatch.

Step 2: Repair or Reinstall the .NET Runtime Dependencies

  • Navigate to Control Panel > Programs > Programs and Features and locate “.NET Desktop Runtime” or “.NET 8/9 Runtime” (required by SQL Server 2025).
  • Select Repair rather than uninstalling, to avoid breaking other dependent services.
  • If repair fails, download the matching runtime installer from the official Microsoft .NET download page and reinstall manually.
  • Restart the server after the repair completes:
  Restart-Computer -Force

Step 3: Validate SQL Server Service Account Permissions

  • Open Services.msc and identify the account running the “SQL Server (MSSQLSERVER)” service.
  • Ensure this account has Read & Execute permissions on:
  • C:\Program Files\dotnet\
  • C:\Windows\Microsoft.NET\Framework64\
  • C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\
  • Grant permissions via PowerShell if needed:
  icacls "C:\Program Files\dotnet" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)RX"

Step 4: Rebuild the CLR Host Binding via SQL Server Setup Repair

  • Launch SQL Server Installation Center from the Start Menu.
  • Select Maintenance > Repair, choose the affected instance, and let the wizard reinitialize the CLR hosting files.
  • Once repair finishes, restart the SQL Server service:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 5: Restart SQL Server and Confirm Resolution

  • Fully restart the SQL Server service (not just the instance) since CLR is only initialized once per service lifecycle.
  • Check the SQL Server Error Log immediately after restart for any recurrence of Error 6512.

Alternative or Verification Steps

  • Run a test CLR query to confirm functionality, such as creating a simple CLR-based scalar function or executing SELECT * FROM sys.dm_clr_tasks; — if it returns without error, the CLR host is functioning correctly.
  • If the issue persists after all steps, uninstall and cleanly reinstall the SQL Server Database Engine component (not the entire instance) using Add/Remove Features in SQL Server Installation Center, which forces a full re-registration of the CLR hosting binaries.

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

Troubleshooting Guide: SQL Server Error 6513 – CLR Initialization Failure Due to Memory Pressure

Why This Error Happens

Error 6513 occurs when SQL Server cannot initialize the CLR host because the MemToLeave (MTL) region — a reserved block of virtual address space outside the SQL Server buffer pool used for CLR, extended stored procedures, and linked server providers — has become exhausted. This is typically caused by excessive non-buffer-pool memory consumption from a high number of worker threads, oversized -g (memory-to-leave) configuration, extended stored procedure leaks, or a 32-bit virtual address space bottleneck even on 64-bit systems with constrained VAS settings. It can also be triggered by third-party CLR assemblies that fail to release unmanaged memory properly.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory-to-Leave Configuration

  • Open SQL Server Configuration Manager and check the SQL Server service startup parameters for a -g flag (e.g., -g512).
  • If no -g parameter is present, SQL Server is using the default (256 MB on 64-bit), which may be insufficient under heavy CLR or XP usage.
  • Run DBCC MEMORYSTATUS in SSMS and inspect the MEMORYCLERK_SQLCLR and “MemToLeave” sections of the output to confirm the region is under pressure.

Step 2: Increase the MemToLeave Region

  • Add or modify the -g startup parameter via SQL Server Configuration Manager → Properties → Startup Parameters.
  • Set a higher value, such as -g512 or -g1024, depending on workload (test incrementally; do not set excessively high as it reduces buffer pool memory).
  • Restart the SQL Server service for the change to take effect:
  • net stop MSSQLSERVER && net start MSSQLSERVER

Step 3: Reduce Worker Thread and Linked Server Overhead

  • Lower the max worker threads setting in sp_configure if the instance is running with a non-default, excessively high thread count.
  • Audit and disable unused extended stored procedures (sp_helpextendedproc) and legacy linked server OLE DB providers that consume MTL space.
  • Run sp_configure 'max worker threads' and reset to 0 (auto-configure) if it was manually overridden.

Step 4: Patch and Validate CLR Assemblies

  • Ensure SQL Server 2025 is updated to the latest Cumulative Update (CU) via Windows Update or the Microsoft Update Catalog, as early CLR host builds have known memory leak fixes.
  • Review custom CLR assemblies using sys.assemblies and sys.dm_clr_loaded_assemblies for unmanaged memory leaks; recompile with PERMISSION_SET = SAFE where possible.
  • Restart the SQL Server CLR integration: sp_configure 'clr enabled', 1; RECONFIGURE; after validating assemblies.

Step 5: Check System-Level Virtual Address Space Constraints

  • On Windows Server 2025 / Windows 11, confirm no /3GB or increaseuserva boot switches are forcing an artificially small kernel-mode VAS split (legacy BCD settings can still apply to compatibility modes).
  • Use bcdedit /enum to confirm no legacy switches are active, and remove them with bcdedit /deletevalue increaseuserva if found.

Alternative or Verification Steps

  • Re-run DBCC MEMORYSTATUS after applying changes and confirm the MemToLeave region shows available reserved space rather than near-zero free bytes.
  • If the error persists, consider migrating memory-intensive CLR workloads to an out-of-process service (e.g., a .NET microservice called via external calls) to permanently offload pressure from the MTL region.

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

Troubleshooting Guide: Error 6510 – .NET Framework 4 Requirement Missing

Why This Error Happens

This error occurs when SQL Server 2025 attempts to invoke a feature (such as SQL CLR integration, SQL Server Agent subsystems, or Integration Services components) that depends on the .NET Framework 4 runtime, but the runtime is either not installed or has been disabled/corrupted on the host system. SQL Server 2025, despite shipping with modern .NET support, still relies on the legacy .NET Framework 4 (or 4.x compatible) runtime for certain backward-compatible CLR integration features and older extended stored procedures. On Windows Server 2025 and Windows 11, .NET Framework 4.8.x is typically present as an OS component, but it can be removed via Server Manager roles/features or corrupted by incomplete Windows Updates.

Step-by-Step Resolution Guide

Step 1: Verify Current .NET Framework Installation Status

  • Open PowerShell as Administrator and run:
    Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" -Name Release -ErrorAction SilentlyContinue
  • Check the returned “Release” value against Microsoft’s version reference table (528040+ indicates 4.8 or later is installed).
  • If the registry key is missing entirely, .NET Framework 4.x is not installed on the machine.

Step 2: Enable the Feature via Windows Server Manager (Windows Server 2025)

  • Launch Server Manager > Manage > Add Roles and Features.
  • Navigate to Features and expand .NET Framework 4.8 Features.
  • Ensure .NET Framework 4.8 and WCF Services (if applicable) checkboxes are selected, then click Install.
  • Reboot the server once installation completes to finalize the component registration.

Step 3: Enable the Feature via Windows 11 (Optional Features)

  • Go to Settings > Apps > Optional Features > More Windows Features.
  • Locate .NET Framework 4.8 Advanced Services in the Windows Features dialog box.
  • Check the box, click OK, and allow Windows to download required files from Windows Update if prompted.
  • Restart the machine after the installation finishes.

Step 4: Repair a Corrupted Installation

  • If .NET Framework 4 shows as installed but the error persists, download the .NET Framework Repair Tool from the official Microsoft Download Center.
  • Run the tool with Administrator privileges and select the detected .NET Framework 4.x installation to repair.
  • Follow the prompts to fix registry entries and reinstall missing binary components automatically.

Step 5: Restart SQL Server Services

  • Open SQL Server Configuration Manager.
  • Right-click the SQL Server (MSSQLSERVER) service (or named instance) and select Restart.
  • Also restart SQL Server Agent if the error originated from a scheduled job or subsystem task.

Alternative or Verification Steps

  • Re-run the specific SQL Server feature or job that triggered Error 6510 (e.g., SSIS package execution, CLR-enabled stored procedure, or Agent job step) and confirm the error no longer appears in the SQL Server Error Log.
  • As an alternative, if Server Manager fails to install the feature due to WSUS/Group Policy restrictions, manually download the .NET Framework 4.8 Offline Installer from Microsoft and run it directly with the /q /norestart silent install flags via an elevated command prompt.

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

Microsoft SQL Server 2025 Error 6511: CLR Initialization Failure

Why This Error Happens

Error 6511 occurs when SQL Server’s SQLCLR host fails to load the Common Language Runtime, typically because the required .NET runtime version is missing, corrupted, or incompatible with SQL Server 2025’s hosting requirements. This can also stem from restrictive OS-level permissions on the SQL Server service account, preventing access to the CLR assemblies located in the .NET installation directory. Additionally, a mismatch between the CLR version registered in the Windows registry and the actual binaries on disk—often caused by an incomplete Windows Update or botched .NET patch—will trigger this HRESULT failure.

Step-by-Step Resolution Guide

Step 1: Verify and Repair the .NET Runtime Installation

  • Open Control Panel > Programs and Features and confirm the .NET runtime version required by SQL Server 2025 is listed (check SQL Server 2025 release notes for the exact build number).
  • If present, select it and click Repair rather than uninstalling, as a full removal can orphan registry keys.
  • Alternatively, run dotnet --info in an elevated Command Prompt to validate the installed runtime integrity.

Step 2: Check SQL Server Service Account Permissions

  • Navigate to the .NET installation folder, typically C:\Windows\Microsoft.NET\Framework64\<version>\.
  • Right-click the folder, go to Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read & Execute permissions.
  • Also verify permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ for consistency.

Step 3: Rebuild the CLR Integration Configuration

  • Open SQL Server Management Studio (SSMS) and connect via an account with sysadmin rights.
  • Run the following T-SQL to disable and re-enable CLR integration, forcing SQL Server to reload the runtime:
EXEC sp_configure 'clr enabled', 0;
RECONFIGURE;
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 4: Inspect Windows Event Viewer and SQL Error Log

  • Open Event Viewer > Windows Logs > Application and filter for Source “MSSQLSERVER” to find the full stack trace alongside Error 6511.
  • Cross-reference the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the specific HRESULT code, which pinpoints whether it’s a file access issue (0x80070005) or a missing module (0x8007007E).

Step 5: Reinstall SQL Server CLR Components via Setup

  • If the above steps fail, launch the SQL Server 2025 Installation Media and select Maintenance > Repair.
  • This re-registers the SQLCLR hosting DLLs (sqlservr.exe dependencies) and restores any corrupted binaries without affecting your databases.

Alternative or Verification Steps

  • To verify the fix, execute a simple CLR test in SSMS: create a basic CLR stored procedure or run SELECT * FROM sys.dm_clr_tasks;—if it returns results without error, the CLR host is functioning correctly.
  • If the error persists after a repair, consider performing a clean uninstall of the .NET runtime and manually reinstalling the specific version using an offline installer package downloaded directly from the official Microsoft .NET site, as corrupted installer caches can cause repeated repair failures.

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

Troubleshooting Guide: SQL Server Error 6508 — “Could not find field ‘%s’ for type ‘%s’ in assembly ‘%s'”

Why This Error Happens

This error occurs when SQL Server’s CLR integration engine attempts to resolve a field reference within a SQL CLR assembly (.dll), but the field metadata does not match what is registered in the sys.assembly_files catalog. This mismatch is typically caused by an outdated or corrupted assembly being loaded into SQL Server 2025 after the source code was modified and recompiled without re-registering the assembly. It can also occur if a dependent assembly was updated independently, breaking the version binding expected by the parent assembly, or if Windows Server 2025 file permissions prevent SQL Server from reading the correct .dll version from disk.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic Assembly and Field

  • Run the following query to locate the assembly throwing the error:
  SELECT a.name, a.clr_name, af.content 
  FROM sys.assemblies a
  JOIN sys.assembly_files af ON a.assembly_id = af.assembly_id;
  • Cross-reference the %s placeholders in the error log (found in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to identify the exact type and field name causing the mismatch.

Step 2: Drop and Re-register the Assembly

  • Disable CLR strict security temporarily if testing in a non-production environment:
  EXEC sp_configure 'clr strict security', 0;
  RECONFIGURE;
  • Drop the outdated assembly:
  DROP ASSEMBLY YourAssemblyName;
  • Re-add the current, correctly compiled version of the .dll:
  CREATE ASSEMBLY YourAssemblyName 
  FROM 'C:\SQLAssemblies\YourAssembly.dll' 
  WITH PERMISSION_SET = SAFE;

Step 3: Verify File Integrity and Permissions on Windows Server 2025

  • Navigate to the assembly’s source folder and confirm the .dll timestamp matches the latest build.
  • Ensure the SQL Server service account has Read & Execute NTFS permissions on the folder via Right-click > Properties > Security in Windows 11 or Windows Server 2025.
  • Clear any cached or orphaned .dll copies in C:\Windows\assembly or temporary deployment folders that might be conflicting with the version SQL Server is attempting to load.

Step 4: Rebuild Dependent Assemblies

  • If the assembly depends on other CLR libraries, rebuild all dependent projects in Visual Studio using matching .NET target framework versions.
  • Re-deploy all dependent assemblies together to avoid field/type version mismatches:
  ALTER ASSEMBLY YourAssemblyName 
  FROM 'C:\SQLAssemblies\YourAssembly.dll';

Alternative or Verification Steps

  • Run a test query or stored procedure that invokes the CLR function/type previously throwing Error 6508, and confirm it executes without exceptions.
  • If the error persists, restart the SQL Server service (net stop MSSQLSERVER && net start MSSQLSERVER) to clear any cached assembly metadata, then repeat Step 2.

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

Troubleshooting Guide: SQL Server Error 6509 – Assembly Metadata Gathering Failure

Why This Error Happens

Error 6509 occurs when SQL Server’s CLR integration engine fails to read or parse metadata from a managed assembly (.dll) during a CREATE ASSEMBLY, ALTER ASSEMBLY, or automatic load operation. This is typically caused by a corrupted or incompatible assembly binary, a mismatch between the .NET runtime version the assembly was compiled against and the version SQL Server 2025 supports, or insufficient file-system/registry permissions preventing the SQL Server service account from accessing the assembly’s dependencies. The accompanying HRESULT value usually points to a COM interop or file-access failure underlying the metadata read.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly File Integrity and Compatibility

  • Confirm the source .dll is not corrupted by copying it to a local folder and inspecting it with ildasm.exe or dotnet-ildasm to ensure metadata loads cleanly outside SQL Server.
  • Check the target framework version the assembly was built against; SQL Server 2025 CLR integration requires assemblies compiled for a supported .NET version (verify against the SQL Server 2025 CLR compatibility matrix).
  • Re-compile the assembly with the correct target framework if a mismatch is found.

Step 2: Check SQL Server CLR Configuration

  • Open a query window and run sp_configure 'clr enabled', 1; RECONFIGURE; to confirm CLR integration is active.
  • Run sp_configure 'clr strict security', 0; temporarily (test environments only) to rule out strict security blocking unsigned/untrusted assemblies, then RECONFIGURE.
  • If strict security is the cause, properly sign the assembly and add it to the trusted assemblies list using sys.sp_add_trusted_assembly with the correct SHA-512 hash.

Step 3: Validate File System and Service Account Permissions

  • Confirm the SQL Server service account (visible in SQL Server Configuration Manager) has Read & Execute permissions on the assembly file and any referenced dependency DLLs.
  • Check the folder path for NTFS permission inheritance issues, especially if the assembly resides on a network share or a path under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\.
  • Use icacls "C:\path\to\assembly.dll" to grant explicit read access to the SQL Server service account if missing.

Step 4: Re-register and Reload the Assembly

  • Drop the problematic assembly using DROP ASSEMBLY [AssemblyName]; if it exists in a broken state.
  • Re-import the binary using CREATE ASSEMBLY [AssemblyName] FROM 'C:\path\to\assembly.dll' WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear any cached metadata handles.

Step 5: Review SQL Server Error Log for the HRESULT Detail

  • Open the SQL Server Error Log (via SSMS > Management > SQL Server Logs) and locate the full Error 6509 entry including the hexadecimal HRESULT.
  • Cross-reference the HRESULT value (e.g., 0x80131107, 0x80070005) against standard Win32/COM error code tables to pinpoint whether it is an access-denied, file-not-found, or bad-image-format failure, then apply the corresponding fix from Steps 1–3.

Alternative or Verification Steps

  • Verify the fix by re-running the CREATE ASSEMBLY statement and querying SELECT * FROM sys.assemblies WHERE name = 'AssemblyName'; to confirm it registers without error.
  • If the issue persists, deploy the assembly on a clean test instance of SQL Server 2025 with default CLR settings to isolate whether the problem is environmental (permissions/config) or intrinsic to the assembly binary itself.

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

Troubleshooting Guide: SQL Server Error 6506 – “Could not find method ‘%s’ for type ‘%s’ in assembly ‘%s'”

Why This Error Happens

This error occurs when the SQL CLR (Common Language Runtime) integration attempts to execute a method inside a registered assembly, but the method signature, name, or type definition no longer matches what SQL Server has cataloged internally. This mismatch is typically caused by an outdated or corrupted assembly being loaded after a DLL was recompiled or updated without re-registering it in SQL Server 2025. It can also occur due to versioning conflicts between the .NET runtime on Windows Server 2025/Windows 11 and the assembly metadata stored in the sys.assemblies system catalog.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly Registration in SQL Server

  • Open SQL Server Management Studio (SSMS) and connect to the instance throwing Error 6506.
  • Run the following query to inspect the assembly details:
  SELECT * FROM sys.assemblies WHERE name = 'YourAssemblyName';
  SELECT * FROM sys.assembly_modules;
  • Confirm the method and type names referenced in the error message actually exist in the current build of the assembly.

Step 2: Drop and Re-register the Outdated Assembly

  • If the assembly code was updated but not reloaded into SQL Server, you must refresh it manually.
  • Run:
  ALTER ASSEMBLY YourAssemblyName
  FROM 'C:\Path\To\UpdatedAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • If ALTER ASSEMBLY fails due to dependent objects, drop and recreate it instead:
  DROP ASSEMBLY YourAssemblyName;
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\Path\To\UpdatedAssembly.dll'
  WITH PERMISSION_SET = SAFE;

Step 3: Validate the .NET Runtime Compatibility

  • Ensure the DLL was compiled against the .NET Framework/CLR version supported by SQL Server 2025 on Windows Server 2025/Windows 11.
  • Check the installed CLR version using:
  SELECT * FROM sys.dm_os_loaded_modules WHERE name LIKE '%clr%';
  • If there’s a version mismatch, recompile the source assembly targeting the correct runtime version and redeploy it.

Step 4: Clear Cached Execution Plans

  • Stale execution plans referencing the old assembly signature can trigger Error 6506 even after re-registration.
  • Run:
  DBCC FREEPROCCACHE;
  • Restart the SQL Server service via Services.msc (SQL Server (MSSQLSERVER)) to fully clear in-memory CLR hosting state.

Step 5: Check File System and Deployment Path Integrity

  • Confirm the DLL file referenced during assembly creation is not corrupted or blocked by Windows.
  • Right-click the DLL file in File Explorer → Properties → Unblock (under the General tab), since Windows Server 2025 may flag externally sourced DLLs.
  • Re-deploy the DLL to a trusted local directory before re-running the CREATE ASSEMBLY statement.

Alternative or Verification Steps

  • After re-registering the assembly, execute the exact stored procedure or CLR function that previously failed and confirm no Error 6506 appears in the SQL Server Error Log (SQL Server Logs folder or via EXEC sp_readerrorlog).
  • If the issue persists, drop all dependent CLR objects, fully remove the assembly with DROP ASSEMBLY ... WITH CASCADE, and perform a clean reinstall of the assembly from a freshly compiled DLL to rule out catalog corruption.

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

Troubleshooting Guide: SQL Server Error 6507 – “Failed to Open Malformed Assembly”

Why This Error Happens

This error occurs when SQL Server’s CLR integration engine attempts to load a .NET assembly (DLL) into the database but finds that the binary is corrupted, truncated, or was compiled with an incompatible .NET runtime version. It can also surface when the assembly bytes stored in sys.assembly_files have been damaged due to a failed deployment, disk-level corruption, or an interrupted CREATE ASSEMBLY transaction. Additionally, security policies like Windows Defender Application Control (WDAC) or antivirus software may quarantine or strip portions of the file before SQL Server reads it into memory.

Step-by-Step Resolution Guide

Step 1: Verify the Source Assembly Integrity

  • Locate the original .dll file on disk (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\) and confirm its file size matches the build output.
  • Run Get-FileHash -Path "C:\Deploy\MyAssembly.dll" -Algorithm SHA256 in PowerShell and compare it against the hash from your build server or source control.
  • If the hash doesn’t match or the file size is 0 KB, the file is corrupted and must be rebuilt or re-copied.

Step 2: Re-register the Assembly in SQL Server

  • Drop the broken assembly reference using DROP ASSEMBLY MyAssembly; (ensure no dependent objects are blocking this first).
  • Re-import the clean binary using:
  CREATE ASSEMBLY MyAssembly
  FROM 'C:\Deploy\MyAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • If deploying via Visual Studio, use Build > Deploy again to push a fresh binary rather than relying on a cached DLL.

Step 3: Check .NET Runtime Compatibility

  • Confirm the assembly was compiled targeting a CLR version supported by SQL Server 2025 (CLR 4.0/.NET Framework compatible, not a raw .NET 6+/.NET 8 assembly unless using the updated SQLCLR hosting model).
  • Open the .csproj file and verify the <TargetFramework> tag matches a supported runtime.
  • Recompile the project if an unsupported target framework (like net8.0-windows) was used instead of the required compatibility shim.

Step 4: Rule Out Security Software Interference

  • Check Windows Defender or third-party AV quarantine logs for the DLL filename around the timestamp of the error.
  • Add an exclusion path in Windows Security for your SQL Server deployment folder:
  • Go to Windows Security > Virus & threat protection > Manage settings > Exclusions.
  • Add the folder path where assemblies are staged before deployment.

Alternative or Verification Steps

  • Run SELECT * FROM sys.assembly_files; and SELECT * FROM sys.assemblies; to confirm the assembly now shows a valid, non-null content size and current timestamp.
  • If the error persists, bypass disk caching entirely by deploying the assembly directly via a VARBINARY(MAX) literal insert instead of a file path, which eliminates file-system-level corruption as a variable.

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

Troubleshooting Guide: Error 6504 in SQL Server 2025

Why This Error Happens

Error 6504 occurs when a computed column, function, or view attempts to return a NULL value for a column or expression that has been explicitly defined with a NOT NULL constraint or schema-bound restriction. This typically happens after a schema change, a faulty user-defined function (UDF), or a corrupted view definition that no longer aligns with the underlying table’s constraints. It can also surface when extended properties or system metadata catalogs become inconsistent following an in-place upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object

  • Open SQL Server Management Studio (SSMS) and check the full error message for the specific table and column names (replacing the %.*ls placeholders).
  • Run the following query to locate schema-bound views or functions referencing that column:
  SELECT referencing_schema_name, referencing_entity_name 
  FROM sys.dm_sql_referencing_entities('dbo.YourTableName', 'OBJECT');
  • Check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the exact timestamp of the failure.

Step 2: Validate Column Constraints and Data Types

  • Script out the table definition and verify if the column in question was recently altered to NOT NULL without a DEFAULT constraint.
  • Check for orphaned computed columns:
  SELECT name, is_nullable, is_computed 
  FROM sys.columns 
  WHERE object_id = OBJECT_ID('dbo.YourTableName');
  • If using computed columns, ensure the underlying formula cannot mathematically result in a NULL (e.g., check for unguarded NULL + NULL logic).

Step 3: Repair or Refresh Metadata

  • Navigate to the specific schema-bound view and refresh it to sync metadata with the underlying table structure:
  EXEC sp_refreshview 'dbo.YourViewName';
  • If the issue stems from a corrupted system catalog (common after OS-level Windows Server 2025 updates), run DBCC CHECKDB on the specific database to rule out corruption:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 4: Adjust Application-Side Null Handling

  • If the error originates from an ORM (like Entity Framework) running on Windows 11, check the .edmx or model configuration to ensure the application model matches the SQL Server nullability settings.
  • Update the application code to use ISNULL() or COALESCE() wrappers in the Stored Procedure to catch unexpected logic flow errors before they reach the strict NOT NULL column.

Alternative or Verification Steps

  • Verification: Re-run the specific transaction or SELECT statement that triggered the error. If successful, check the SQL Server Error Log via EXEC sp_readerrorlog; to confirm Error 6504 is no longer being logged.
  • Alternative: If the error persists due to a corrupted view, drop and recreate the view entirely using DROP VIEW followed by a fresh CREATE VIEW statement rather than relying on ALTER VIEW.

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

Why This Error Happens

Error 6505 occurs when SQL Server’s CLR integration engine cannot locate a specific class or type definition inside a registered assembly (.DLL). This typically happens because the assembly metadata in the sys.assemblies catalog is out of sync with the actual binary file, often due to a partial update, a renamed namespace, or a mismatched build (e.g., deploying a Debug build when the catalog expects a Release build signature). It can also occur if the assembly was altered on disk after being registered, corrupting the internal mapping between the SQL object and the compiled Type.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly Registration in the Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025.
  • Run the following query to check the current state of the assembly: SELECT name, clr_name, permission_set_desc FROM sys.assemblies WHERE name = 'YourAssemblyName';
  • Confirm the clr_name matches the expected namespace and class structure of your compiled code.

Step 2: Drop and Re-register the Assembly

  • Since a simple ALTER ASSEMBLY often fails to update internal type caches correctly, perform a clean drop: DROP ASSEMBLY YourAssemblyName;
  • Re-create it using the CREATE ASSEMBLY command, pointing explicitly to the updated binary path: CREATE ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure the file path is accessible by the SQL Server service account (check NTFS permissions on the folder in Windows 11/Server 2025).

Step 3: Validate the DLL Build Configuration

  • Check that the compiled DLL does not have mismatched namespaces; open the project in Visual Studio and confirm the public class name matches exactly what is referenced in the CREATE FUNCTION or CREATE PROCEDURE T-SQL statement (e.g., EXTERNAL NAME YourAssembly.[Namespace.ClassName].MethodName).
  • Rebuild the solution in Release mode to ensure no debug-specific symbols are causing a mismatch.
  • Redeploy the newly built .dll file to the server, overwriting the previous version in the C:\SQLAssemblies\ directory.

Step 4: Restart the SQL Server CLR Host

  • Restart the SQL Server (MSSQLSERVER) service via the Services console (services.msc) or SQL Server Configuration Manager to clear the cached CLR AppDomain.
  • This forces SQL Server to reload the assembly metadata fresh upon the next connection attempt.

Alternative or Verification Steps

  • To verify the fix, execute the specific stored procedure or function again and confirm Error 6505 no longer appears in the SQL Server Error Log (SQL Server Management Studio > Management > SQL Server Logs).
  • If the error persists, use a decompiler tool (like ILSpy) on the deployed .dll to physically confirm the Type and Namespace exist exactly as referenced in the T-SQL EXTERNAL NAME clause, as a typo in casing (Case Sensitivity) is a common hidden cause.

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

Why This Error Happens

Error 6502 occurs when SQL Server attempts to load a CLR assembly (via CREATE ASSEMBLY or ALTER ASSEMBLY) but cannot physically access the DLL file specified in the path. This is typically caused by the SQL Server service account lacking NTFS read permissions on the file or folder, the file being moved/deleted after the statement was issued, or the path being an inaccessible UNC/network share that the service account cannot authenticate against. It can also occur if the file is locked by another process, is corrupted, or if Windows Defender/antivirus software is actively blocking access to the .dll file.

Step-by-Step Resolution Guide

Step 1: Verify the File Path and Existence

  • Confirm the exact path referenced in the error message exists on disk (check for typos, trailing spaces, or incorrect drive letters).
  • Open File Explorer or run dir "C:\Path\To\Assembly.dll" in Command Prompt to confirm the file is present.
  • If the path is a UNC share (e.g., \\Server\Share\Assembly.dll), ping the host and confirm share visibility from the SQL Server machine itself, not just your workstation.

Step 2: Grant NTFS Permissions to the SQL Server Service Account

  • Open Services.msc on Windows Server 2025 and note the exact logon account used by the SQL Server (MSSQLSERVER) service.
  • Right-click the folder containing the DLL → Properties → Security tab → Edit → Add.
  • Grant the SQL Server service account (e.g., NT Service\MSSQLSERVER or a domain service account) Read & Execute permissions.
  • Apply changes and restart the SQL Server service via net stop MSSQLSERVER && net start MSSQLSERVER if permissions were modified while the service was running.

Step 3: Check for File Locks or Antivirus Interference

  • Use Resource Monitor (resmon.exe) → CPU tab → Associated Handles to search for the DLL filename and identify any process locking it.
  • Temporarily disable Windows Defender real-time protection or add an exclusion for the assembly folder:
  • Add-MpPreference -ExclusionPath "C:\Path\To\Assembly.dll" (run in elevated PowerShell).
  • Re-attempt the CREATE ASSEMBLY statement after clearing the lock or exclusion.

Step 4: Validate the Assembly File Integrity

  • Confirm the DLL is not corrupted by copying it to another machine and inspecting it with dumpbin /headers Assembly.dll or re-deploying a fresh copy from source control/build output.
  • If the file was transferred via FTP or email, re-transfer using binary mode to avoid corruption.

Step 5: Re-run the CREATE/ALTER ASSEMBLY Statement

  • Execute the original T-SQL command again from SQL Server Management Studio (SSMS) using an account with CREATE ASSEMBLY permissions.
  • Example: CREATE ASSEMBLY MyAssembly FROM 'C:\Path\To\Assembly.dll' WITH PERMISSION_SET = SAFE;

Alternative or Verification Steps

  • After applying fixes, verify success by querying SELECT * FROM sys.assemblies WHERE name = 'MyAssembly'; to confirm the assembly loaded without error.
  • If permissions-based fixes fail, use the FROM (varbinary) syntax instead of a file path—read the DLL into a variable using OPENROWSET(BULK ... , SINGLE_BLOB) and pass it directly to CREATE ASSEMBLY, bypassing file-system access issues entirely.

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

Troubleshooting Guide: SQL Server Error 6503 – “Assembly was not found in the SQL catalog”

Why This Error Happens

This error occurs when a SQL Server CLR (Common Language Runtime) assembly reference exists in a database object, such as a trigger, function, or stored procedure, but the actual assembly metadata has been removed or corrupted in the sys.assemblies catalog view. This mismatch commonly happens after a database restore from a different server, a failed deployment of a SQLCLR project, or manual deletion of an assembly without first dropping its dependent objects. In some cases, replication or database mirroring can also cause catalog desynchronization between the primary and secondary instances.

Step-by-Step Resolution Guide

Step 1: Verify Assembly Existence in the Catalog

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check if the assembly is registered: SELECT * FROM sys.assemblies WHERE name = 'YourAssemblyName';
  • If the result set is empty, the assembly is confirmed missing from the catalog, validating Error 6503.

Step 2: Re-register the Missing Assembly

  • Locate the original .dll file for the assembly on disk (commonly found in your Visual Studio project’s bin\Release or bin\Debug folder).
  • Copy the .dll to a trusted path on the server, such as C:\SQLAssemblies\.
  • Execute the CREATE ASSEMBLY command in a new query window:
    CREATE ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure the PERMISSION_SET matches the original configuration (SAFE, EXTERNAL_ACCESS, or UNSAFE).

Step 3: Rebuild Dependent Database Objects

  • Identify any stored procedures, triggers, or functions that reference the assembly using sys.sql_modules.
  • Drop and recreate these objects to force SQL Server to re-link them to the newly registered assembly.
  • Run: DROP PROCEDURE dbo.YourCLRProcedure; GO followed by the original CREATE PROCEDURE ... EXTERNAL NAME YourAssemblyName.ClassName.MethodName; script.

Step 4: Check CLR Integration Configuration

  • Confirm that CLR integration is enabled on the instance, as a disabled configuration can sometimes mask or compound catalog errors.
  • Run: sp_configure 'clr enabled', 1; RECONFIGURE;
  • On Windows Server 2025, verify that .NET Framework 4.8 or the required runtime components are still present via “Add Roles and Features” in Server Manager.

Alternative or Verification Steps

  • To verify the fix, execute the dependent stored procedure or function manually; it should run without raising Error 6503, and sys.assemblies should now list the correct assembly_id.
  • If the error persists, restore the specific assembly file from a known-good backup of the master or user database using RESTORE DATABASE ... WITH REPLACE, ensuring you are not overwriting unrelated schema changes made since the backup was taken.

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

Troubleshooting Guide: SQL Server Error 6500 — CLR Method Return Type Mismatch

Why This Error Happens

This error occurs when a SQLCLR (Common Language Runtime) function, procedure, or trigger registered inside SQL Server returns a .NET data type that does not match the type expected by the SQL Server engine. This typically results from an outdated or mismatched assembly DLL being registered against a method signature that has since changed, or from an incompatible serialization format between the CLR object and the corresponding SQL type. It can also occur after an in-place upgrade to SQL Server 2025, where stricter type-checking rules reject return types that were previously tolerated in older engine versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Method

  • Open SQL Server Management Studio (SSMS) and run the following query to find the exact object referencing the CLR assembly: SELECT * FROM sys.assembly_modules;
  • Cross-reference the %ls placeholders in the error message (method name, class name, assembly name) with the output to pinpoint the exact function or procedure.
  • Check the Windows Event Viewer under Applications and Services Logs > Microsoft > SQL Server for the full stack trace tied to Event ID 6500.

Step 2: Validate and Rebuild the Assembly Source Code

  • Open the original Visual Studio / .NET project used to build the assembly DLL.
  • Confirm the method’s return type explicitly maps to a valid SQL Server-compatible type (e.g., use SqlInt32 instead of plain int, or SqlString instead of string).
  • Rebuild the project targeting .NET Framework/Core version compatible with SQL Server 2025 CLR integration (verify via SELECT compatibility_level FROM sys.databases;).
  • Save the newly compiled .dll file to a secure path, such as C:\SQLAssemblies\UpdatedAssembly.dll.

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

  • Disable strict CLR strict security temporarily if needed for testing (not recommended for production): EXEC sp_configure 'clr strict security', 0; RECONFIGURE;
  • Drop the old assembly: DROP ASSEMBLY [YourAssemblyName];
  • Re-import the fixed assembly: CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\SQLAssemblies\UpdatedAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 4: Verify Permission Sets and Trust Configuration

  • Ensure the assembly’s permission set (SAFE, EXTERNAL_ACCESS, or UNSAFE) matches what the method actually requires at runtime.
  • If using UNSAFE, confirm the assembly is signed and added to the trusted assemblies list: EXEC sys.sp_add_trusted_assembly @hash = <hash_value>, @description = N'Trusted CLR Assembly';
  • Re-run the failing stored procedure or function to confirm the error no longer triggers.

Alternative or Verification Steps

  • Run SELECT * FROM sys.dm_exec_describe_first_result_set(N'EXEC YourProcedureName') to confirm the returned result set matches the expected schema types without throwing Error 6500.
  • If the error persists, bypass the CLR integration entirely by rewriting the logic as a native T-SQL function, which eliminates CLR-to-SQL type mapping issues altogether.

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

Troubleshooting Guide: SQL Server Error 6501 – CREATE/ALTER ASSEMBLY Failed

Why This Error Happens

This error occurs when SQL Server 2025 cannot physically access the DLL or assembly file specified in the CREATE ASSEMBLY or ALTER ASSEMBLY statement, typically because the SQL Server service account lacks NTFS read permissions on the file or folder. It can also result from an incorrect file path, a file that has been moved or deleted, or the file being locked by another process, antivirus software, or Windows Defender’s enhanced scanning features on Windows Server 2025. Additionally, if the assembly resides on a network share (UNC path), authentication or firewall restrictions between the SQL Server host and the file server can block access.

Step-by-Step Resolution Guide

Step 1: Verify the File Path and Existence

  • Confirm the exact path used in your CREATE ASSEMBLY ... FROM 'path' statement matches the actual file location.
  • Open File Explorer or run dir "C:\SQLAssemblies\YourAssembly.dll" in Command Prompt to confirm the file exists.
  • Check for typos, incorrect drive letters, or case-sensitivity issues if using a mapped network path.

Step 2: Grant NTFS Permissions to the SQL Server Service Account

  • Identify the service account running SQL Server via SQL Server Configuration Manager > SQL Server Services.
  • Right-click the folder containing the DLL (e.g., C:\SQLAssemblies\) > Properties > Security tab.
  • Add the service account (e.g., NT Service\MSSQLSERVER or a custom domain account) and grant Read & Execute permissions.
  • Click Apply, then restart the SQL Server service for permissions to take effect.

Step 3: Check for File Locks or Antivirus Interference

  • Use Resource Monitor (resmon.exe) on Windows Server 2025 to check if another process has locked the DLL file.
  • Temporarily disable Windows Defender real-time protection or add an exclusion for the assembly folder via Windows Security > Virus & threat protection > Exclusions.
  • Re-attempt the CREATE ASSEMBLY command after confirming no lock exists.

Step 4: Validate Network Share Access (If Applicable)

  • If the DLL is hosted on a UNC path (e.g., \\FileServer\Assemblies\MyAssembly.dll), ensure the SQL Server service account has both share-level and NTFS-level read permissions.
  • Test connectivity using Test-NetConnection -ComputerName FileServer -Port 445 in PowerShell to rule out firewall blocking SMB traffic.
  • Consider copying the file locally to the SQL Server host as a workaround if network latency or authentication (Kerberos double-hop) is suspected.

Step 5: Rebuild or Replace a Corrupted Assembly File

  • If permissions and paths are correct but the error persists, the DLL file itself may be corrupted.
  • Recompile the assembly from source code and redeploy it to the target directory.
  • Verify file integrity using Get-FileHash "C:\SQLAssemblies\YourAssembly.dll" in PowerShell and compare against a known-good build.

Alternative or Verification Steps

  • Run the CREATE ASSEMBLY statement again from SQL Server Management Studio (SSMS) and confirm it completes without Error 6501; then verify with SELECT * FROM sys.assemblies WHERE name = 'YourAssemblyName';.
  • As an alternative, import the assembly as a binary value directly using CREATE ASSEMBLY ... FROM 0x... (hex byte stream) to bypass file system permission issues entirely.

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

Troubleshooting Guide: SQL Server Error 6399 — Selective XML Index Path Dependency Conflict

Why This Error Happens

This error occurs because the selective XML index path you are attempting to drop is a shared dependency used by one or more secondary selective XML indexes defined on the same XML column. SQL Server enforces a strict dependency hierarchy where primary selective XML index paths cannot be removed while secondary indexes still reference them, in order to prevent orphaned or corrupted index structures. This typically happens during schema refactoring, index maintenance scripts, or automated deployment pipelines that attempt to drop paths out of order.

Step-by-Step Resolution Guide

Step 1: Identify All Dependent Secondary Indexes

  • Query sys.selective_xml_index_paths and sys.xml_indexes to find all secondary selective XML indexes associated with the same primary XML index.
  • Use the following query to list dependencies:
SELECT xi.name AS IndexName, sxip.path, xi.secondary_type_desc
FROM sys.xml_indexes xi
JOIN sys.selective_xml_index_paths sxip 
    ON xi.object_id = sxip.object_id AND xi.index_id = sxip.index_id
WHERE xi.object_id = OBJECT_ID('YourTableName');
  • Note the names of every secondary index referencing the path you intend to remove.

Step 2: Drop Secondary Indexes First

  • Drop each dependent secondary selective XML index before touching the primary path.
  • Use the standard DROP INDEX syntax for each identified index:
DROP INDEX SecondaryIndexName ON YourTableName;
  • Repeat for all secondary indexes listed in Step 1 to clear the dependency chain.

Step 3: Drop the XML Path from the Primary Index

  • Once no secondary indexes reference the path, drop the XML path using sp_xml_remove_selective_index_path or the appropriate ALTER INDEX statement.
  • Example:
EXEC sp_xml_remove_selective_index_path 
    @object_name = 'YourTableName', 
    @path = '/your/xml/path';
  • Confirm no errors are returned during execution.

Step 4: Rebuild or Recreate Secondary Indexes (If Needed)

  • If the secondary indexes are still required for query performance, recreate them using updated paths that do not reference the removed path.
  • Validate the new index definitions against your current XML schema collection.
  • Run DBCC CHECKDB or DBCC CHECKTABLE on the affected table to ensure structural integrity after index changes.

Alternative or Verification Steps

  • Re-run the query from Step 1 against sys.selective_xml_index_paths to confirm the path no longer appears and no orphaned secondary index references remain.
  • If the error persists, check for cached execution plans or open transactions holding schema locks on the table using sys.dm_tran_locks, and retry the drop operation after clearing active sessions.

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

Why This Error Happens

Error 6401 occurs when a ROLLBACK TRANSACTION or ROLLBACK WORK statement references a transaction or savepoint name that does not exist in the current session’s transaction stack. This typically happens due to a mismatch in nested transaction naming, a savepoint being created in a different connection/session scope, or application code that attempts to roll back after a transaction has already been committed or rolled back implicitly (such as after a severe error or connection reset). It can also surface when connection pooling reuses a session that has lost its transaction context.

Step-by-Step Resolution Guide

Step 1: Audit the Transaction and Savepoint Names in Code

  • Open the stored procedure, trigger, or application code referencing the failing transaction name.
  • Verify that SAVE TRANSACTION savepoint_name and ROLLBACK TRANSACTION savepoint_name use identical, case-sensitive string values.
  • Check for typos or dynamically generated names (e.g., via string concatenation) that may not match at runtime.

Step 2: Check for Premature Transaction Completion

  • Review @@TRANCOUNT before the rollback statement using PRINT @@TRANCOUNT for debugging.
  • Confirm that no prior COMMIT or ROLLBACK has already closed the transaction before the named rollback executes.
  • Inspect TRY...CATCH blocks to ensure error handling logic does not fire multiple rollback attempts on the same transaction.

Step 3: Validate Connection and Session Scope

  • Ensure the savepoint was created and is being rolled back within the exact same database connection/session (SPID).
  • Check Connection Pooling settings in your application’s connection string, located typically in web.config or appsettings.json, since pooled connections can reset transaction context unexpectedly.
  • If using MARS (Multiple Active Result Sets), verify that MultipleActiveResultSets=True in the connection string is not causing transaction state conflicts across batches.

Step 4: Review SQL Server Error Logs

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025.
  • Search for Error 6401 timestamps and correlate them with the specific query or stored procedure execution to isolate the failing transaction block.
  • Enable Trace Flag 3604 temporarily in SQL Server Configuration Manager to output additional transaction diagnostics to the console if reproducing in a test environment.

Alternative or Verification Steps

  • Run the corrected stored procedure or script manually in SQL Server Management Studio (SSMS) and confirm @@TRANCOUNT returns to 0 after execution without triggering Error 6401.
  • If the issue persists intermittently, wrap rollback logic in a conditional check such as IF XACT_STATE() = -1 ROLLBACK TRANSACTION savepoint_name to prevent rollback attempts on already-doomed or completed transactions.

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

Troubleshooting Guide: SQL Server Error 6397 – Selective XML Index Path Too Deep

Why This Error Happens

Error 6397 occurs when you attempt to create a selective XML index (SXI) on an XML column using an XQuery path expression that exceeds the maximum supported nesting depth allowed by SQL Server’s XML indexing engine. This limitation exists because the internal node table structure used by selective XML indexes relies on a fixed-depth path tokenization scheme, and paths beyond this threshold cannot be reliably mapped to the internal B-tree representation. This typically happens when XML schemas have deeply nested elements (common in SOAP payloads, configuration files, or hierarchical business documents) and a promoted path or selective path is defined too far down the tree.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path Definition

  • Open the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX ... FOR ... (PATH) statement that triggered the error.
  • Review the full error text, which includes the exact path string (e.g., /Root/Level1/Level2/.../Level20/Value) and the maximum allowed depth value %d.
  • Count the number of / segments in the reported path to confirm how far it exceeds the limit.

Step 2: Shorten or Restructure the XML Path Expression

  • Edit the T-SQL script containing the PATH (N'...') clause for the selective XML index.
  • Reduce the depth by targeting a higher-level ancestor node instead of the deeply nested leaf node, if business logic allows.
  • Example: Change PATH (N'/Root/A/B/C/D/E/F/G/H/I/J/K/Value') to a shallower equivalent like PATH (N'/Root/A/B/C/D/E/Value') if the XML schema can be flattened.
  • If the deep path is required for querying, consider using a standard XML PRIMARY XML INDEX with a secondary PATH index instead of a selective XML index, since standard indexes do not enforce this depth restriction.

Step 3: Flatten the XML Schema Where Possible

  • Open SQL Server Management Studio (SSMS) and review the XML schema collection bound to the column (sys.xml_schema_collections).
  • Work with application developers to redesign the XML document structure to reduce unnecessary nesting levels before ingestion.
  • Use XQuery transformations (via nodes() and value()) at the application tier to pre-flatten data if schema redesign is not feasible.

Step 4: Recreate the Selective XML Index

  • Drop the failed index definition if a partial object was created: DROP XML INDEX [IndexName] ON [dbo].[TableName];
  • Re-run the corrected CREATE SELECTIVE XML INDEX statement with the shortened path(s).
  • Confirm the script completes without raising Error 6397 in SSMS “Messages” tab.

Step 5: Validate Index Depth Limits Documentation

  • Cross-check the maximum depth value reported in the error against Microsoft’s official SQL Server 2025 documentation for selective XML indexes.
  • Ensure no other promoted paths in the same index definition also violate the limit before resubmitting the full script.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths to confirm the new path entries were registered successfully without errors.
  • If restructuring the XML is not an option, use a traditional Primary/Secondary XML Index combination instead of a Selective XML Index, as it does not impose the same path-depth restriction.

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

Troubleshooting Guide: SQL Server Error 6398 – Selective XML Index MAXLENGTH Out of Range

Why This Error Happens

This error occurs when creating or altering a Selective XML Index (SXI) and the MAXLENGTH option specified for a given XML path exceeds the permissible boundary enforced by SQL Server’s internal path-promotion engine. SQL Server 2025 validates the MAXLENGTH value against the data type used to store the promoted node (for example, nvarchar or varbinary), and any value outside the allowed byte range triggers a hard validation failure before the index is built. This is typically caused by a copy-pasted T-SQL script with a value from a different schema, a manual typo, or an attempt to set MAXLENGTH larger than the maximum supported row/column size for the chosen data type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path and Current Value

  • Open the exact CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX statement that triggered Error 6398.
  • Locate the specific XML path referenced in the error message (the %.*ls placeholder will show the actual path, e.g., /Root/Customer/@id).
  • Note the current MAXLENGTH value assigned to that path in your WITH (PATHS (...)) clause.

Step 2: Check the Allowed Range in the Error Output

  • Re-run the failing script in SQL Server Management Studio (SSMS) and capture the full error text, which includes the two bounding numbers (%d - %d).
  • For most promoted scalar types in SQL Server 2025, the valid range is typically 1 through 4000 for nvarchar-based promotions, or up to 8000 for varbinary/varchar based types — confirm using the exact numbers from your error message since this can vary by data type.
  • Cross-reference the path’s declared SQL_TYPE in your index definition (e.g., AS SQL nvarchar(100)) since MAXLENGTH must stay within that type’s storage ceiling.

Step 3: Correct the MAXLENGTH Value in the Index Definition

  • Edit the T-SQL script and adjust the MAXLENGTH parameter to fall within the reported valid range.
  • Example fix:
CREATE SELECTIVE XML INDEX SXI_Orders
ON dbo.OrdersTable (XmlColumn)
FOR XML INDEX PXML_Orders
PATHS
(
    '/Root/Customer/@id' AS SQL nvarchar(100) MAXLENGTH 100
)
  • Ensure the MAXLENGTH value matches or is smaller than the declared SQL nvarchar(n) / varbinary(n) length to avoid truncation conflicts.

Step 4: Drop and Recreate the Index

  • If the Selective XML Index partially exists from a failed creation attempt, drop it first:
DROP XML INDEX IF EXISTS SXI_Orders ON dbo.OrdersTable;
  • Re-execute the corrected CREATE SELECTIVE XML INDEX statement.

Step 5: Validate Server and Database Compatibility Level

  • Confirm the database is running at a compatibility level that supports Selective XML Indexes (130 or higher) using:
SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is outdated, update it with ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; (adjust to your SQL Server 2025 supported level) and retry the index creation.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths to confirm the path was registered successfully with the corrected max_length value: SELECT * FROM sys.selective_xml_index_paths WHERE path_id = (SELECT object_id FROM sys.indexes WHERE name = 'SXI_Orders');
  • If the error persists despite correct values, rebuild the underlying XML schema collection (if one is bound to the column) and retry, as a stale or corrupted XML Schema Collection can sometimes cause SQL Server to miscalculate allowed length boundaries.

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

Troubleshooting Guide: SQL Server Error 6394 — Selective XML Index Non-Leaf Element Conflict

Why This Error Happens

This error occurs when the Selective XML Index (SXI) engine encounters an XML path where a node expected to be a leaf (containing scalar data) is instead found to contain nested child elements or mixed content. This typically happens because the underlying XML data violates the schema assumptions defined in the selected XML index paths, often due to inconsistent or malformed XML being inserted after the index was created. It can also result from a corrupted or outdated selective index definition that no longer matches the structural reality of the XML column’s content.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data and Index

  • Run the failing query or transaction in isolation to capture the full error message, noting the %.*ls path and the selective XML index name.
  • Query sys.selective_xml_index_paths and sys.xml_indexes to cross-reference the index definition against the reported path.
  • Use SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('YourTable') to confirm the index type and status.

Step 2: Validate and Correct the XML Document Structure

  • Extract the specific XML instance(s) using SELECT YourXmlColumn FROM YourTable WHERE PrimaryKey = <id> for the row referenced in the error.
  • Check whether the node at the reported path contains child elements or mixed content when the index promotion rule expects a scalar (leaf) value.
  • Correct the source XML generation logic (application, ETL job, or stored procedure) so that it consistently produces leaf nodes at that path, or update the index definition to treat it as a non-leaf path.

Step 3: Drop and Rebuild the Selective XML Index

  • Drop the affected index: DROP INDEX [SXI_IndexName] ON [dbo].[YourTable];
  • Recreate it with corrected path definitions in the WITH XMLNAMESPACES and FOR clauses, ensuring promoted paths match actual document structure.
  • Example: CREATE SELECTIVE XML INDEX [SXI_IndexName] ON [dbo].[YourTable] ([XmlColumn]) FOR ([PromotedPath1], [PromotedPath2]);
  • Rebuild with ALTER INDEX [SXI_IndexName] ON [dbo].[YourTable] REBUILD; if the path definitions remain valid but the index appears stale.

Step 4: Check for Corruption via DBCC

  • Run DBCC CHECKTABLE('YourTable') WITH ALL_ERRORMSGS, DATA_PURITY; to rule out physical corruption contributing to inconsistent index metadata.
  • Review the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for correlated I/O or consistency warnings around the same timeframe.

Alternative or Verification Steps

  • Re-run the original query or transaction that triggered Error 6394; if it completes without exception and sys.dm_db_index_physical_stats shows a healthy state for the index, the fix is verified.
  • If the error persists, drop the selective XML index entirely and rely on a standard primary XML index temporarily, then re-engineer the SXI path schema in a test environment before reapplying it to production.

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

Troubleshooting Guide: SQL Server Error 6395 – Secondary Selective XML Index Key Length Exceeded

Why This Error Happens

This error occurs because the combined key length of indexed XML path values in a Selective XML Index (SXI) secondary index exceeds the maximum allowable byte limit enforced by SQL Server 2025. SQL Server imposes this ceiling to maintain B-tree page efficiency, so when XML node values at the specified path are too large (often due to wide VARCHAR/NVARCHAR promotions or deeply nested, verbose XML content), the index creation or update operation fails. This is not a corruption issue but a schema/data design constraint triggered by unusually large or unbounded XML element values being promoted into the index.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Path and Data

  • Run sys.selective_xml_index_paths and sys.xml_indexes to locate the exact path (%.*ls) referenced in the error message.
  • Use SELECT xmlcolumn.query('<path>') against the affected table to identify which rows contain oversized values at that node.
  • Check the actual byte length using DATALENGTH() on the extracted node values to confirm they exceed the reported maximum (commonly 900 bytes for standard indexes, or up to 1700 bytes depending on configuration).

Step 2: Reduce or Restructure the Indexed Path’s Data Type

  • Open SQL Server Management Studio (SSMS) and navigate to the Selective XML Index definition via Object Explorer > Databases > [YourDB] > Tables > [YourTable] > Indexes.
  • Modify the XML Schema Collection or promoted type for that path to use a smaller fixed-length type (e.g., change xs:string without length restriction to a bounded xs:string with maxLength facet).
  • If the path is a promoted scalar, recreate the Selective XML Index specifying a smaller explicit type:
  DROP XML INDEX SXI_YourIndex ON dbo.YourTable;
  CREATE SELECTIVE XML INDEX SXI_YourIndex ON dbo.YourTable (XmlColumn)
  FOR ('/path/to/node' AS SQL VARCHAR(450) SINGLETON);

Step 3: Exclude or Filter Oversized XML Fragments

  • If large values are legitimate business data (e.g., embedded Base64 blobs or large text nodes), exclude that specific path from promotion using a filtered XML index definition.
  • Use WHERE clause filtering in the index path configuration file (.xsx promotion config) to skip nodes exceeding the byte threshold.
  • Alternatively, store oversized XML fragments in a separate VARBINARY(MAX) column outside the indexed XML structure.

Step 4: Rebuild the Selective XML Index

  • Execute ALTER INDEX SXI_YourIndex ON dbo.YourTable REBUILD; after making schema changes.
  • Monitor the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for confirmation that the rebuild completes without recurrence of Error 6395.

Alternative or Verification Steps

  • Verify the fix by querying sys.dm_db_index_physical_stats to confirm the index is in a healthy, non-fragmented state and re-run the original INSERT/UPDATE operation that triggered the error.
  • If restructuring the XML schema isn’t feasible, consider disabling selective promotion for that specific path and rely on a standard Primary/Secondary XML Index with full-document indexing instead.

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

Why This Error Happens

This error occurs because Microsoft SQL Server enforces a hard limit of 1,000 promoted paths per selective XML index, and your current index definition has exceeded that threshold. Selective XML indexes rely on “promoted paths” to extract specific XQuery node values into relational columns for faster querying, but each distinct path counted against the index contributes to this ceiling. This typically happens when applications or scripts dynamically add promoted paths in a loop, or when an XML schema has significantly more unique element/attribute paths than originally anticipated during index design.

Step-by-Step Resolution Guide

Step 1: Audit Existing Promoted Paths

  • Query the sys.selective_xml_index_paths catalog view to list every promoted path currently registered for the index in question.
  • Run: SELECT * FROM sys.selective_xml_index_paths WHERE xml_index_id = (SELECT index_id FROM sys.indexes WHERE name = 'YourIndexName');
  • Identify redundant, unused, or auto-generated paths that are no longer required by current queries.

Step 2: Drop and Consolidate Unnecessary Paths

  • Use DROP XML INDEX or the ALTER INDEX ... DROP XML PATH syntax (via sp_xml_index_path management scripts) to remove paths that are not actively used in WHERE clauses or JOIN predicates.
  • Consider consolidating similar paths using wildcard XQuery expressions (e.g., //Item/* instead of multiple explicit child paths) to reduce the total path count.
  • Save a backup script of the current index definition before dropping paths: sp_helptext 'YourIndexName' or script via SSMS Object Explorer.

Step 3: Rebuild the Selective XML Index with Optimized Paths

  • Drop the existing selective XML index entirely using DROP INDEX YourIndexName ON YourTable;.
  • Recreate the index with CREATE SELECTIVE XML INDEX, explicitly listing only the essential promoted paths (staying well under the 1,000-path limit) alongside a supporting secondary XML index if broader coverage is still needed.
  • On Windows Server 2025/Windows 11, ensure the SQL Server service account has sufficient %TEMP% disk space (check C:\Windows\Temp or the configured tempdb location) since large index rebuilds generate heavy temporary I/O.

Step 4: Split XML Workload Across Multiple Indexes

  • If your schema genuinely requires more than 1,000 distinct paths, split the XML column indexing strategy across multiple selective XML indexes, each handling a logical subset of paths (e.g., one index per XML namespace or document section).
  • Update application queries to reference the correct index hints if necessary.

Alternative or Verification Steps

  • After rebuilding, run DBCC CHECKCONSTRAINTS and re-execute the original failing query or index creation script to confirm Error 6396 no longer appears in SQL Server Error Logs or Event Viewer (Applications and Services Logs > MSSQLSERVER).
  • If the path count still exceeds limits after optimization, consider replacing the selective XML index with a standard Primary/Secondary XML Index combination, which does not impose the same 1,000-path promotion restriction.

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

Troubleshooting Guide: SQL Server Error 6392 – Secondary Selective XML Index Path Restriction

Why This Error Happens

This error occurs because SQL Server’s Selective XML Indexes (SXI) feature does not allow a secondary index to be created on a path that resolves to a generic node() type. When a path expression in the selective XML index definition uses node() instead of a specific element or attribute type, SQL Server cannot determine a concrete data type for indexing, which violates the schema requirements for secondary SXI indexes. This typically happens when the XML Schema Collection associated with the column is incomplete, overly generic, or when the path promotion was defined without explicit typing during the primary XML index creation.

Step-by-Step Resolution Guide

Step 1: Review the Primary Selective XML Index Definition

  • Query the primary XML index metadata to identify the exact path causing the conflict:
  SELECT * FROM sys.xml_indexes WHERE object_id = OBJECT_ID('YourTable');
  • Check the path_locator and associated promoted path types using sys.selective_xml_index_paths.
  • Confirm whether the path in question is explicitly typed or defaulting to node().

Step 2: Modify the XML Path to Use a Specific Node Type

  • Open the T-SQL script where the secondary selective XML index is defined (typically via CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX ... FOR PATH).
  • Replace the generic node() type in the path expression with an explicit element, attribute, or value type, for example:
  -- Instead of:
  '/root/element/node()'
  -- Use:
  '/root/element' AS XQUERY 'xs:string'
  • Ensure the path aligns with a concrete type defined in the associated XML Schema Collection (if one is bound to the column).

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

  • If the column uses an XML Schema Collection, validate it includes explicit type definitions for the node in question:
  SELECT xsc.name, xsc.definition 
  FROM sys.xml_schema_collections xsc;
  • Update or re-import the schema collection using CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION with properly typed nodes instead of xs:anyType.
  • Drop and recreate the primary and secondary selective XML indexes after the schema update:
  DROP XML INDEX IF EXISTS PrimaryXmlIndex ON YourTable;
  CREATE PRIMARY XML INDEX PrimaryXmlIndex ON YourTable (XmlColumn);

Step 4: Recreate the Secondary Selective XML Index

  • Once the path is corrected, re-run the CREATE SELECTIVE XML INDEX statement for the secondary (PATH, VALUE, or PROPERTY) index.
  • Confirm the SQL Server 2025 instance has the latest Cumulative Update applied, as path-type resolution bugs in SXI have been patched in recent builds (verify via SELECT @@VERSION;).

Alternative or Verification Steps

  • Verify the fix by running DBCC CHECKCONSTRAINTS and re-executing the index creation script to confirm Error 6392 no longer appears in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER on Windows Server 2025/Windows 11).
  • If retyping the path is not feasible due to application constraints, use a Primary XML Index only (without secondary selective indexes) on that specific path, and rely on XQuery performance tuning instead.

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

Troubleshooting Guide: SQL Server Error 6393 — Duplicate Path Mapping in Selective XML Index

Why This Error Happens

Error 6393 occurs when a Selective XML Index (SXI) definition contains two or more path expressions that resolve to the exact same node path while also being mapped to identical XSD types. SQL Server 2025 enforces strict uniqueness on path-to-type mappings within a single selective XML index to avoid ambiguous promotion of XML node values into secondary indexes. This typically results from manually scripted CREATE XML INDEX or CREATE SELECTIVE XML INDEX / CREATE XML SELECTIVE INDEX statements where redundant WITH XMLNAMESPACES or path promotion clauses were copy-pasted without updating the path or the type binding, or from merging index definitions generated by different schema versions.

Step-by-Step Resolution Guide

Step 1: Review the Full Index Definition Script

  • Open the T-SQL script or use SSMS to script out the existing selective XML index via Right-click Index > Script Index as > CREATE To.
  • Locate the CREATE SELECTIVE XML INDEX statement and inspect every path promotion entry under the FOR clause.
  • Pay close attention to repeated sql:column, path expressions, and AS XQUERY / AS SQL type declarations.

Step 2: Identify the Duplicate Path/Type Pair

  • Compare each path expression (e.g., /Root/Customer/@id) listed in the index body against every other entry.
  • Check if two entries share the identical path string AND the identical XSD type (e.g., both mapped as xs:int).
  • Use a text diff tool or Ctrl+F in Query Editor against the script file to quickly spot exact string duplicates in the path list.
  • Example of the conflict pattern to search for:
PATHS (
    '/Root/Customer/@id' AS xs:int,
    '/Root/Customer/@id' AS xs:int  -- duplicate causes Error 6393
)

Step 3: Remove or Consolidate the Redundant Path Entry

  • Delete the duplicate line entirely if it is an exact redundant mapping.
  • If the two paths were meant to map to different types (e.g., one as xs:int and one as xs:string), correct the type on one entry instead of deleting it, since differing types are permitted.
  • Save the corrected script to a .sql file, e.g., C:\SQLScripts\Fix_SXI_Index.sql.

Step 4: Drop and Recreate the Selective XML Index

  • Run the following in SSMS or sqlcmd connected to your SQL Server 2025 instance:
DROP INDEX [SXI_YourIndexName] ON dbo.YourTable;
GO
-- Execute corrected CREATE SELECTIVE XML INDEX script
  • Confirm the instance service MSSQLSERVER (or named instance) is running under Windows Server 2025 / Windows 11 via Services.msc before executing, to avoid connection timeouts mid-script.

Step 5: Validate Index Creation Logs

  • Check SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for any residual warnings after re-creation.
  • Confirm no Error 6393 reappears during the CREATE SELECTIVE XML INDEX execution output.

Alternative or Verification Steps

  • Verify success by querying sys.selective_xml_index_paths and sys.xml_indexes to confirm only unique path/type combinations exist for the target index ID.
  • As an alternative, if the script was generated by a third-party ORM or schema migration tool, regenerate the index definition from a clean schema export rather than manually editing the existing (possibly corrupted) script.

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

Troubleshooting Guide: Error 6390 – ALTER SCHEMA COLLECTION Failed Due to Selective XML Index Path Invalidation

Why This Error Happens

This error occurs when you attempt to modify an XML Schema Collection that is actively referenced by a Selective XML Index (SXI) on a table, and the proposed schema change would invalidate the specific XML path currently being indexed. SQL Server 2025 performs a validation pass during ALTER SCHEMA COLLECTION operations, and if the new schema definition no longer matches the node type, data type, or structure expected at the indexed path, the engine blocks the change to prevent index corruption. This typically happens after a source system update changes an XML element’s data type (e.g., from xs:string to xs:integer) or removes/renames a node that a secondary XML index relies on.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Index and Path

  • Run the following query to find the exact selective XML index and promoted path causing the conflict:
SELECT si.name AS IndexName, sp.path_expression, t.name AS TableName
FROM sys.selective_xml_index_paths sp
JOIN sys.indexes si ON sp.index_id = si.index_id AND sp.object_id = si.object_id
JOIN sys.tables t ON sp.object_id = t.object_id;
  • Cross-reference the path_expression output with the %.*ls path noted in the Error 6390 message to confirm the exact node in conflict.

Step 2: Drop the Selective XML Index Temporarily

  • Before altering the schema collection, you must remove the dependency:
DROP INDEX [SXI_IndexName] ON [dbo].[YourTable];
  • Note: On large XML datasets (100GB+), ensure you have adequate tempdb space, as dropping an SXI with “secondary indexes” (VALUE, PATH, or PROPERTY) can trigger significant tempdb usage during the subsequent rebuild.

Step 3: Apply the ALTER SCHEMA COLLECTION Command

  • With the index removed, the schema collection is now free of the dependency lock. Execute your intended change:
ALTER XML SCHEMA COLLECTION [dbo].[YourSchemaCollection]
ADD N'<xsd:schema>...</xsd:schema>';
  • Ensure the new schema definition aligns with the data types expected by your application layer to prevent future casting errors.

Step 4: Recreate the Selective XML Index

  • Rebuild the SXI using the CREATE SELECTIVE XML INDEX syntax, redefining the promoted paths to match the new schema structure.
  • If the path name changed (e.g., /Root/Customer/ID to /Root/Customer/CustID), update the PATH argument in the WITH XMLNAMESPACES or path definition clause accordingly to prevent the error from recurring on the next refresh.

Alternative or Verification Steps

  • Verification: After recreating the index, run DBCC CHECKCONSTRAINTS and query sys.xml_indexes to confirm the is_valid status is 1 and the index is no longer flagged as suspect.
  • Alternative: If dropping the production index is not feasible due to uptime requirements, create a new schema collection version, update the XML column’s validation reference to the new collection, and migrate the SXI during a scheduled maintenance window rather than performing an in-place ALTER.

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

Troubleshooting Guide: SQL Server Error 6391 – Invalid Key Column Type in Secondary Selective XML Index

Why This Error Happens

This error occurs when SQL Server attempts to promote a node identified by an XML path expression to a SQL data type that is not supported as a key column in a secondary selective XML index (SXI). Secondary selective XML indexes only support a specific subset of scalar SQL types (such as INT, BIGINT, NVARCHAR, DATETIME2, etc.) for promoted paths, and the node being referenced either resolves to an unsupported type (like XML, SQL_VARIANT, or a CLR type) or returns a value that is ambiguous in type due to mixed-content XML nodes. This typically stems from a mismatch between the PROMOTE type specified in the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... FOR PATH statement and the actual data stored at that XML path.

Step-by-Step Resolution Guide

Step 1: Review the XML Index Definition

  • Locate the CREATE SELECTIVE XML INDEX or the associated sys.xml_index_nodes / sys.selective_xml_index_paths metadata for the affected index.
  • Run the following query to inspect promoted path types:
SELECT path, [type], is_wildcard 
FROM sys.selective_xml_index_paths 
WHERE xml_index_id = (SELECT index_id FROM sys.indexes WHERE name = 'YourXMLIndexName');
  • Identify the specific path mentioned in the Error 6391 message (the %.*ls placeholder will show the actual path in the real error output).

Step 2: Correct the Promoted Data Type

  • Edit the index creation script and change the PROMOTE clause to a supported scalar type (e.g., NVARCHAR(100), INT, BIGINT, DATETIME2, DECIMAL, FLOAT, BIT, or UNIQUEIDENTIFIER).
  • Avoid promoting paths to XML, SQL_VARIANT, VARBINARY(MAX), or any CLR-based user-defined type, as these are explicitly disallowed in secondary selective XML indexes.
  • Example corrected syntax:
CREATE SELECTIVE XML INDEX SXI_Orders ON dbo.OrdersTable(XmlColumn)
FOR (
    PathOrderID = '/Order/@ID' AS SQL BIGINT,
    PathOrderDate = '/Order/Date' AS SQL DATETIME2
);

Step 3: Validate the Underlying XML Data

  • Query sample XML data to confirm the actual node content matches the expected promoted type:
SELECT XmlColumn.value('(/Order/Date)[1]', 'DATETIME2')
FROM dbo.OrdersTable;
  • If the XML contains mixed-type or inconsistent values at that path (e.g., some nodes are dates, others are plain text), normalize the source XML data or exclude that path from promotion.

Step 4: Drop and Recreate the Secondary XML Index

  • Since index definitions cannot be altered in place, drop the existing secondary index:
DROP INDEX SXI_Orders ON dbo.OrdersTable;
  • Recreate it using the corrected path/type mapping from Step 2.
  • Ensure the primary XML index already exists before creating the secondary selective index, as SQL Server 2025 still enforces this dependency.

Step 5: Apply Latest Cumulative Update

  • Check Windows Server 2025 / Windows 11 for the latest SQL Server 2025 Cumulative Update (CU) via SQL Server Setup or Microsoft Update Catalog.
  • Some early builds of SQL Server 2025 contain known type-promotion bugs with selective XML indexes on nested or namespace-qualified paths; applying the latest CU resolves several of these edge cases.

Alternative or Verification Steps

  • After recreating the index, run DBCC CHECKDB and re-execute a test query using the promoted path in a WHERE clause to confirm the optimizer utilizes the new secondary XML index without throwing Error 6391.
  • If the issue persists, as a workaround, remove the problematic path from the selective index definition entirely and rely on a standard primary XML index with runtime .value()/.nodes() queries until the data type inconsistency in the source XML is resolved.

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

Troubleshooting Guide: Error 6388 – Selective DG Version Mismatch

Why This Error Happens

This error occurs when SQL Server 2025’s Selective Dynamic Gating (DG) metadata stored within the database’s system catalog becomes out of sync with the Selective DG engine version actively running on the SQL Server instance. This typically happens after an in-place upgrade, a patch/cumulative update installation, or a database restore/attach operation where the source server had a different Selective DG build than the destination server. Index corruption or an interrupted update process during a service pack installation can also leave the index metadata referencing an incompatible or deprecated DG version.

Step-by-Step Resolution Guide

Step 1: Verify Current SQL Server and Selective DG Build Versions

  • Run SELECT @@VERSION; in a new query window to confirm the exact build number of SQL Server 2025.
  • Cross-reference this build against Microsoft’s Selective DG compatibility matrix in the official release notes for your Cumulative Update (CU).
  • Check the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for any failed component registration messages during the last startup.

Step 2: Rebuild the Affected Index

  • Identify the specific index named in the error message (replace %.*ls with the actual index name from your error log).
  • Execute an ALTER INDEX [IndexName] ON [Schema].[TableName] REBUILD; command to force SQL Server to regenerate the Selective DG metadata using the current engine version.
  • For large tables, consider adding the WITH (ONLINE = ON) option (Enterprise Edition only) to avoid extended table locks during business hours.

Step 3: Update Statistics and Refresh Database Compatibility

  • Run EXEC sp_updatestats; on the affected database to ensure the query optimizer metadata aligns with the newly rebuilt index structures.
  • Verify the database compatibility level matches SQL Server 2025 standards by running SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDBName';.
  • If the compatibility level is outdated (e.g., set to a legacy 2019 level), update it using ALTER DATABASE [YourDBName] SET COMPATIBILITY_LEVEL = 170;.

Step 4: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest CU for SQL Server 2025 to ensure the Selective DG engine binaries are fully patched.
  • Run the installer as Administrator on Windows Server 2025/Windows 11 and select “Repair” if the engine files appear corrupted rather than outdated.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (Run as Administrator) once the patch installation completes.

Alternative or Verification Steps

  • Verify the Fix: Run DBCC CHECKDB('YourDBName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no further Selective DG consistency errors are reported for the database.
  • Alternative Solution: If the rebuild fails due to persistent corruption, drop and recreate the index manually using the original index definition script, then re-run UPDATE STATISTICS to force a clean metadata write.

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

Troubleshooting Guide: SQL Server Error 6389 – Selective XML Index Maxlength Exceeded

Why This Error Happens

This error occurs when a value being inserted into an XML column exceeds the maximum length constraint defined for a specific path in a Selective XML Index (SXI). SQL Server 2025 enforces strict maxlength boundaries on promoted nodes within the index schema, and any XML data exceeding this byte or character limit at the specified path will be rejected during the insert or update operation. This typically happens after a source system change increases the size of XML payloads without a corresponding update to the index’s path specification, or when the index was created with an undersized maxlength for a promoted property.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path and Index

  • Capture the full error message, noting the %.*ls values for both the path and the selective XML index name.
  • Query sys.selective_xml_index_paths joined with sys.xml_indexes to locate the current max_length setting for the reported path.
  • Run: SELECT sxip.path, sxip.max_length, xi.name AS index_name FROM sys.selective_xml_index_paths sxip JOIN sys.xml_indexes xi ON sxip.xml_index_id = xi.index_id;

Step 2: Inspect the Source Data Causing the Overflow

  • Isolate the specific XML document or batch being inserted that triggered the error.
  • Use DATALENGTH() or LEN() against the XQuery .value() extraction of the same path to confirm the actual size of the incoming data.
  • Compare this value against the max_length returned in Step 1 to confirm the overflow margin.

Step 3: Drop and Recreate the Selective XML Index with Updated Maxlength

  • Since ALTER INDEX does not support modifying path-level max_length for SXI directly, you must drop and recreate the index.
  • Run: DROP INDEX [YourSXIName] ON [YourSchema].[YourTable];
  • Recreate using: CREATE SELECTIVE XML INDEX [YourSXIName] ON [YourSchema].[YourTable]([XmlColumn]) FOR ([YourPathName] = 'YourXPath' AS SQL VARCHAR(MAX));
  • Alternatively, increase the specific value from a fixed length (e.g., VARCHAR(100)) to a larger explicit size or VARCHAR(MAX) if path cardinality supports it.

Step 4: Rebuild Dependent Secondary XML Indexes

  • If secondary indexes (VALUE, PATH, or PROPERTY) reference the same XML column, rebuild them after the SXI recreation to ensure schema consistency.
  • Run: ALTER INDEX ALL ON [YourSchema].[YourTable] REBUILD;
  • Check sys.dm_db_index_physical_stats to confirm the rebuild completed without fragmentation warnings.

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement that failed; if it completes without Error 6389, the maxlength adjustment was successful.
  • If recreating the index is not immediately feasible, implement a staging table with VARCHAR(MAX) validation logic to truncate or flag oversized XML nodes before they reach the indexed production table.

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

Troubleshooting Guide: Error 6386 – Cannot Convert Selective XML Index Using DROP_EXISTING

Why This Error Happens

This error occurs because SQL Server 2025 does not allow the DROP_EXISTING option to be used when attempting to convert a primary Selective XML Index (SXI) directly into a Secondary Selective XML Index (SSXI). The engine detects that the target index name already exists as a primary selective XML index, and since the internal metadata structures for primary and secondary XML indexes are fundamentally different, the CREATE XML INDEX ... WITH (DROP_EXISTING = ON) syntax cannot simply “rebuild” it into the other type. Essentially, this is a schema-definition conflict rather than a permissions or connectivity issue—the operation requires an explicit drop-and-recreate sequence rather than an in-place conversion.

Step-by-Step Resolution Guide

Step 1: Identify the Existing Index Type

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the following query to confirm the index is currently a primary selective XML index:
SELECT name, secondary_type_desc, using_xml_index_id 
FROM sys.xml_indexes 
WHERE name = 'YourIndexName';
  • If using_xml_index_id is NULL, this confirms it is a primary SXI, which explains why DROP_EXISTING fails when targeting a secondary type.

Step 2: Manually Drop the Existing Primary Index

  • Since DROP_EXISTING cannot bridge the two types, you must remove the old index explicitly.
  • Execute the drop command on the affected table:
DROP INDEX YourIndexName ON dbo.YourTable;
  • Ensure no active transactions or open sessions are locking the table (check via sp_who2 or Activity Monitor) before dropping, as this can cause a blocking timeout rather than a clean removal.

Step 3: Recreate the Index as a Secondary Selective XML Index

  • Once the primary index is dropped, create the new secondary index using the USING XML INDEX clause to link it to a valid primary selective XML index.
  • Use the following syntax structure:
CREATE SELECTIVE XML INDEX SecondaryIndexName 
ON dbo.YourTable (XmlColumn) 
USING XML INDEX PrimaryIndexName 
FOR PATHS;
  • Verify that the PrimaryIndexName referenced here is a valid, currently existing primary selective XML index on the same table and column.

Step 4: Restart the SQL Server Service (If Metadata Cache is Stale)

  • If the error persists even after dropping the index, the Query Optimizer metadata cache might be holding stale references.
  • Open Services.msc on Windows Server 2025, locate SQL Server (MSSQLSERVER), and perform a restart, or run DBCC FREEPROCCACHE to clear cached execution plans without a full service restart.

Alternative or Verification Steps

  • Verification: Re-run the sys.xml_indexes query from Step 1; the secondary_type_desc column should now display PATH, VALUE, or PROPERTY (depending on your configuration) instead of NULL.
  • Alternative: If the conversion must happen within a single transaction to avoid downtime on a production replica, wrap the DROP INDEX and CREATE SELECTIVE XML INDEX statements inside an explicit BEGIN TRANSACTION/COMMIT block to ensure atomicity rather than relying on the native conversion syntax.

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

Troubleshooting Guide: Error 6387 — Cannot Remove All Paths for Selective XML Index

Why This Error Happens

This error occurs when a T-SQL script or maintenance routine attempts to DROP or ALTER the final remaining path definition from a selective XML index using sys.sp_xml_index_path or an ALTER INDEX ... DROP XML PATH statement. SQL Server 2025 enforces a strict integrity constraint requiring at least one promoted path to exist at all times, because a selective XML index with zero paths has no defined schema to selectively promote nodes into relational storage. This typically happens during automated schema migration scripts, index rebuild jobs, or manual cleanup operations where all paths are dropped sequentially before a new one is added, rather than being swapped atomically.

Step-by-Step Resolution Guide

Step 1: Identify the Current Path Configuration

  • Query the system views to see exactly what paths exist on the index before attempting any modification.
  • Run the following in SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance:
SELECT xip.name, xip.path, xip.is_primitive 
FROM sys.selective_xml_index_paths xip
JOIN sys.indexes i ON xip.object_id = i.object_id AND xip.index_id = i.index_id
WHERE i.name = 'YourIndexName';
  • Note down every path name; you will need at least one placeholder to remain active during the transaction.

Step 2: Add the New Path Before Dropping the Old One

  • Do not drop all existing paths in a single batch or script block.
  • Reverse the order of operations in your migration script: first execute sp_xml_index_path with the 'add' action to insert the new/replacement path.
  • Only after the new path is successfully committed, proceed to drop the obsolete paths using the 'drop' action.

Step 3: Rebuild the Index as a Fallback

  • If the script logic cannot be easily reordered (e.g., legacy ORM-generated SQL), drop the entire selective XML index and the underlying secondary XML indexes.
  • Recreate the primary XML index and the selective XML index from scratch using a single CREATE SELECTIVE XML INDEX statement that defines the full, correct set of paths in one atomic operation.
  • This avoids the sequential “add/drop” limitation entirely by defining the final state immediately.

Step 4: Check for Blocking Automation Scripts

  • If this error persists in production despite manual fixes, check Task Scheduler (Windows Server 2025) or SQL Server Agent jobs for automated DBA maintenance scripts.
  • Search script files for instances of sp_xml_index_path @operation = N'drop' executed in a loop or cursor, as this is the most common cause of the “last path” failure in automated environments.

Alternative or Verification Steps

  • Verify the Fix: Re-run the sys.selective_xml_index_paths query from Step 1. If the index was repaired correctly, you should see your newly intended path listed, and the index status in sys.indexes should show is_disabled = 0.
  • Alternative Fix: If you simply need to clear the index structure entirely, use DROP INDEX [IndexName] ON [TableName] to remove the whole selective XML index object rather than trying to strip its paths down to zero via the stored procedure.

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

Why This Error Happens

Error 6383 occurs when the XML data being inserted or updated does not conform to the promoted path definitions configured in the Selective XML Index (SXI). This typically happens because the underlying XML schema was altered, a node was promoted with an incompatible SQL data type, or the XML instance contains a structure (such as a repeated node or namespace mismatch) that violates the index’s path constraints. In some cases, this also surfaces after an in-place upgrade to SQL Server 2025 if legacy XML indexes were created under older optimizer rules that are now stricter.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Index and Path

  • Run SELECT * FROM sys.selective_xml_index_paths WHERE object_id = OBJECT_ID('YourTable') to list all promoted paths tied to the index named in the error.
  • Cross-reference the path listed against the actual XML column data using SELECT xmlcolumn.query('/path/to/node') FROM YourTable.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full stack trace accompanying Error 6383.

Step 2: Validate XML Data Type Compatibility

  • Confirm the SQL data type used in CREATE SELECTIVE XML INDEX (e.g., AS SQL INT) actually matches the real-world data in that XML node; mismatched types (such as text in a node typed as INT) are the most common trigger.
  • If using an XML Schema Collection, verify it hasn’t drifted from the data by running SELECT xml_collection_id, name FROM sys.xml_schema_collections WHERE name = 'YourSchemaName'.
  • Update the schema collection using ALTER XML SCHEMA COLLECTION if definitions are outdated.

Step 3: Drop and Rebuild the Selective XML Index

  • Disable the problematic index first: ALTER INDEX [YourSXIName] ON YourTable DISABLE;
  • Drop it entirely: DROP XML INDEX [YourSXIName] ON YourTable;
  • Recreate it with corrected paths, for example:
  CREATE SELECTIVE XML INDEX SXI_Fixed
  ON YourTable (XmlColumn)
  FOR (PathNode = '/root/node' AS SQL VARCHAR(100));
  • Rebuild statistics afterward using UPDATE STATISTICS YourTable;

Step 4: Apply Latest Cumulative Update

  • On Windows Server 2025, confirm you are running the latest SQL Server 2025 Cumulative Update via SELECT @@VERSION;, since early builds had known promoted-path validation bugs now patched.
  • Download and apply the latest CU from the Microsoft Update Catalog, then restart the SQL Server (MSSQLSERVER) service from services.msc.

Alternative or Verification Steps

  • After rebuilding, re-run the original INSERT/UPDATE statement that triggered Error 6383 and confirm it completes without exception; also run DBCC CHECKCONSTRAINTS and sys.dm_db_index_physical_stats to confirm index health.
  • If the error persists, as a workaround, drop the Selective XML Index entirely and use a standard Primary XML Index instead, which has fewer structural constraints on promoted paths.

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

Troubleshooting Guide: SQL Server Error 6384 — Invalid Wildcard Path in Selective XML Index

Why This Error Happens

This error occurs when defining a selective XML index (SXI) path node and the path expression uses a wildcard character (‘*’) on only one side of a namespace-qualified node — either the URI portion or the local name portion — without the other. SQL Server’s selective XML index path parser requires that wildcards be applied consistently to both components of a qualified name, or not at all, because partial wildcarding creates an ambiguous namespace resolution during index creation. This is typically a syntax/authoring issue in the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... FOR statement rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Index Definition

  • Open the T-SQL script or stored procedure that issued the CREATE SELECTIVE XML INDEX or the secondary/auxiliary path index statement referenced in the error.
  • Check SQL Server Management Studio (SSMS) Query Results/Messages pane for the full error text, which includes the index name (%.*ls) truncated in the message — cross-reference this with sys.selective_xml_index_paths if the index partially exists.
  • Note the exact path expression being passed into the PATH or FOR clause, especially any node that uses *.

Step 2: Correct the Wildcard Syntax in the XML Path Expression

  • Identify nodes written like *:LocalName (wildcard URI, explicit name) or Prefix:* (explicit URI, wildcard name) — these are the invalid half-wildcard forms.
  • Rewrite the path so wildcards apply to both the URI and name (*:*) or to neither (use a fully qualified namespace-uri:local-name pair).
  • Example fix:
  • Invalid: /ns:* or /*:Customer
  • Valid: /*:* (fully wildcarded) or /http://schemas.example.com/ns:Customer (fully qualified)
  • Update any WITH XMLNAMESPACES clause in the script to ensure the namespace prefix used in the path matches a properly declared URI.

Step 3: Drop and Recreate the Selective XML Index

  • Run DROP XML INDEX [IndexName] ON [Schema].[Table]; if a partial or broken index object was left behind from the failed creation attempt.
  • Re-run the corrected CREATE SELECTIVE XML INDEX statement:
  CREATE SELECTIVE XML INDEX SXI_Example
  ON dbo.YourTable (XmlColumn)
  FOR (
      PATH_NODE PATH = '/*:*/Order/@*:*' AS SQL VARCHAR(100)
  );
  • Confirm the statement completes without Error 6384 and the index appears in sys.indexes.

Step 4: Validate the XML Schema Collection (if bound)

  • If the XML column is bound to an XML Schema Collection, run SELECT * FROM sys.xml_schema_collections; to confirm the namespace URIs match exactly what you used in the index path.
  • Re-import or update the schema collection with ALTER XML SCHEMA COLLECTION if namespace mismatches are found, then retry index creation.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths joined to sys.indexes to confirm the new path entries exist and show the expected path_expression without errors.
  • If the error persists despite correct syntax, test the path expression in a standalone .value() or .nodes() XQuery against a sample XML instance in SSMS to confirm SQL Server parses the namespace/wildcard combination correctly before re-embedding it into the index definition.

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

Troubleshooting Guide: SQL Server Error 6385 – Selective XML Index Does Not Exist

Why This Error Happens

This error occurs when a query or stored procedure references a Selective XML Index (SXI) by name on a specific table column, but SQL Server cannot locate that index in the system catalog (sys.selective_xml_index_paths or sys.xml_indexes). This typically happens because the index was dropped, renamed, or never successfully created due to a failed or partially committed DDL transaction. It can also occur after a database restore or migration where the XML index metadata became out of sync with the underlying table schema, or if the index was created on a different column than the one referenced in the query.

Step-by-Step Resolution Guide

Step 1: Verify the Index Actually Exists

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run the following query to check for the index’s existence:
  SELECT i.name AS IndexName, c.name AS ColumnName, t.name AS TableName
  FROM sys.xml_indexes i
  JOIN sys.columns c ON i.object_id = c.object_id AND i.column_id = c.column_id
  JOIN sys.tables t ON i.object_id = t.object_id
  WHERE t.name = 'YourTableName';
  • Confirm whether the index name and column name in your query match exactly what is returned (names are case-sensitive depending on collation).

Step 2: Recreate the Selective XML Index

  • If the index is missing, recreate it using the correct syntax, ensuring the column reference is accurate:
  CREATE SELECTIVE XML INDEX SXI_YourIndexName
  ON dbo.YourTableName (YourXmlColumn)
  USING XML INDEX PrimaryXmlIndexName
  FOR ({your XQuery path and type});
  • Ensure the Primary XML Index on the same column exists first, as Selective XML Indexes depend on it.
  • Check the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for any failure messages during the original CREATE INDEX attempt.

Step 3: Check for Schema or Column Mismatches

  • Confirm the column name referenced in the application or stored procedure code has not been altered (e.g., via ALTER TABLE ... ALTER COLUMN).
  • Use sp_help 'YourTableName' to validate current column names, data types, and index bindings.
  • Update any hardcoded references in stored procedures, views, or application connection strings (found in web.config or appsettings.json for applications running on Windows 11/Server 2025) to match the correct index and column names.

Step 4: Rebuild Database Metadata (If Corruption Is Suspected)

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out catalog corruption.
  • If corruption is found, restore from a known good backup using SSMS or RESTORE DATABASE T-SQL command, pointing to your .bak file location (e.g., D:\SQLBackups\YourDatabase.bak).

Alternative or Verification Steps

  • After recreating the index, re-run the original query or stored procedure that triggered Error 6385 to confirm it executes without exception.
  • As an alternative, query sys.selective_xml_index_paths directly to cross-reference path definitions if the error persists only for specific XQuery path expressions rather than the whole index.

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

Troubleshooting Guide: SQL Server Error 6381 – Path Not Found in Selective XML Index

Why This Error Happens

Error 6381 occurs when a query references an XML path (via sql:column or a direct path expression) that does not exist in the promoted path set of the Selective XML Index (SXI). This typically happens because the path was never registered during index creation, the path was removed or altered after the index was built, or there’s a mismatch between the XML schema and the promoted paths/types defined in the index. It can also surface if the underlying XML data structure changed (e.g., namespace updates, element renaming) without rebuilding the corresponding secondary XML index.

Step-by-Step Resolution Guide

Step 1: Identify the Failing Path and Index

  • Capture the exact error message text, including the %.*ls substituted values for path and index name.
  • Run the following query to inspect currently defined promoted paths for the SXI:
  SELECT * FROM sys.xml_indexes WHERE object_id = OBJECT_ID('YourTable');
  SELECT * FROM sys.selective_xml_index_paths WHERE xml_component_id = <index_id>;
  • Compare the path reported in the error against the path_expression column in the results.

Step 2: Validate the XML Schema and Path Syntax

  • Open the source XML column data and confirm the exact element/attribute hierarchy using a sample document.
  • Check for namespace mismatches — paths must include correctly bound namespace prefixes matching sys.xml_schema_namespaces or the WITH XMLNAMESPACES clause used in the query.
  • Ensure the path expression casing and structure (e.g., /root/child/@attribute) exactly matches how it was declared in CREATE SELECTIVE XML INDEX.

Step 3: Drop and Recreate the Selective XML Index with Correct Paths

  • Drop the outdated index:
  DROP INDEX sxi_YourIndexName ON YourTable;
  • Recreate it with the corrected/updated path registered:
  CREATE SELECTIVE XML INDEX sxi_YourIndexName
  ON YourTable (XmlColumn)
  FOR (Path1 = '/root/child/@attribute' AS SQL TYPE VARCHAR(50));
  • Confirm the path is now listed in sys.selective_xml_index_paths.

Step 4: Update Dependent Queries and Stored Procedures

  • Search application code and stored procedures using sql:column hints or .value()/.query() methods referencing the old path.
  • Update all references to match the newly promoted path syntax exactly.
  • Recompile affected stored procedures using sp_recompile 'YourProcedureName' to clear stale execution plans.

Step 5: Rebuild Statistics and Validate Index Integrity

  • Run DBCC CHECKTABLE('YourTable') WITH DATA_PURITY to confirm no underlying corruption exists.
  • Update statistics on the table to ensure the query optimizer uses the refreshed index metadata:
  UPDATE STATISTICS YourTable;

Alternative or Verification Steps

  • Re-execute the original failing query and confirm Error 6381 no longer appears in SQL Server Error Logs or Event Viewer (Event ID 6381 under Applications and Services Logs > MSSQLSERVER).
  • If the error persists, temporarily drop the Selective XML Index entirely and rely on standard XML .value()/.nodes() methods to isolate whether the issue is index-specific or a genuine XML data/path integrity problem.

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

Troubleshooting Guide: Error 6382 – Could Not Find Selective XML Index on Table

Why This Error Happens

This error occurs when a query or maintenance operation references a Selective XML Index (SXI) by name, but SQL Server 2025 cannot locate it in the system catalog for the specified table. This typically happens because the index was dropped, renamed, or never successfully created due to a failed or rolled-back transaction. It can also occur if the index exists on a different table or schema than the one referenced in the query, or if metadata corruption has desynchronized the sys.selective_xml_indexes catalog view from the actual table structure.

Step-by-Step Resolution Guide

Step 1: Verify the Index Exists and Check Its Exact Name

  • Run the following query to confirm the index name and associated table:
SELECT si.name AS IndexName, t.name AS TableName, s.name AS SchemaName
FROM sys.selective_xml_indexes si
JOIN sys.tables t ON si.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id;
  • Confirm there are no typos, case-sensitivity mismatches, or schema qualification issues in the calling query (e.g., dbo.Table1 vs sales.Table1).

Step 2: Check for Incomplete Index Creation or Rollback

  • Inspect the SQL Server Error Log for any failed CREATE SELECTIVE XML INDEX statements around the time the index was supposedly built.
  • Path to logs: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG
  • If the creation transaction was interrupted (e.g., connection timeout, disk I/O failure), re-run the index creation statement manually:
CREATE SELECTIVE XML INDEX SXI_IndexName
ON dbo.YourTable (XmlColumn)
USING XML INDEX PXML_Index
FOR XMLPATH;

Step 3: Rebuild or Recreate the Selective XML Index

  • Drop any orphaned or partial index references using:
DROP INDEX IF EXISTS SXI_IndexName ON dbo.YourTable;
  • Recreate the index explicitly, ensuring the underlying Primary XML Index exists first, since Selective XML Indexes depend on it.
  • Validate that the table has a unique clustered index, as this is a prerequisite for XML indexing in SQL Server 2025.

Step 4: Run Consistency Checks on the Database

  • Execute DBCC CHECKDB to rule out metadata corruption affecting the system catalog views:
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is found in system tables related to XML indexing, restore from a known good backup rather than attempting repair, as REPAIR_ALLOW_DATA_LOSS can affect index metadata integrity.

Step 5: Restart SQL Server Service to Clear Cached Plans

  • Open Services.msc on Windows Server 2025 / Windows 11 and restart the SQL Server (MSSQLSERVER) service.
  • Alternatively, clear the plan cache to remove stale query plans referencing the old index definition:
DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Re-run the original query or application process that triggered Error 6382 and confirm it executes without referencing a missing index.
  • As a verification check, query sys.selective_xml_indexes again post-fix to ensure the index now appears with the correct object_id mapping to your target table.

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

Troubleshooting Guide: SQL Server Error 6379 – Selective XML Index Already Exists on Column

Why This Error Happens

This error occurs because SQL Server enforces a strict one-to-one relationship between a column and its selective XML index (SXI); once a selective XML index has been created on an xml-typed column, any attempt to create a second one on that same column is rejected. The root cause is typically a script or deployment process that re-runs CREATE SELECTIVE XML INDEX without first checking for existing indexes via sys.selective_xml_index_paths or sys.indexes. This commonly happens during automated schema migrations, CI/CD database deployment pipelines, or when a DBA manually re-applies an index creation script against a database that was restored or already contains the index from a prior deployment.

Step-by-Step Resolution Guide

Step 1: Identify the Existing Selective XML Index

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025 / Windows 11.
  • Run the following query to confirm the conflicting index and its associated column/table:
SELECT i.name AS IndexName, t.name AS TableName, c.name AS ColumnName
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
JOIN sys.tables t ON i.object_id = t.object_id
WHERE i.type_desc = 'XML' AND c.name = 'YourXmlColumnName';
  • Note the existing index name reported in the Error 6379 message (%.*ls) for use in the next step.

Step 2: Drop or Rename the Conflicting Index

  • If the existing index is obsolete or being replaced, drop it using:
DROP INDEX [ExistingSelectiveXmlIndexName] ON dbo.YourTableName;
  • If you need to preserve the existing index, rename your new index creation script to use a different, unique name rather than attempting a duplicate on the same column.
  • Verify there are no residual secondary selective XML indexes (promoted path indexes) still referencing the column, as these must also be dropped before recreating the primary SXI.

Step 3: Update Deployment Scripts to Prevent Recurrence

  • Modify your schema migration or deployment scripts to include an existence check before creation:
IF NOT EXISTS (
    SELECT 1 FROM sys.indexes i
    JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
    JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    WHERE i.type_desc = 'XML' AND c.name = 'YourXmlColumnName'
)
BEGIN
    CREATE SELECTIVE XML INDEX [NewSXIName] ON dbo.YourTableName(YourXmlColumnName)
    USING XML INDEX [PrimaryXmlIndexName];
END
  • Store this guarded script in your version-controlled deployment repository to avoid future idempotency failures during re-deployment.

Step 4: Recreate the Selective XML Index Correctly

  • Execute the corrected CREATE SELECTIVE XML INDEX statement, ensuring it references a unique index name and the correct underlying primary XML index.
  • Confirm the SQL Server service account has sufficient permissions (ALTER on the table and REFERENCES on the XML schema collection, if applicable) under Windows Server 2025 security policies.

Alternative or Verification Steps

  • Verify the fix by re-running the sys.selective_xml_index_paths catalog view query against the table to confirm only one selective XML index exists per XML column, and test the original deployment script to ensure it completes without Error 6379.
  • As an alternative, if multiple indexing strategies are needed for the same column, use secondary selective XML indexes (CREATE SELECTIVE XML INDEX ... FOR) tied to the single primary SXI instead of attempting to create multiple independent primary indexes.

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

Troubleshooting Guide: Error 6380 – Multiple Values Found for SINGLETON Option in Selective XML Index

Why This Error Happens

This error occurs when a selective XML index (SXI) is defined with the SINGLETON option on an XML path, but the actual XML data stored in the column contains multiple nodes matching that path for a given row. SQL Server 2025 enforces the SINGLETON constraint strictly during index population or update operations, expecting exactly one node per instance at the specified path. This mismatch typically arises from incorrect XML schema assumptions during index creation, malformed or inconsistent XML data inserted after the index was built, or source data that was migrated/imported without validating against the indexed XPath structure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Data and Path

  • Note the exact path reported in the error message (the %.*ls placeholder will show the actual XPath in your error log).
  • Run a query using nodes() and value() against the affected XML column to count matching nodes per row:
  SELECT PrimaryKeyColumn, COUNT(*) AS NodeCount
  FROM YourTable
  CROSS APPLY YourXmlColumn.nodes('/Path/To/Element') AS T(X)
  GROUP BY PrimaryKeyColumn
  HAVING COUNT(*) > 1;
  • Review the output to locate the specific rows causing the violation.

Step 2: Correct or Clean the XML Data

  • Decide whether the duplicate nodes are valid business data (meaning SINGLETON is the wrong constraint) or are erroneous/duplicate entries that need removal.
  • If data is erroneous, use modify() with XML DML to remove extra nodes:
  UPDATE YourTable
  SET YourXmlColumn.modify('delete (/Path/To/Element)[2]')
  WHERE PrimaryKeyColumn = @AffectedID;
  • If duplicates are legitimate, proceed to Step 3 to redefine the index instead of altering data.

Step 3: Drop and Recreate the Selective XML Index Without SINGLETON (If Applicable)

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Drop the existing selective XML index:
  DROP SELECTIVE XML INDEX YourSXIName ON YourTable;
  • Recreate it using a non-singleton path type if multiple nodes are expected:
  CREATE SELECTIVE XML INDEX YourSXIName ON YourTable(YourXmlColumn)
  FOR
  (
      PathName = '/Path/To/Element' AS XQUERY 'xs:string'
  );
  • Ensure the path definition no longer includes the SINGLETON keyword unless the data is guaranteed to be unique at that node.

Step 4: Rebuild and Validate the Index

  • Execute an index rebuild to force repopulation and catch any remaining violations:
  ALTER INDEX ALL ON YourTable REBUILD;
  • Check SQL Server error logs (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG by default on Windows Server 2025) to confirm Error 6380 no longer appears.

Alternative or Verification Steps

  • Verify the fix by re-running the index creation statement and confirming it completes without error; also execute a full DBCC CHECKDB or DBCC CHECKTABLE to ensure XML index consistency.
  • As an alternative, if you cannot modify the underlying XML data due to business constraints, redesign the selective XML index to use a non-singleton (multi-value) path promotion instead, avoiding the strict uniqueness enforcement altogether.

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

Troubleshooting Guide: SQL Server Error 6377 — Invalid Wildcard Path in Selective XML Index

Why This Error Happens

This error occurs when a user attempts to create or modify a selective XML index (SXI) using an XQuery path expression that contains a wildcard character (*) as the final step of the path. SQL Server’s Selective XML Indexes feature explicitly disallows wildcards in the terminal node of a promoted path because the engine requires a concrete, resolvable node name to build the indexed path node and type statistics at that final level. This is a path-definition syntax restriction enforced by the SXI parser, not a permissions or connectivity issue, and it typically surfaces during CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX statements with an auxiliary path set.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path Definition

  • Locate the exact CREATE SELECTIVE XML INDEX or ALTER TABLE statement referenced in the error message (the %.*ls placeholder will show the index name).
  • Run the following query to inspect existing promoted paths on the index:
SELECT path_id, path_expression, is_primitive
FROM sys.selective_xml_index_paths
WHERE xml_index_id = (SELECT index_id FROM sys.indexes WHERE name = 'YourXmlIndexName');
  • Note which path_expression ends in /*, //*, or @*.

Step 2: Rewrite the Path to Remove the Trailing Wildcard

  • Replace the wildcard in the last step with an explicit element or attribute name.
  • Example of an invalid path: /Root/Customer/*
  • Corrected version: /Root/Customer/Address (or enumerate each child element you actually need indexed as a separate path entry).
  • If you need multiple children indexed, add each one as its own WITH XMLNAMESPACES/path entry rather than relying on a wildcard:
CREATE SELECTIVE XML INDEX SXI_Customer
ON dbo.CustomerData (XmlColumn)
USING XML INDEX PXML_CustomerData
FOR (
  PathAddress = '/Root/Customer/Address',
  PathPhone   = '/Root/Customer/Phone'
);

Step 3: Validate Namespace and Schema Assumptions

  • Confirm that the element names you substituted actually exist in the XML instances stored in the column (use SELECT TOP 10 XmlColumn FROM dbo.CustomerData to sample data).
  • If the XML schema is dynamic and truly requires wildcard-style flexibility, consider using a standard XML index (primary/secondary XML index) instead of a Selective XML Index, since standard XML indexes do not have this last-step wildcard restriction.

Step 4: Recreate the Index

  • Drop the previous failed/partial index definition if it exists:
DROP INDEX IF EXISTS SXI_Customer ON dbo.CustomerData;
  • Re-run the corrected CREATE SELECTIVE XML INDEX script from Step 2.
  • Check sys.messages for Error 6377 text to confirm no residual syntax issue:
SELECT * FROM sys.messages WHERE message_id = 6377 AND language_id = 1033;

Alternative or Verification Steps

  • Verify the fix by re-running the CREATE SELECTIVE XML INDEX statement and confirming it completes without error, then query sys.selective_xml_index_paths again to confirm the new path is listed correctly.
  • If wildcard-style indexing is a hard requirement for your workload, switch to a non-selective (standard) XML index on the column, or promote individual known element names as separate scalar/relational columns via computed columns instead of relying on XML path wildcards.

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

Troubleshooting Guide: SQL Server Error 6378 – Selective XML Index Creation Failure

Why This Error Happens

This error occurs because SQL Server 2025 requires a table to have a clustered primary key consisting of fewer columns than the internal limit before a Selective XML Index (SXI) can be created on it. When the clustered primary key is composed of too many columns, SQL Server cannot generate the internal structures needed to support the selective indexing of XML node data. This typically happens on legacy tables migrated from older schemas or tables designed with wide composite keys that exceed the supported threshold.

Step-by-Step Resolution Guide

Step 1: Identify the Current Primary Key Structure

  • Open SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Run the following query to inspect the existing clustered primary key column count:
SELECT i.name AS IndexName, COUNT(ic.column_id) AS ColumnCount
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE i.object_id = OBJECT_ID('dbo.YourTableName') AND i.is_primary_key = 1
GROUP BY i.name;
  • Confirm whether the column count exceeds the supported limit for selective XML indexes.

Step 2: Redesign the Clustered Primary Key

  • Drop the existing clustered primary key constraint using:
ALTER TABLE dbo.YourTableName DROP CONSTRAINT PK_YourTableName;
  • Recreate a narrower clustered primary key, ideally using a single surrogate key column (e.g., an INT or BIGINT identity column):
ALTER TABLE dbo.YourTableName ADD CONSTRAINT PK_YourTableName PRIMARY KEY CLUSTERED (NewSurrogateKeyID);
  • Ensure any foreign key relationships are updated to reference the new key structure.

Step 3: Recreate the Selective XML Index

  • Once the clustered primary key has been simplified, attempt to create the selective XML index again:
CREATE SELECTIVE XML INDEX SXI_YourTableName
ON dbo.YourTableName (YourXmlColumn);
  • Confirm no errors are returned during index creation.

Step 4: Validate Server and Database Compatibility Level

  • Check that the database compatibility level supports Selective XML Indexes (SQL Server 2025 features require compatibility level 170 or higher):
SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If needed, update it with:
ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths and sys.xml_indexes to confirm the selective XML index now appears correctly against the table.
  • If redesigning the primary key is not feasible due to application dependencies, consider using a standard Primary XML Index instead, which does not impose the same clustered key column restrictions.

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

Troubleshooting Guide: SQL Server Error 6375 — Invalid Data Type for Selective XML Index

Why This Error Happens

This error occurs when you attempt to create or promote a secondary selective XML index (SXI) on an XML column path whose declared data type is not supported by the selective XML index feature, such as sql_variant, xml, image, text, ntext, timestamp, geography, or geometry. Selective XML indexes rely on a fixed, sanctioned set of SQL Server scalar types (such as int, varchar, nvarchar, decimal, datetime2, etc.) to shred and index promoted XML node values, so any path typed outside that allow-list will cause the engine to reject the index definition. This is typically a schema-design or script-generation issue rather than a corruption or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Path and Data Type

  • Open the failing CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX ... FOR ... statement in SQL Server Management Studio (SSMS) 21 connected to your SQL Server 2025 instance.
  • Locate the sql:path or node promotion clause referenced in the error text (%.*ls placeholders will be filled in with the actual type and index name in the real error message).
  • Cross-reference the promoted type against the supported list documented for Selective XML Indexes in SQL Server 2025 Books Online.

Step 2: Modify the Promoted Node Type Definition

  • Edit the WITH XMLNAMESPACES / FOR ... AS SQL TYPE clause in your index creation script to use a supported scalar type (for example, change sql_variant to nvarchar(4000) or image to varbinary(max)).
  • If the path targets a spatial or large-object node, redesign the promotion to extract a string/numeric surrogate value instead of the unsupported type.
  • Save the corrected script to C:\SQLScripts\FixSelectiveXMLIndex.sql (or your team’s standard script repository path) for version tracking.

Step 3: Drop and Recreate the Selective XML Index

  • Run DROP XML INDEX IF EXISTS [IndexName] ON [Schema].[Table]; to remove the invalid definition.
  • Execute the corrected CREATE SELECTIVE XML INDEX statement with the updated SQL type.
  • Monitor the Messages tab in SSMS for successful completion, confirming Error 6375 no longer appears.

Step 4: Validate Underlying Table Schema

  • Check the base table’s XML column and any computed columns involved using sp_help '[Schema].[Table]'.
  • Ensure no other secondary XML indexes on the same column reference unsupported types before attempting a full rebuild with ALTER INDEX ALL ON [Schema].[Table] REBUILD;.

Alternative or Verification Steps

  • Confirm the fix by querying sys.selective_xml_index_paths and sys.xml_indexes to verify the index exists with the corrected type and status is_disabled = 0.
  • If the redesign is not feasible, use a standard Primary XML Index instead of a Selective XML Index, as primary XML indexes do not enforce the same restrictive type promotion list.

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

Troubleshooting Guide: SQL Server Error 6376 — Selective XML Index Structure Error

Why This Error Happens

Error 6376 occurs when SQL Server detects that the XML data being indexed does not conform to the structure expected by the Selective XML Index (SXI) path definitions, often due to mismatched or missing XML schema promotion paths. This typically happens when the underlying XML column contains documents with inconsistent namespaces, unexpected node types, or structural variations that fall outside the selected paths defined during index creation. It can also surface after a database migration or upgrade to SQL Server 2025 where XML schema collections were altered or dropped without rebuilding the associated selective index paths.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Index and Column

  • Run SELECT * FROM sys.selective_xml_index_paths WHERE object_id = OBJECT_ID('YourTable') to list all defined paths.
  • Cross-reference the path causing the failure using the table/index name printed in the error message (%.*ls).
  • Note the exact XML column and promoted path expressions tied to the index.

Step 2: Validate the XML Data Against Expected Paths

  • Extract a sample of the XML data using SELECT TOP 10 XmlColumn FROM YourTable and manually inspect for namespace mismatches or malformed nodes.
  • Check if an XML Schema Collection (XSC) is bound to the column via SELECT xml_collection_id FROM sys.columns WHERE object_id = OBJECT_ID('YourTable').
  • Confirm the XSC still exists using SELECT * FROM sys.xml_schema_collections, since a missing or altered schema is a common trigger in SQL Server 2025 post-upgrade scenarios.

Step 3: Drop and Rebuild the Selective XML Index

  • Execute DROP INDEX [YourSXIName] ON [YourSchema].[YourTable]; to remove the corrupted index definition.
  • Recreate the primary XML index first (if not present) using CREATE PRIMARY XML INDEX.
  • Rebuild the selective index with corrected path statements, e.g., CREATE SELECTIVE XML INDEX [YourSXIName] ON [YourTable]([XmlColumn]) FOR ([PathName] = 'YourXPathExpression' AS [DataType] SINGLETON);.

Step 4: Check for Windows Server 2025 / Windows 11 File System or Permission Conflicts

  • Verify the SQL Server service account has full read/write access to the data and log file directories (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Open Services.msc, confirm the SQL Server (MSSQLSERVER) service is running under the correct domain/service account without “Access Denied” warnings in Event Viewer.
  • Run a consistency check with DBCC CHECKDB('YourDatabase') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying page-level corruption affecting the XML index structure.

Step 5: Apply Latest Cumulative Update

  • Confirm your build number via SELECT @@VERSION; and compare against the latest SQL Server 2025 Cumulative Update (CU) release notes.
  • Download and install the newest CU from the Microsoft Update Catalog, as early 2025 builds had known XML indexing path-resolution bugs patched in subsequent updates.

Alternative or Verification Steps

  • After rebuilding, run SELECT * FROM sys.dm_db_xml_index_physical_stats(DB_ID(), OBJECT_ID('YourTable')) to confirm the index reports a healthy state with no fragmentation or error flags.
  • If the error persists, bypass the Selective XML Index temporarily and use a standard Primary XML Index with .exist() or .value() queries as a stopgap while the schema collection and path definitions are fully audited.

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

Troubleshooting Guide: SQL Server Error 6373 – Selective XML Index Path Restriction

Why This Error Happens

Error 6373 occurs when you attempt to create or modify a Selective XML Index (SXI) using an XPath expression that contains predicates, wildcards, or complex navigation steps (such as [1], [@attribute='value'], or //). Selective XML Indexes in SQL Server 2025 only support simple path expressions that navigate directly through element and attribute names without any filtering logic. This limitation exists because the SXI engine promotes XML nodes into relational tag/path tables at index-creation time, and it cannot pre-evaluate conditional or positional logic during that promotion phase.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XPath Expression

  • Open the failing CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX ... FOR PATH statement in SSMS.
  • Locate the path string referenced in the error message (the %.*ls placeholder will show the actual path in the real error output).
  • Check specifically for predicates like [1], [last()], [@id='5'], or axis operators like // or *.

Step 2: Simplify the Path Expression

  • Rewrite the path to use only direct child/attribute navigation, e.g., change /Root/Items[1]/Item to /Root/Items/Item.
  • Remove any attribute filters; instead, promote the attribute itself as a separate simple path entry if you need to query on it.
  • Example of a valid simple path: /Customers/Customer/Address/@City.

Step 3: Recreate the Selective XML Index

  • Drop the invalid index definition if a partial object was created:
DROP INDEX IF EXISTS SXI_Customers ON dbo.CustomerXmlData;
  • Recreate it using only validated simple paths:
CREATE SELECTIVE XML INDEX SXI_Customers
ON dbo.CustomerXmlData (XmlColumn)
FOR
  PathA = '/Customers/Customer/Name' AS XQUERY 'xs:string',
  PathB = '/Customers/Customer/Address/@City' AS XQUERY 'xs:string';
  • Execute the batch in SSMS or via sqlcmd on Windows Server 2025 and confirm no errors are returned.

Step 4: Move Complex Filtering Logic to Query Time

  • If you need predicate-based filtering, apply it in your WHERE clause or XMLQUERY/value() calls at runtime instead of at index-definition time.
  • The SXI will still accelerate the underlying simple path lookup, while SQL Server applies the predicate logic during execution.

Alternative or Verification Steps

  • Run sys.xml_indexes and sys.selective_xml_index_paths catalog views to confirm the new paths are registered without errors: SELECT * FROM sys.selective_xml_index_paths WHERE object_id = OBJECT_ID('dbo.CustomerXmlData');
  • If simple paths still fail, test the XML schema structure independently using XMLQUERY in a standalone SELECT statement to confirm the path syntax is valid XPath 1.0/2.0 before re-attempting index creation.

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

Troubleshooting Guide: SQL Server Error 6374 — Invalid Path for Selective XML Index

Why This Error Happens

This error occurs when the XML path specified in a sys.selective_xml_index_paths definition contains unsupported constructs, such as wildcards, attribute-centric expressions, or namespace nodes that the Selective XML Index (SXI) engine cannot parse. SQL Server 2025 enforces stricter XQuery subset validation for SXI paths, meaning paths that worked in earlier promotion schemas (like xml column promotion via sp_xml_schema_collection) may now be rejected. Additionally, this can stem from a corrupted or incorrectly migrated index metadata entry carried over from an older database compatibility level.

Step-by-Step Resolution Guide

Step 1: Validate the XML Path Syntax Against SXI Limitations

  • Open SQL Server Management Studio (SSMS) 21 connected to your SQL Server 2025 instance.
  • Review the exact path string reported in the error message (the %.*ls placeholders will show the actual path and index name in the real error output).
  • Confirm the path does not use unsupported XQuery features for SXI, such as the // descendant-or-self operator in certain positions, * wildcards combined with predicates, or multiple consecutive namespace prefixes.
  • Cross-reference supported syntax in the “CREATE SELECTIVE XML INDEX” documentation for the 2025 release, as the grammar subset has been tightened compared to SQL Server 2022.

Step 2: Drop and Recreate the Selective XML Index with a Corrected Path

  • Run the following to identify the offending index definition:
SELECT si.name, sxip.path_expression 
FROM sys.selective_xml_index_paths sxip
JOIN sys.indexes si ON sxip.index_id = si.index_id AND sxip.object_id = si.object_id
WHERE si.name = 'YourIndexName';
  • Drop the problematic index:
DROP INDEX YourIndexName ON dbo.YourTable;
  • Recreate it using a simplified, fully qualified path expression (avoid relative wildcards):
CREATE SELECTIVE XML INDEX SXI_YourIndex 
ON dbo.YourTable(XmlColumn)
FOR (pp1 = '/Root/Element/SubElement');

Step 3: Check for Namespace Declaration Conflicts

  • Open the XML Schema Collection bound to the column via:
SELECT name, xml_collection_id FROM sys.xml_schema_collections;
  • Verify that namespace prefixes used in your path expression match exactly (case-sensitive) with those declared in the schema collection or in the WITH XMLNAMESPACES clause of your index creation script.
  • Correct any mismatched or missing namespace prefix bindings in the CREATE SELECTIVE XML INDEX statement.

Step 4: Update Database Compatibility Level and Apply Latest Cumulative Update

  • Check your current compatibility level:
SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If below 170 (SQL Server 2025’s expected level), update it:
ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • Install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as early builds had known SXI path-parsing regressions fixed in subsequent patches.

Alternative or Verification Steps

  • After recreating the index, run DBCC CHECKCONSTRAINTS and a test SELECT query using the XML path in a WHERE clause with .exist() or .value() to confirm the SXI is being used via the execution plan (look for “Selective XML Index Scan”).
  • If the error persists, as a fallback, create a standard Primary XML Index instead of a Selective XML Index on the column — this bypasses the stricter path validation rules while still improving query performance for XML data.

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

Troubleshooting Guide: Error 6371 – Duplicate Path Name in Selective XML Index

Why This Error Happens

Error 6371 occurs when you attempt to create or alter a Selective XML Index (SXI) and assign the same name to two or more different paths within the same index definition. SQL Server requires every named path in a selective XML index to be unique because these names are used internally to reference specific XML node sets for indexing and querying. This typically happens due to a copy-paste mistake in the CREATE SELECTIVE XML INDEX or sp_xml_schema_collection-related path statements, or when a schema change introduces a path that collides with an existing named path.

Step-by-Step Resolution Guide

Step 1: Locate the Conflicting Index Definition

  • Open the T-SQL script or stored procedure that issued the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX statement that triggered Error 6371.
  • Note the index name referenced in the error message (shown as %.*ls), since this tells you exactly which selective XML index definition to inspect.
  • Query metadata for existing paths using:
  SELECT * FROM sys.selective_xml_index_paths 
  WHERE object_id = OBJECT_ID('YourTableName');

Step 2: Identify and Rename the Duplicate Path

  • Review each PATH (...) AS [name] clause in your index creation script.
  • Check carefully for two paths that share an identical AS [name] alias, even if their XPath expressions differ.
  • Rename one of the duplicate aliases to something unique and descriptive, for example:
  PATH ('/Root/Customer/Name') AS CustomerName,
  PATH ('/Root/Vendor/Name') AS VendorName  -- renamed from duplicate "Name"
  • Save the corrected script before re-running it.

Step 3: Drop and Recreate the Selective XML Index

  • If the index partially exists from a failed prior attempt, drop it first:
  DROP XML INDEX IF EXISTS SXI_Index_Name ON YourTableName;
  • Re-run the corrected CREATE SELECTIVE XML INDEX statement with unique path names applied.
  • Confirm the statement completes with “Commands completed successfully” and no further 6371 errors appear in the SQL Server Error Log or Event Viewer (Event ID matching SQL Server Database Engine source).

Step 4: Validate Schema Collections (If Applicable)

  • If your XML column is schema-bound, cross-check the associated XML Schema Collection for any path promotions that might auto-generate conflicting names.
  • Use sp_help_xml_schema_collection or inspect sys.xml_schema_collections to confirm no overlapping namespace paths are causing indirect duplication.

Alternative or Verification Steps

  • Verify the fix by re-querying sys.selective_xml_index_paths to confirm each path_name value is distinct for the given object_id.
  • As an alternative, use SQL Server Management Studio (SSMS) 21’s built-in “Script Index As” feature to regenerate the index definition visually, which highlights naming conflicts before execution.

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

Troubleshooting Guide: Error 6372 – Duplicate Path Mapping in Selective XML Index (SQL Server 2025)

Why This Error Happens

This error occurs when creating or altering a Selective XML Index (SXI) and the same XML path expression has been specified more than once using SQL data type mappings within the same secondary XML index definition. SQL Server requires every path in a selective XML index to be unique because each path promotion creates a distinct relational representation of the XML node, and duplicate mappings create ambiguous storage instructions. This typically results from copy-pasted CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX ... FOR statements where path entries were not properly deduplicated, or from auto-generated DDL scripts that merged multiple schema definitions referencing the same XML node.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Path Expression

  • Open the exact T-SQL script that triggered Error 6372 and locate the CREATE SELECTIVE XML INDEX or the secondary promoted path index statement.
  • Review the error message text closely — it references the index name (%.*ls), so confirm which XML index object is affected.
  • Use the following query to inspect existing promoted paths on the table:
  SELECT * FROM sys.xml_index_nodes 
  WHERE object_id = OBJECT_ID('YourTableName');

Step 2: Remove or Consolidate Duplicate Path Mappings

  • Open the index creation script in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Search for repeated PATH clauses pointing to the same XML node (e.g., '/Root/Customer/Name' appearing twice with different SQL types like NVARCHAR and INT).
  • Delete the duplicate entry, keeping only one SQL data type mapping per unique path expression.
  • If two different data types are genuinely required for the same node, create a secondary selective XML index using FOR with a distinct index name instead of duplicating the path in the same definition.

Step 3: Drop and Recreate the Selective XML Index

  • Drop the problematic index to clear any partial metadata:
  DROP INDEX IF EXISTS SXI_YourIndexName ON dbo.YourTableName;
  • Recreate it using the corrected, deduplicated path list:
  CREATE SELECTIVE XML INDEX SXI_YourIndexName 
  ON dbo.YourTableName (XmlColumn)
  FOR (PATHS 
       (
         '/Root/Customer/Name' AS NVARCHAR(100),
         '/Root/Customer/OrderID' AS INT
       )
  );
  • Ensure no path string appears twice across the PATHS list, including case-sensitive or whitespace-variant duplicates.

Step 4: Validate Schema Source If Auto-Generated

  • If the DDL was generated by a migration tool or ORM (e.g., Entity Framework, SSDT project), check the source XML schema collection (XML SCHEMA COLLECTION) for redundant node definitions.
  • Regenerate the deployment script after fixing the schema collection to prevent the duplication from reoccurring in future deployments.

Alternative or Verification Steps

  • After recreating the index, run sys.xml_selective_index_paths to confirm each path appears exactly once:
    SELECT path_expression, sql_data_type FROM sys.xml_selective_index_paths WHERE xml_index_id = (SELECT index_id FROM sys.indexes WHERE name = 'SXI_YourIndexName');
  • If the error persists despite a clean script, restart the SQL Server 2025 instance service via Services.msc (on Windows Server 2025/Windows 11) to clear any cached execution plans or metadata locks tied to the prior failed index build, then re-run the CREATE SELECTIVE XML INDEX statement.

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

Troubleshooting Guide: SQL Server Error 6369 – MAX_LENGTH Option Invalid for Selective XML Index

Why This Error Happens

This error occurs when a selective XML index (SXI) promoted path definition attempts to apply the MAX_LENGTH option to a SQL type that does not support the maxLength facet, such as float, datetime, or decimal without appropriate configuration. The MAX_LENGTH facet is only valid for variable-length character-based types (like nvarchar or varchar) because it defines a storage boundary for string data. This typically stems from a mismatch between the XML schema collection’s defined node type and the SQL type specified in the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... FOR statement.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Path and Type

  • Open SQL Server Management Studio (SSMS) and locate the exact script that generated the error.
  • Run the following query to review existing selective XML index definitions and their associated types:
SELECT * FROM sys.selective_xml_index_paths 
WHERE xml_index_id = (SELECT object_id FROM sys.indexes WHERE name = 'YourIndexName');
  • Note the specific SQL_TYPE assigned to the path causing the conflict.

Step 2: Correct the SQL Type Assignment

  • Modify the CREATE SELECTIVE XML INDEX statement to remove MAX_LENGTH from types incompatible with the facet (e.g., INT, BIGINT, DATETIME2).
  • If the underlying XML node is genuinely textual, ensure the promoted type is explicitly cast as NVARCHAR or VARCHAR rather than a numeric or temporal type.
  • Example of a corrected syntax structure:
CREATE SELECTIVE XML INDEX SXI_Index ON dbo.XmlTable(XmlColumn)
FOR (
    PATH1 = '/root/node' AS XQUERY 'xs:string' MAX_LENGTH = 100
);

Step 3: Drop and Rebuild the Index

  • If the index was partially created or left in a corrupted state due to the failed transaction, drop it manually:
DROP INDEX SXI_Index ON dbo.XmlTable;
  • Re-run the corrected CREATE SELECTIVE XML INDEX script to rebuild the index with the valid facet configuration.

Step 4: Validate XML Schema Collection Compatibility

  • If the table uses a bound XML Schema Collection (XSD), verify that the xs:element type in the schema aligns with the SQL promoted type.
  • Use sys.xml_schema_collections to cross-reference the schema’s native data type against the index definition to prevent future facet mismatches.

Alternative or Verification Steps

  • Verification: After recreating the index, run DBCC CHECKDB or query sys.indexes to confirm the index_id is active and is_disabled is set to 0.
  • Alternative: If type mismatches persist due to complex XSD constraints, consider using a standard (non-selective) Primary XML Index instead, as it does not require explicit facet-based type promotion for every path.

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

Troubleshooting Guide: SQL Server Error 6370 — MAX_LENGTH Option Conflict with ‘node()’ in Selective XML Index

Why This Error Happens

This error occurs because the MAX_LENGTH option is only valid for XML path types that resolve to scalar values like sql_variant, not for paths that return node() types. When you define a selective XML index (SXI) secondary index and specify a path that evaluates to node(), SQL Server rejects the MAX_LENGTH specification because node-type paths store structural XML fragments rather than fixed-length scalar data. This typically happens when a path expression in the CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... USING XML INDEX statement is ambiguous or incorrectly typed, causing the engine to infer node() instead of a scalar type.

Step-by-Step Resolution Guide

Step 1: Review the Selective XML Index Definition

  • Open SQL Server Management Studio (SSMS) and locate the T-SQL script that created the failing index.
  • Identify the specific path in the FOR clause (e.g., /Root/Customer/@id) that is associated with the MAX_LENGTH option.
  • Check the XML schema collection (if bound) to confirm what data type that node actually resolves to.

Step 2: Correct the Path Expression or Remove MAX_LENGTH

  • If the path is intended to return a scalar value (like an attribute or text node), adjust the XPath expression to explicitly target the scalar, for example changing /Root/Customer to /Root/Customer/@CustomerID.
  • If the path is genuinely meant to return a node() (a complex XML fragment), remove the MAX_LENGTH clause entirely from that path’s definition since it is unsupported for this type.
  • Example corrected syntax:
  CREATE SELECTIVE XML INDEX SXI_Main ON dbo.XmlTable(XmlColumn)
  FOR (PathCustomerID = '/Root/Customer/@CustomerID' AS SQL VARCHAR(50))

Step 3: Drop and Recreate the Index

  • Run DROP XML INDEX SXI_Main ON dbo.XmlTable; to remove the faulty index definition.
  • Re-run the corrected CREATE SELECTIVE XML INDEX statement with the updated path/type mapping.
  • Check the SQL Server Error Log via EXEC sp_readerrorlog 0, 1, 'XML Index'; to confirm no residual errors were logged during creation.

Step 4: Validate XML Schema Collection Bindings (If Applicable)

  • If the XML column uses XML(SchemaCollection), run SELECT * FROM sys.xml_schema_collections; to verify the schema definitions align with the expected node types.
  • Update the schema collection using ALTER XML SCHEMA COLLECTION if a type mismatch is causing the engine to infer node() unexpectedly.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths to confirm the path’s path_type column shows a scalar type (e.g., VALUE) rather than NODE for the corrected path.
  • If the error persists, as a workaround, create a standard Primary XML Index instead of a Selective XML Index for that column, since primary XML indexes do not require MAX_LENGTH type enforcement on node paths.

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

Troubleshooting Guide: SQL Server Error 6367 — “XSD Data Type Not Allowed for Selective XML Index”

Why This Error Happens

This error occurs when you attempt to create or promote a path in a Selective XML Index (SXI) on a column whose XML schema collection (XSD) defines a data type that SQL Server does not support for selective indexing, such as xs:anyType, union types, or certain list-based types. SQL Server 2025 enforces strict type validation against the registered XML Schema Collection before allowing a path to be included in the selective index node table. This typically stems from a mismatch between the schema’s type definitions and the restricted subset of XSD primitive/simple types that the Selective XML Index engine can translate into relational storage.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XSD Type and Path

  • Run the failing CREATE SELECTIVE XML INDEX or CREATE XML INDEX ... FOR PATH statement again and capture the full error text, noting the exact type name and path reported in the %.*ls placeholders.
  • Query sys.xml_schema_collections and sys.xml_schema_components to locate where that type is defined:
  SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Cross-reference the path against your XSD file to confirm whether it resolves to xs:anyType, xs:anySimpleType, a union, or a list type.

Step 2: Modify the XML Schema Collection to Use a Supported Type

  • Edit the source .xsd file (commonly stored in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Schemas\ or your application’s schema repository) to replace the unsupported type with a supported simple type such as xs:string, xs:int, xs:decimal, or xs:dateTime.
  • Drop and re-register the updated schema collection:
  DROP XML SCHEMA COLLECTION YourSchemaCollectionName;
  GO
  CREATE XML SCHEMA COLLECTION YourSchemaCollectionName AS N'<paste updated XSD here>';
  GO
  • If the schema is used in production, stage this change first in a Windows Server 2025 test instance to validate no downstream XML validation breaks.

Step 3: Exclude or Re-map the Unsupported Path in the Selective XML Index Definition

  • When defining the SXI, explicitly exclude paths that resolve to unsupported types using the FOR PATH clause with a narrower XPath expression rather than selecting the entire node subtree.
  • Example of a corrected definition:
  CREATE SELECTIVE XML INDEX SXI_Orders ON dbo.OrdersTable(XmlColumn)
  FOR 
  (
      PathOrderId = '/Order/Id' AS SQL VARCHAR(50),
      PathOrderDate = '/Order/Date' AS SQL DATETIME2
  );
  • Avoid wildcard paths (//*) when the underlying schema contains mixed or abstract types.

Step 4: Rebuild and Validate the Index

  • After correcting the schema and path definitions, rebuild the selective XML index:
  ALTER INDEX SXI_Orders ON dbo.OrdersTable REBUILD;
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm Error 6367 no longer appears during the rebuild operation.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_index_paths to confirm all intended paths were successfully registered with valid SQL type mappings.
  • If re-mapping types is not feasible due to application constraints, use a standard (non-selective) Primary/Secondary XML Index instead, which supports the full XSD type range without the selective type restrictions.

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

Troubleshooting Guide: SQL Server Error 6368 – Selective XML Index Conflict with XML Schema Collection

Why This Error Happens

This error occurs because Selective XML Index (SXI) does not support explicit XSD type declarations when the underlying XML column is already bound to an XML Schema Collection via CREATE XML SCHEMA COLLECTION. SQL Server 2025 enforces strict validation rules that prevent a secondary, manually-specified XSD type from conflicting with the schema-driven typing already applied to the column. Essentially, the engine refuses to let two competing type-definition sources (the schema collection and the manual XSD type in the index definition) govern the same XML data simultaneously.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Column and Schema Collection

  • Run the following query to confirm which column is tied to an XML Schema Collection:
SELECT c.name AS ColumnName, t.name AS TableName, xsc.name AS SchemaCollectionName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.xml_schema_collections xsc ON c.xml_collection_id = xsc.xml_collection_id
WHERE t.name = '<YourTableName>';
  • Note the exact XSD type referenced in your CREATE SELECTIVE XML INDEX statement, as this is the value causing the conflict.

Step 2: Remove the Explicit XSD Type from the Index Definition

  • Open your SXI creation script (usually a .sql deployment file in your project repository or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Scripts\).
  • Locate the CREATE SELECTIVE XML INDEX statement and remove the FOR ([path] AS XQUERY 'xsd_type') clause that manually specifies the XSD type.
  • Example corrected syntax:
CREATE SELECTIVE XML INDEX SXI_Index
ON dbo.YourTable (XmlColumn)
FOR (
    [Path1] = '/root/element' AS XQUERY 'string'  -- remove this clause if column is schema-bound
);

Step 3: Let SQL Server Infer Typing from the Schema Collection

  • Since the column already has an associated schema collection, simply omit the AS XQUERY type clause entirely for that path.
  • Re-run the CREATE SELECTIVE XML INDEX statement without specifying a competing type.
  • Validate the schema collection itself is not corrupted:
EXEC sp_help '<SchemaCollectionName>';

Step 4: Rebuild the Selective XML Index

  • Drop the failed or partially created index:
DROP INDEX SXI_Index ON dbo.YourTable;
  • Recreate it using corrected syntax from Step 2/3.
  • If the table is large, run this during a maintenance window since SXI builds can be resource-intensive on Windows Server 2025 hosts.

Alternative or Verification Steps

  • Verify the fix by querying sys.selective_xml_indexes and sys.selective_xml_index_paths to confirm the index was created successfully without errors.
  • If the issue persists, consider unbinding the schema collection temporarily (ALTER TABLE ... ALTER COLUMN ... XML(NULL)), creating the SXI with explicit typing, then re-binding the schema collection afterward — though this is only a workaround for edge cases, not a long-term best practice.

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

Troubleshooting Guide: SQL Server Error 6365 – XML Data Type Exceeding 2GB

Why This Error Happens

This error occurs because the xml data type in SQL Server has a hard architectural limit of 2GB per value, and an operation—such as a concatenation, FOR XML query, modification via .modify(), or a large data import—has produced a result that exceeds this ceiling. It is most commonly triggered by recursive or iterative XML aggregation (e.g., building a large XML document in a loop) without size validation, or by importing a malformed/oversized XML source file. In rare cases, corrupted intermediate data or a runaway recursive query can also inflate the XML payload unexpectedly before the operation aborts.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Process

  • Review SQL Server error logs and query history to pinpoint the exact statement throwing Error 6365.
  • Check sys.dm_exec_query_stats and sys.dm_exec_requests for long-running or high-memory-grant queries involving XML columns.
  • Look specifically for FOR XML AUTO/PATH, .modify(), .query(), or CAST/CONVERT operations on large datasets.

Step 2: Break Down Large XML Operations into Smaller Batches

  • Refactor the query to paginate results using OFFSET/FETCH or batch processing with a loop that commits smaller chunks.
  • Avoid concatenating XML fragments in a single in-memory variable; instead, write intermediate results to a staging table.
  • Example: Replace a single FOR XML PATH('') call over millions of rows with batches of 10,000–50,000 rows at a time.

Step 3: Validate and Sanitize Source XML Data

  • If importing external XML files, confirm the source file size and structure using PowerShell:
  • Get-Item "C:\Data\import.xml" | Select-Object Length
  • Open the file in a validator (e.g., XML Notepad or Visual Studio XML Editor) to check for duplicate nodes, malformed tags, or unintended recursive elements causing bloat.
  • Strip unnecessary namespaces or redundant nested elements before re-importing.

Step 4: Increase Resource Allocation and Monitor Memory Grants (If Applicable)

  • Navigate to SQL Server Management Studio (SSMS) → Server Properties → Memory, and confirm Maximum Server Memory is not artificially constraining large operation buffers.
  • On Windows Server 2025, verify the SQL Server service account has sufficient virtual memory allocation via:
  • Control Panel → System → Advanced System Settings → Performance Settings → Advanced → Virtual Memory
  • Restart the SQL Server service after adjustments:
  • Restart-Service -Name 'MSSQLSERVER'

Step 5: Apply Latest Cumulative Update for SQL Server 2025

  • Check your current build version:
  • SELECT @@VERSION;
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as XML handling edge-case bugs are periodically patched.
  • Reboot the server and re-run the original operation to confirm stability.

Alternative or Verification Steps

  • Re-run the original query or import job after batching; monitor execution using SELECT DATALENGTH(XMLColumn) to confirm output stays under the 2GB (2,147,483,647 byte) threshold.
  • If the error persists, consider storing the data as VARBINARY(MAX) with application-level XML parsing instead of relying on native SQL Server XML processing for extremely large datasets.

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

Troubleshooting Guide: SQL Server Error 6366 – Invalid Type for Element

Why This Error Happens

This error occurs when registering an XML Schema Collection in SQL Server 2025 that defines an element using the built-in XSD types ID, IDREF, IDREFS, or any custom simple type derived from them. SQL Server’s XML type system intentionally blocks these types from being assigned directly to elements because ID/IDREF are designed for attribute-based uniqueness constraints, not element content validation. This typically surfaces when importing third-party or legacy XSD files into CREATE XML SCHEMA COLLECTION statements without first auditing the schema for unsupported type usage.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XSD File and Element

  • Locate the exact XML Schema Collection causing the failure using: SELECT name, definition FROM sys.xml_schema_collections WHERE name = 'YourSchemaName';
  • Open the source .xsd file in a text editor or XML IDE (e.g., Visual Studio, VS Code with XML extension).
  • Search for type="xs:ID", type="xs:IDREF", or type="xs:IDREFS" within <xs:element> declarations.
  • Note the exact line number and element name matching the %s placeholder in the error message.

Step 2: Modify the Schema to Remove ID/IDREF from Elements

  • Change the offending element’s type from xs:ID or xs:IDREF to xs:string or another non-restricted simple type.
  • Example fix: <xs:element name="RecordKey" type="xs:ID"/> becomes <xs:element name="RecordKey" type="xs:string"/>.
  • If uniqueness enforcement is still required, move the ID/IDREF constraint to an attribute instead of an element, since SQL Server permits these types on attributes.
  • Save the corrected .xsd file to a new version path (e.g., C:\Schemas\corrected_schema_v2.xsd) to preserve the original for reference.

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

  • Drop the existing broken collection if it was partially created: DROP XML SCHEMA COLLECTION YourSchemaName;
  • Register the corrected version using SQL Server Management Studio (SSMS) or sqlcmd: CREATE XML SCHEMA COLLECTION YourSchemaName AS N'<paste corrected schema XML here>';
  • If loading from disk, use PowerShell to inject file contents into a variable before executing the T-SQL command, since CREATE XML SCHEMA COLLECTION does not natively read file paths.

Step 4: Validate Dependent Objects and Permissions

  • Check that the executing login has ALTER permission on the schema or db_ddladmin role membership, since permission issues can mask as unrelated XML errors in SQL Server 2025.
  • Review any tables, stored procedures, or XML columns referencing the old schema collection and re-link them if the collection was dropped and recreated with a new object ID.
  • Run sp_help 'YourSchemaName' to confirm the schema is registered correctly post-fix.

Alternative or Verification Steps

  • Verify the fix by running a test INSERT or CAST operation against an XML column bound to the corrected schema collection; it should complete without raising Error 6366.
  • If the third-party schema cannot be modified (e.g., vendor-locked XSD), use an XSLT transformation step to strip ID/IDREF type declarations before the XML payload is validated against the SQL Server schema collection.

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

Troubleshooting Guide: SQL Server Error 6362 — Alter Schema Collection Conflict

Why This Error Happens

This error occurs because SQL Server enforces strict XML schema evolution rules, and it will not allow an ALTER XML SCHEMA COLLECTION operation when the existing schema contains a lax wildcard (processContents="lax") or an element/attribute typed as xs:anyType. These constructs introduce ambiguity that SQL Server’s type system cannot safely reconcile during an incremental schema merge. Essentially, the engine cannot guarantee validation integrity when adding new components to a schema that already permits “any” content without strict typing.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Schema Component

  • Run the following query to inspect the existing schema collection definition:
  SELECT xml_schema_namespace(N'dbo', N'YourSchemaCollectionName');
  • Review the output for xs:any elements with processContents="lax" or processContents="skip", and for any elements/attributes explicitly or implicitly typed as xs:anyType.
  • Note the exact namespace and component causing the lax definition.

Step 2: Drop and Recreate Instead of Altering

  • Since ALTER XML SCHEMA COLLECTION cannot modify a schema containing lax wildcards, export the full current schema XML to a local file (e.g., C:\SQLSchemas\CurrentSchema.xml) using the query from Step 1.
  • Manually edit the XML file to change processContents="lax" to processContents="strict" (or remove the xs:anyType reference) and add your new schema components directly into this file.
  • Drop the existing collection:
  DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Recreate it in full using the merged XML file:
  CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS
  N'<xsd:schema ... >...</xsd:schema>';

Step 3: Update Dependent Objects

  • If any XML-typed columns, parameters, or variables reference the dropped schema collection, re-bind them after recreation since DROP will fail if dependencies exist.
  • Script out dependent table definitions first using SSMS (Generate Scripts > Advanced > Script XML Schema Collection) before dropping, so you can reapply column bindings cleanly.
  • Re-run CREATE XML SCHEMA COLLECTION first, then re-create or re-alter dependent tables/columns to point back to the schema.

Step 4: Validate Server and Compatibility Level

  • Confirm the database compatibility level supports your schema operations:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • On Windows Server 2025/Windows 11 hosts, ensure the SQL Server 2025 instance has the latest Cumulative Update applied, as early XML schema validation bugs in CU-level builds have caused false-positive 6362 errors.

Alternative or Verification Steps

  • After recreating the schema collection, verify success by running SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName'; and confirming no errors on a test ALTER with a trivial addition.
  • If dropping is not feasible due to heavy dependencies, consider creating a new schema collection version (e.g., SchemaV2) and migrating columns incrementally instead of altering the original lax-typed collection.

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

Troubleshooting Guide: Error 6363 — ALTER SCHEMA COLLECTION Failed on Schema-Bound Collection

Why This Error Happens

This error occurs because the XML Schema Collection you are trying to modify is referenced by a schema-bound object (such as a table column, function, or stored procedure) that uses WITH SCHEMABINDING. SQL Server 2025 blocks alterations to schema collections configured with lax validation (lax or skip processing contents) when schema binding is active, because doing so could invalidate dependent objects without warning. Essentially, the engine is protecting data integrity by preventing structural changes to a collection that other bound objects depend on for validation guarantees.

Step-by-Step Resolution Guide

Step 1: Identify All Dependent Schema-Bound Objects

  • Run sys.sql_expression_dependencies or sys.xml_schema_collections joined with sys.columns to locate every object bound to the target schema collection.
  • Use the following query to list dependencies: SELECT referencing_entity_name FROM sys.dm_sql_referencing_entities('dbo.YourSchemaCollection', 'OBJECT');
  • Note every table, column, function, or procedure using WITH SCHEMABINDING tied to this collection.

Step 2: Remove Schema Binding from Dependent Objects

  • For columns using the XML schema collection with DOCUMENT or CONTENT typing, run ALTER TABLE YourTable ALTER COLUMN YourXmlColumn XML(CONTENT dbo.YourSchemaCollection) without the schema-bound dependency temporarily, or drop the constraint if applicable.
  • For functions or stored procedures, execute ALTER FUNCTION/ALTER PROCEDURE and remove the WITH SCHEMABINDING clause from the definition.
  • Script out the original object definitions first using SQL Server Management Studio (SSMS) 21 “Script Object as ALTER” feature, so they can be restored later.

Step 3: Perform the ALTER SCHEMA COLLECTION Operation

  • Execute your intended ALTER XML SCHEMA COLLECTION dbo.YourSchemaCollection ADD 'YourNewSchemaDefinition' statement now that binding is removed.
  • Confirm the statement completes without Error 6363 appearing in the Messages pane.

Step 4: Reapply Schema Binding to Dependent Objects

  • Re-run the original CREATE/ALTER scripts captured in Step 2, reinstating WITH SCHEMABINDING on each affected function, procedure, or column definition.
  • Validate each object compiles successfully against the updated schema collection structure.

Alternative or Verification Steps

  • Verify the fix by querying sys.xml_schema_collections and re-running sys.dm_sql_referencing_entities to confirm all dependent objects are re-bound without errors.
  • If reapplying schema binding fails due to incompatible XML content, consider creating a new schema collection version (e.g., dbo.YourSchemaCollection_v2) and migrating objects individually rather than altering the live collection in place.

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

Troubleshooting Guide: Error 6364 – ALTER SCHEMA COLLECTION Failed (XML Revalidation Error)

Why This Error Happens

This error occurs when SQL Server attempts to revalidate existing XML data in a column against an updated or altered XML Schema Collection, and the stored data no longer conforms to the new schema definition. This typically happens after a schema collection is modified (via ALTER XML SCHEMA COLLECTION) to add stricter type constraints, required elements, or changed data types, while legacy data in the table still reflects the old, more permissive schema. It can also occur due to partial or corrupted schema collection imports where element definitions conflict with existing XML instance documents.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Validation Conflict

  • Review the full error message text following “did not succeed due to the following reason” — this contains the specific XSD validation failure (e.g., missing required element, invalid enumeration value, or type mismatch).
  • Run the following query to locate the offending table and column:
SELECT t.name AS TableName, c.name AS ColumnName, xsc.name AS SchemaCollectionName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.xml_schema_collections xsc ON c.xml_collection_id = xsc.xml_collection_id
WHERE xsc.name = 'YourSchemaCollectionName';
  • Note the TableName and ColumnName returned for use in the next step.

Step 2: Export and Inspect the Existing XML Data

  • Query the actual XML content stored in the flagged column to compare it against the new schema rules:
SELECT ColumnName
FROM TableName
WHERE ColumnName.exist('/*') = 1;
  • Use SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) to open the XML result in the grid and click through to view it in the XML editor.
  • Cross-reference the document structure against the .xsd file you are trying to apply via the ALTER SCHEMA COLLECTION statement.

Step 3: Correct the Mismatched Data or Adjust the Schema

  • Option A (Fix the Data): Update the non-conforming rows using .modify() XQuery expressions to insert missing nodes or correct invalid values so they match the new schema.
  • Option B (Fix the Schema): If the data is correct but the schema is overly strict, revise the .xsd file to use minOccurs="0" for optional elements or broaden restrictive simpleType enumerations before re-running the ALTER SCHEMA COLLECTION command.
  • Save your changes and re-run the ALTER XML SCHEMA COLLECTION [YourSchemaCollectionName] ADD '<schema file content>' statement.

Step 4: Clear Cached Execution Plans and Metadata

  • If the alteration still fails intermittently despite seemingly valid data, flush the plan cache in case stale metadata is referencing the old schema version:
DBCC FREEPROCCACHE;
  • Restart the “SQL Server (MSSQLSERVER)” service via services.msc on Windows Server 2025 if the issue persists after cache clearing, ensuring no active user connections are interrupted during a maintenance window.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original ALTER SCHEMA COLLECTION T-SQL command; if it completes with “Command(s) completed successfully,” query the table again using the .exist() method to confirm all rows now pass validation (result should consistently return 1).
  • Alternative Solution: If immediate correction of all legacy rows is not feasible, consider dropping the XML type binding temporarily (convert the column to untyped XML), perform a bulk data cleanup via a script, and then reapply the strict schema collection to the column afterward.

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

Troubleshooting Guide: Error 6360 — “%d is not a valid style number when converting from XML”

Why This Error Happens

This error occurs when a Transact-SQL statement uses the CONVERT() function to cast data to or from the XML data type with a style parameter that falls outside the range of values SQL Server recognizes (typically 0, 1, or 2 for XML conversions). It is most commonly caused by a typo, a hardcoded legacy value carried over from an older application, or dynamically generated SQL that passes an invalid integer into the style argument. In some cases, this surfaces after migrating databases to SQL Server 2025 on Windows Server 2025, where stricter validation of conversion styles exposes queries that previously ran on looser legacy engines.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact statement using SQL Server Profiler, Extended Events, or the Query Store (sys.query_store_query_text) to find the query throwing Error 6360.
  • Look specifically for CONVERT(xml, @value, style) or CONVERT(varchar, @xmlcolumn, style) patterns.
  • Note the literal or variable being passed as the style argument.

Step 2: Correct the Style Parameter Value

  • Confirm that only valid XML conversion styles are used: 0 (default, no whitespace preservation) or 1 (preserve whitespace); style 2 is accepted in some internal paths but is undocumented, so avoid relying on it.
  • Edit the query to replace the invalid number, for example change CONVERT(xml, @data, 128) to CONVERT(xml, @data, 1).
  • If the style value is generated dynamically (e.g., from a config table or application variable), add a validation check in T-SQL:
  IF @style NOT IN (0,1)
      SET @style = 0;

Step 3: Audit Stored Procedures and Linked Application Code

  • Search all stored procedures, views, and functions for CONVERT(...xml...) calls:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%CONVERT%xml%';
  • Check any ORM frameworks (Entity Framework, Dapper) or ETL packages (SSIS) that auto-generate XML conversion syntax, since upgraded drivers for SQL Server 2025 may pass deprecated style codes.
  • Update connection strings or driver versions if an outdated OLE DB/ODBC driver is forcing a legacy style number.

Step 4: Apply and Deploy the Fix

  • Deploy the corrected script or stored procedure to the target instance.
  • Restart the SQL Server Agent service if the fix lives in a scheduled job, via services.msc on Windows Server 2025 or:
  Restart-Service -Name SQLSERVERAGENT

Alternative or Verification Steps

  • Re-run the original query or job manually in SQL Server Management Studio (SSMS) and confirm Error 6360 no longer appears in the Messages tab.
  • If the error persists, enable trace flag 3604 and run DBCC TRACEON(3604) during a test execution to get verbose conversion error output, helping pinpoint remaining invalid style references in nested function calls.

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

Troubleshooting Guide: Error 6361 – “Invalid Null Parameter Specified” (XML Schema Collections)

Why This Error Happens

This error occurs when a T-SQL statement attempts to execute CREATE XML SCHEMA COLLECTION or a related operation (such as ALTER XML SCHEMA COLLECTION) while passing a NULL value as the source XML definition instead of a valid, non-null XML document or variable. SQL Server 2025 strictly validates that the schema source parameter contains actual XSD content, and it rejects the batch outright if the application layer, ORM, or stored procedure fails to populate that variable correctly. This is typically caused by an uninitialized variable in application code, a failed data retrieval step upstream (such as reading a corrupted or missing .xsd file), or a parameter mapping issue in middleware (like ADO.NET or ODBC) that defaults to NULL when a bind variable is empty.

Step-by-Step Resolution Guide

Step 1: Verify the Source Variable or Parameter

  • Open the stored procedure or script that triggers the CREATE XML SCHEMA COLLECTION statement.
  • Check if the variable being passed (e.g., @xmlSchema) is being set via a prior SELECT or file read operation.
  • Run a quick diagnostic query to confirm the value isn’t null before execution:
  IF @xmlSchema IS NULL
      PRINT 'Error: Schema variable is NULL - check source data';

Step 2: Inspect the Application/Middleware Connection Layer

  • If the error originates from an external application (e.g., .NET, Java, or Python script) rather than raw T-SQL, check the connection string and ORM mapping logic.
  • Open Event Viewer on Windows Server 2025 (Windows Logs > Application) and filter for Event ID 6361 to correlate the exact timestamp with the application’s connection pool logs.
  • Verify that the file path or network resource supplying the XSD content (e.g., a UNC path like \\FileServer\Schemas\invoice.xsd) is reachable and not returning an empty stream due to permission issues.

Step 3: Validate File and Share Permissions

  • If the XML schema is sourced from a file on disk, navigate to the folder path and verify the SQL Server service account has Read access.
  • Right-click the folder (e.g., C:\SQLData\Schemas\), go to Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) is listed with at least Read permissions.
  • Restart the SQL Server service via services.msc or run the following in PowerShell to apply permission changes immediately:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Rebuild the Schema Collection Manually

  • As a direct fix, explicitly cast a known-good XSD string into the variable before executing the creation command to rule out corruption:
  DECLARE @xmlSchema XML = N'<xsd:schema>...</xsd:schema>';
  CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS @xmlSchema;
  • If this succeeds, the root cause is confirmed to be upstream data retrieval rather than a SQL Server engine bug.

Alternative or Verification Steps

  • Verification: Query sys.xml_schema_collections after running the fix to confirm the new collection appears in the metadata: SELECT * FROM sys.xml_schema_collections WHERE name = 'MySchemaCollection';
  • Alternative: If the data source is a legacy application that cannot be patched immediately, implement a COALESCE or ISNULL check at the stored procedure level to throw a custom, more descriptive error (e.g., RAISERROR('Source XSD missing', 16, 1)) before the engine attempts the null creation, preventing the generic 6361 error from obscuring the actual upstream failure.

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

Troubleshooting Guide: Error 6358 — “%d is not a valid style number when converting to XML”

Why This Error Happens

This error occurs when a Transact-SQL query uses the FOR XML clause with an explicit style number (typically passed to the xml data type conversion or formatting directive) that falls outside the range of values SQL Server recognizes as valid. It is almost always caused by a typo, a hardcoded legacy style number left over from an older SQL Server version, or dynamically generated SQL that calculates the style value incorrectly. In rarer cases, this can surface after an in-place upgrade to SQL Server 2025 if deprecated style codes that were silently tolerated in earlier engine versions have since been removed or stricter validation has been introduced.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query text using SQL Server Profiler, Extended Events, or the sys.dm_exec_query_stats / sys.dm_exec_sql_text DMVs filtered by Error 6358 correlation.
  • Search the query for CONVERT(), CAST(), or FOR XML clauses that include a numeric style parameter (e.g., CONVERT(xml, @data, 131)).
  • Note the exact style value being passed — this is the %d referenced in the error message.

Step 2: Validate the Style Number Against Supported Values

  • Cross-reference the style number against Microsoft’s official documentation for CONVERT with xml data type (valid values are typically 0, 1, 2, 131, and a small set of others depending on direction of conversion).
  • Confirm whether the style number was inherited from legacy code targeting SQL Server 2008/2012 — some undocumented or deprecated style codes may no longer be honored in SQL Server 2025.
  • If the value is being generated dynamically (e.g., via a variable or application parameter), add input validation/sanitization in the application layer or stored procedure to restrict allowed values.

Step 3: Correct the Query and Redeploy

  • Edit the stored procedure, view, or application code to replace the invalid style number with a supported one.
  • Example fix: SELECT CONVERT(xml, @XmlData, 1) instead of an out-of-range style like 999 or a transposed digit.
  • If using Object Explorer in SQL Server Management Studio (SSMS) 21, right-click the affected stored procedure under Databases > [YourDB] > Programmability > Stored Procedures, select Modify, apply the correction, and execute to update the definition.
  • Redeploy the corrected object to any affected environments (Dev, QA, Production) using your standard deployment pipeline or sqlpackage.exe.

Step 4: Check for Upgrade-Related Compatibility Issues

  • If the error only appeared after upgrading to SQL Server 2025, check the database compatibility level: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Temporarily test with an older compatibility level (e.g., 160) using ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 160; to confirm whether behavior changes are compatibility-related, then plan remediation before reverting to the latest level.

Alternative or Verification Steps

  • Re-run the corrected query or execute the affected stored procedure manually in SSMS/Azure Data Studio and confirm it returns valid XML output without raising Error 6358.
  • Enable SQL Server Error Logs and Extended Events session monitoring for a 24-48 hour period post-fix to confirm Error 6358 no longer appears in sys.dm_os_ring_buffers or the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.

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

Why This Error Happens

SQL Server 2025’s XML parser blocks internal Document Type Definitions (DTDs) by default as a security measure against XML External Entity (XXE) injection attacks and denial-of-service vectors like the “billion laughs” exploit. When a query attempts to parse or cast a string containing an internal subset DTD into the native xml data type without explicitly permitting it, the engine throws Error 6359. This is a deliberate parser restriction, not a corruption or permissions issue — it requires an explicit opt-in via a CONVERT style flag to relax DTD handling.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the T-SQL statement that casts or converts a string to xml (e.g., CAST(@xmlString AS XML) or CONVERT(XML, @xmlString)).
  • Check the source XML payload for a <!DOCTYPE ... [ ... ]> declaration — this internal subset is what triggers the block.
  • Confirm the error in SQL Server Management Studio (SSMS) or via Extended Events capturing Error 6359 with the exact query text.

Step 2: Modify the Conversion Syntax to Use Style 2

  • Rewrite the conversion call to explicitly enable limited internal subset DTD support using style option 2:
  • SET @xmlDoc = CONVERT(XML, @xmlString, 2);
  • Note that style 2 only permits a restricted subset of DTD features (basic entity declarations) and does not re-enable external DTD/DOCTYPE fetching, so SSRF-style external entity attacks remain blocked.
  • Update any stored procedures, SSIS packages, or application-layer queries (ADO.NET, ODBC, JDBC) that build XML conversions dynamically to include this style parameter.

Step 3: Audit and Patch All Call Sites

  • Search your codebase and stored procedure definitions for all instances of CAST(... AS XML), since CAST does not support a style argument — replace these with CONVERT(XML, expr, 2) wherever internal DTDs are expected.
  • Run sys.sql_modules queries to find remaining references:
  • SELECT object_id, definition FROM sys.sql_modules WHERE definition LIKE '%AS XML%';
  • Deploy the updated procedures/scripts to your Windows Server 2025 SQL instance and restart the affected application pool or service if XML parsing is handled in a middle tier.

Step 4: Validate Server-Level XML Parsing Settings

  • Open SQL Server Configuration Manager and confirm no Policy-Based Management (PBM) policy or Resource Governor rule is globally disabling XML parsing styles.
  • Check for any trace flag overrides (e.g., startup parameters in SQL Server Configuration Manager > SQL Server Services > Properties > Startup Parameters) that might force strict DTD rejection regardless of style option.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after any configuration changes.

Alternative or Verification Steps

  • Re-run the original query with the CONVERT(XML, @xmlString, 2) syntax and confirm Error 6359 no longer appears in the SSMS Messages pane or the Windows Event Viewer (Application Log, Source: MSSQLSERVER).
  • If the error persists, strip the internal DTD subset from the source XML entirely at the application layer before insertion, as a safer long-term alternative to relying on style 2 parsing.

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

Troubleshooting Guide: Error 6357 – Cannot Locate CreateInfoSetReaderEx in xmlrw.dll

Why This Error Happens

This error occurs when SQL Server’s XML parsing engine attempts to call a function exported by xmlrw.dll (or its 64-bit counterpart xmlrw64.dll) but finds either a missing, outdated, or mismatched version of the file. This is typically caused by a corrupted SQL Server installation, an incomplete patch/update cycle, or a conflicting third-party application that has overwritten the DLL with an incompatible version. It can also occur if the DLL exists but is not properly registered or sits in a directory not included in the system’s binary search path.

Step-by-Step Resolution Guide

Step 1: Verify the Existence and Version of xmlrw.dll

  • Navigate to the SQL Server binaries directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ (adjust the version folder as needed for SQL Server 2025).
  • Right-click xmlrw.dll and xmlrw64.dll, select Properties > Details, and confirm the file version matches your installed SQL Server build number.
  • If the file is missing entirely, this confirms a corrupted or incomplete installation.

Step 2: Run a SQL Server Repair Operation

  • Open Control Panel > Programs and Features, locate Microsoft SQL Server 2025.
  • Right-click and select Change, then choose the Repair option from the SQL Server Installation Center.
  • Allow the repair wizard to complete; this will restore missing or corrupted system DLLs, including xmlrw.dll.
  • Restart the SQL Server service afterward via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 3: Apply the Latest Cumulative Update (CU)

  • Download the latest Cumulative Update for SQL Server 2025 from the official Microsoft Download Center.
  • Ensure Windows Server 2025 / Windows 11 has all pending OS updates installed first via Settings > Windows Update.
  • Install the CU package, as this will replace xmlrw.dll with the correct, patched version tied to the current build.

Step 4: Check for DLL Conflicts from Third-Party Software

  • Use Process Explorer (Sysinternals) to check if another application has loaded a conflicting version of xmlrw.dll into memory.
  • Uninstall any third-party XML processing tools or legacy SQL Server client components that might place an older xmlrw.dll into a system path directory (e.g., C:\Windows\System32).
  • Reboot the server to clear any locked file handles before re-testing the query.

Alternative or Verification Steps

  • To verify the fix, re-run the specific query or SSIS package that triggered the XML parsing error; the operation should now complete without throwing Error 6357.
  • If the error persists after a repair and CU update, perform a full Uninstall and clean Reinstall of the SQL Server instance to ensure no orphaned or corrupted binary files remain in the Binn directory.

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

Troubleshooting Guide: SQL Server Error 6355 – XML to Target Collation Conversion Failure

Why This Error Happens

Error 6355 occurs when SQL Server attempts to shred or convert XML data containing Unicode characters that cannot be mapped to the target column’s collation, typically because the database or column is using a non-Unicode (non-UTF-8) collation that lacks support for the specific character set in the XML payload. This is commonly triggered when XML data containing extended characters (such as CJK, emoji, or special symbols) is inserted into a varchar or char column instead of nvarchar, or when the server’s default collation does not align with the encoding declared in the XML prolog. Corruption in the XML data encoding header or mismatched code pages between the source system and SQL Server 2025 can also cause this conversion failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Collation and Column

  • Run the following query to check the collation of the target database and table:
  • SELECT DATABASEPROPERTYEX('YourDBName', 'Collation');
  • SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName');
  • Cross-reference this with the character encoding declared in the XML file (check the <?xml version="1.0" encoding="UTF-8"?> header).

Step 2: Modify the Target Column or Database Collation

  • Alter the destination column to use a Unicode data type if it is currently non-Unicode.
  • ALTER TABLE YourTableName ALTER COLUMN YourColumn NVARCHAR(MAX);
  • If the issue is server-wide, consider rebuilding the database with a UTF-8 enabled collation (e.g., Latin1_General_100_CI_AS_SC_UTF8) via SQL Server Configuration Manager on Windows Server 2025.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after applying server-level collation changes.

Step 3: Validate XML Parsing Logic in T-SQL

  • Review the OPENXML or .nodes() method calls in your stored procedures to ensure they are not explicitly casting values to a restrictive collation.
  • Check for explicit COLLATE clauses in your INSERT INTO ... SELECT statements that might force an incompatible collation during the shredding process.
  • Update any hardcoded COLLATE SQL_Latin1_General_CP1_CI_AS instances to COLLATE DATABASE_DEFAULT if Unicode support is required.

Step 4: Check Windows Regional and Language Settings

  • On the Windows Server 2025 host, navigate to Control Panel > Region > Administrative > Change system locale.
  • Ensure “Beta: Use Unicode UTF-8 for worldwide language support” is checked if the application relies on system-wide UTF-8 interpretation.
  • Reboot the server for the locale changes to take effect, then re-run the SQL Server Agent job or query that triggered the error.

Alternative or Verification Steps

  • To verify the fix, re-execute the original INSERT or SELECT statement involving the XML data type; the query should complete without raising Error 6355.
  • If altering the collation is not feasible due to legacy application constraints, use the CONVERT(NVARCHAR(MAX), YourXMLColumn) function as a temporary workaround to force Unicode interpretation during the specific query execution.

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

Troubleshooting Guide: SQL Server Error 6356 – Failed to Load DLL (xmlrw.dll)

Why This Error Happens

This error occurs when SQL Server 2025 attempts to use XML-related functionality (such as OPENXML, XML data type methods, or SSIS XML tasks) but cannot locate or properly load the xmlrw.dll file required for XML parsing. This typically results from a corrupted or missing SQL Server installation component, an incomplete patch/update process, or incorrect file permissions preventing the SQL Server service account from accessing the DLL. In some cases, a mismatched or orphaned registry entry from a previous SQL Server version can also point to an invalid DLL path.

Step-by-Step Resolution Guide

Step 1: Verify the DLL Exists in the Correct Directory

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ (adjust instance folder name as needed for your SQL Server 2025 instance).
  • Confirm that xmlrw.dll and xmlrwbin.dll are both present in this folder.
  • If the files are missing, this confirms a corrupted installation requiring repair (proceed to Step 2).

Step 2: Run a SQL Server Repair Installation

  • Open Control Panel > Programs and Features, locate Microsoft SQL Server 2025, and select Uninstall/Change.
  • Launch the SQL Server Installation Center, choose Maintenance > Repair.
  • Select the affected instance and allow the repair wizard to restore missing or corrupted system files, including xmlrw.dll.
  • Restart the SQL Server service once the repair completes.

Step 3: Check File and Folder Permissions

  • Right-click xmlrw.dll in the Binn directory and select Properties > Security.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read & Execute permissions.
  • If permissions are missing, click Edit, add the service account, and grant the appropriate access level.
  • Run services.msc, restart the SQL Server (MSSQLSERVER) service to apply changes.

Step 4: Register the DLL Manually (If Repair Fails)

  • Open an elevated Command Prompt (Run as Administrator).
  • Navigate to the Binn directory using cd "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn".
  • Run regsvr32 xmlrw.dll to manually re-register the component.
  • Restart the SQL Server service and re-test the XML operation that triggered Error 6356.

Step 5: Apply the Latest Cumulative Update

  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Cumulative updates often replace core binaries, including xmlrw.dll, resolving version mismatches.
  • Reboot the server after installation to ensure all file locks are released and updates apply cleanly.

Alternative or Verification Steps

  • Verify the fix: Run a test query using OPENXML or .nodes() XML method in SQL Server Management Studio (SSMS) to confirm Error 6356 no longer appears.
  • Alternative solution: If the error persists after repair, completely uninstall and reinstall the SQL Server instance, ensuring no leftover files remain in the Binn folder before reinstalling from fresh installation media.

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

Troubleshooting Guide: SQL Server Error 6352 – “Invalid Parameter Specified. XML Schema Collections Can Only Be Created From a String Literal”

Why This Error Happens

This error occurs when a CREATE XML SCHEMA COLLECTION statement attempts to reference a variable, column, or expression instead of a hardcoded string literal for the schema definition. SQL Server 2025 strictly enforces this requirement because the schema parser needs to validate and compile the XSD content at statement-creation time, not at runtime. This commonly happens when developers migrate dynamic SQL scripts or ORM-generated code that passes schema content through parameters rather than inline text.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Statement

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Search recent scripts or deployment logs for CREATE XML SCHEMA COLLECTION statements.
  • Check if the schema source is passed as @variable or N'' + column_name instead of a direct literal string.

Step 2: Rewrite the Statement Using a String Literal

  • Replace any variable reference with the actual XSD content wrapped in single quotes, e.g.:
  CREATE XML SCHEMA COLLECTION MySchemaCollection AS
  N'<?xml version="1.0"?><xs:schema>...</xs:schema>';
  • If the schema is large, store it in a .sql file and use SSMS’s “Open File” feature to paste the raw literal directly into the script rather than loading it via a parameter.
  • Avoid EXEC sp_executesql with parameterized XSD content — this is the primary trigger for Error 6352.

Step 3: Fix Dynamic SQL or Application Code (If Applicable)

  • If the schema is generated by an application (e.g., .NET, Python, or PowerShell scripts connecting to SQL Server 2025), modify the code to inline the XSD text directly into the SQL command string before execution.
  • For PowerShell deployment scripts, verify that Invoke-Sqlcmd is not passing the schema as a -Variable substitution; instead, concatenate it directly into the -Query string.
  • Re-run the corrected script in SSMS to confirm the CREATE XML SCHEMA COLLECTION command executes without raising Error 6352.

Step 4: Clear and Reload the Schema Collection Cache

  • If the schema collection previously failed mid-creation, drop any partial objects:
  DROP XML SCHEMA COLLECTION MySchemaCollection;
  • Re-execute the corrected literal-based script to recreate the collection cleanly.

Alternative or Verification Steps

  • Verify the fix by querying sys.xml_schema_collections to confirm the new schema collection exists and has the expected xml_collection_id.
  • If the error persists despite using a literal, check for invisible Unicode characters or encoding mismatches (UTF-8 vs UTF-16) in the XSD string by re-saving the script file with “SQL Server Compatible” encoding in SSMS before re-running it.

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

Troubleshooting Guide: SQL Server Error 6353 – “Serialization of Built-in Schemata Is Not Supported”

Why This Error Happens

This error occurs when SQL Server attempts to serialize metadata for Service Broker contracts or message types that reference built-in system schemas (such as sys or INFORMATION_SCHEMA) during operations like replication, database mirroring setup, or Service Broker conversation initialization. The SQL Server engine intentionally blocks serialization of these reserved schemata because they are internal constructs not meant to be transmitted across endpoints. This typically surfaces when a script or application incorrectly attempts to bind a Service Broker message type, contract, or queue to a built-in schema instead of a user-defined one, often due to a misconfigured deployment script or a corrupted database project template carried over during an upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to locate Service Broker objects referencing system schemas:
  SELECT name, schema_id, SCHEMA_NAME(schema_id) AS schema_name
  FROM sys.service_message_types
  WHERE SCHEMA_NAME(schema_id) IN ('sys', 'INFORMATION_SCHEMA');
  • Also check sys.service_contracts and sys.service_queues using the same pattern.

Step 2: Re-create the Object Under a Valid User Schema

  • Script out the definition of the affected message type, contract, or queue.
  • Drop the object and recreate it explicitly under dbo or another custom schema:
  CREATE MESSAGE TYPE [dbo].[YourMessageType]
  VALIDATION = WELL_FORMED_XML;
  • Update any dependent contracts or services to reference the corrected schema-qualified object name.

Step 3: Audit Deployment Scripts and DACPAC Files

  • Open your .sql deployment scripts or DACPAC project files in Visual Studio / Azure Data Studio.
  • Search for any hardcoded references to sys. or INFORMATION_SCHEMA. within CREATE MESSAGE TYPE, CREATE CONTRACT, or CREATE QUEUE statements.
  • Replace these references with the correct user-defined schema before redeploying.

Step 4: Clear Cached Broker Metadata

  • Restart the SQL Server Service Broker for the affected database to flush stale metadata:
  ALTER DATABASE [YourDatabase] SET ENABLE_BROKER;
  • If the database is in an inconsistent state, run ALTER DATABASE [YourDatabase] SET NEW_BROKER WITH ROLLBACK IMMEDIATE; in a test environment first to confirm no data loss occurs.

Step 5: Validate SQL Server 2025 Compatibility Level

  • Confirm the database compatibility level supports the updated Service Broker schema validation rules:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If the level is below 170 (SQL Server 2025 default), update it:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Re-run the original operation (replication sync, mirroring failover, or Broker conversation) and confirm Error 6353 no longer appears in the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • If the error persists, restore a clean backup of the database schema (pre-upgrade) and manually migrate only the custom-schema Service Broker objects, bypassing any scripts that reference built-in schemata.

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

Troubleshooting Guide: SQL Server Error 6354 – “Target String Size Too Small to Represent the XML Instance”

Why This Error Happens

This error occurs when SQL Server attempts to convert a large XML data type instance into a string (such as VARCHAR or NVARCHAR) but the target variable’s declared length is insufficient to hold the full serialized XML content. It commonly arises during replication, FOR XML query execution, or when application code implicitly casts XML output into a fixed-length string buffer. Additionally, corrupted or oversized XML fragments in system tables (like those used by Replication or Service Broker) can trigger this error even when explicit casting isn’t performed by the user.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Process

  • Check the SQL Server Error Log (Management Studio > Management > SQL Server Logs) to pinpoint the exact query, job, or replication agent throwing Error 6354.
  • If replication-related, run sp_helpdistributiondbusage to check the distribution database health.
  • Review the application connection string or stored procedure for explicit CAST or CONVERT operations targeting XML data.

Step 2: Increase the Target Variable Size

  • Locate the specific variable declaration in the T-SQL script or stored procedure (e.g., DECLARE @output VARCHAR(100)).
  • Change the data type to NVARCHAR(MAX) to accommodate large XML payloads:
  DECLARE @output NVARCHAR(MAX);
  SET @output = (SELECT * FROM table_name FOR XML AUTO);
  • If modifying third-party application code is not possible, check if the application allows configuration of buffer sizes via a web.config or app.config file.

Step 3: Adjust Replication or Service Broker Settings (If Applicable)

  • If the error originates from Merge or Transactional Replication, open SQL Server Management Studio (SSMS) and navigate to Replication > Local Publications > [Your Publication] > Properties.
  • Verify the @max_text_repl_size setting via sp_configure and increase it if XML snapshots are being truncated:
  sp_configure 'show advanced options', 1;
  RECONFIGURE;
  sp_configure 'max text repl size', -1; -- Sets to unlimited
  RECONFIGURE;

Step 4: Clear Corrupted XML Cache

  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 to clear any cached execution plans holding malformed XML schemas.
  • Run DBCC FREEPROCCACHE to force SQL Server to recompile the execution plans associated with the XML query.

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific query or replication job that failed. Use SELECT DATALENGTH(@output) to confirm the byte size of the XML data does not exceed the NVARCHAR(MAX) limit (2GB).
  • Alternative Solution: If the issue persists in a Linked Server scenario, disable “Implicit Conversions” in the Linked Server provider options under Server Objects > Linked Servers > Providers > SQLNCLI in SSMS.

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

Troubleshooting Guide: SQL Server Error 6350 — “The definition for XML schema collection has changed”

Why This Error Happens

This error occurs when a query execution plan or metadata cache references an XML schema collection that has been altered (via ALTER XML SCHEMA COLLECTION or dropped/recreated) after the plan was compiled. SQL Server detects a mismatch between the cached schema version and the current schema definition, typically due to concurrent DDL operations running against the schema collection while dependent queries or stored procedures are executing. This can also surface after an in-place upgrade to SQL Server 2025 if plan cache entries or compiled XML validation metadata were not properly invalidated.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure Cache for the Affected Database

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance.
  • Run DBCC FREEPROCCACHE to clear stale execution plans, or scope it using DBCC FLUSHPROCINDB(db_id) for a single database.
  • Re-run the failing query/procedure to force a fresh compilation against the current schema collection.

Step 2: Identify Concurrent Schema Modifications

  • Query sys.dm_tran_locks and sys.xml_schema_collections to check if another session recently altered the schema collection.
  • Review Extended Events or the Default Trace for ALTER XML SCHEMA COLLECTION events around the error timestamp.
  • Coordinate with application teams to serialize schema changes instead of running them during active query execution windows.

Step 3: Recompile Dependent Objects

  • Identify stored procedures, functions, or views referencing the XML schema collection using sys.sql_expression_dependencies.
  • Run sp_recompile 'ObjectName' on each dependent object to force plan regeneration.
  • Validate the object compiles cleanly by executing it manually in a test transaction.

Step 4: Validate Schema Collection Integrity

  • Run SELECT xml_schema_namespace, definition FROM sys.xml_schema_collections to confirm the current schema definition matches what the application expects.
  • If corruption is suspected, drop and recreate the schema collection using a verified XSD backup: CREATE XML SCHEMA COLLECTION [Schema].[Name] AS N'<xsd definition>'.
  • Ensure the SQL Server service account has appropriate permissions on any linked file resources used to import the schema.

Step 5: Apply Latest Cumulative Update

  • Check Help > About in SSMS or run SELECT @@VERSION to confirm your build number.
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, since this error has known fixes related to schema cache invalidation logic.
  • Reboot the Windows Server 2025 host if prompted, then re-test the failing workload.

Alternative or Verification Steps

  • Re-execute the previously failing query or stored procedure immediately after cache clearing — a successful run with no Error 6350 confirms resolution.
  • If the issue persists, enable Extended Events session sqlserver.error_reported filtered on error number 6350 to capture the exact query plan and schema collection version at failure time for deeper root-cause analysis.

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

Troubleshooting Guide: Error 6351 – XML Schema Collection Altered During Batch Execution

Why This Error Happens

This error occurs when a concurrent session modifies, drops, or alters an XML schema collection that is bound to a return parameter of a stored procedure or function while another session’s batch is still executing against that same module. SQL Server detects this schema-binding conflict mid-execution and aborts the batch to prevent data corruption or type mismatches, since the XML validation rules changed after compilation but before completion. This is typically caused by a DDL operation (such as ALTER XML SCHEMA COLLECTION) running in parallel with active transactions referencing that schema, often in high-concurrency environments or during automated deployment scripts that lack proper locking or sequencing.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Session and Schema Collection

  • Query sys.dm_exec_requests and sys.dm_tran_locks to find sessions holding locks on the affected XML schema collection.
  • Run the following to pinpoint the schema collection in question:
  • SELECT * FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Cross-reference the module name from the error message (%.*ls) using sys.objects and sys.sql_modules.

Step 2: Re-run the Batch After Isolating the Conflict

  • Simply re-executing the batch, as the error suggests, often resolves transient conflicts once the DDL operation completes.
  • Wrap the retry logic in a TRY...CATCH block with a short delay (WAITFOR DELAY '00:00:02') to handle this automatically in scripts.
  • Confirm no other session is actively running ALTER XML SCHEMA COLLECTION against the same collection during your retry window.

Step 3: Serialize DDL Changes to XML Schema Collections

  • Ensure that any deployment scripts or maintenance jobs that alter XML schema collections run during a maintenance window, not during peak transactional activity.
  • Use explicit transactions with SERIALIZABLE isolation level when altering schema collections to prevent overlapping reads:
  • BEGIN TRAN; ALTER XML SCHEMA COLLECTION dbo.YourSchema ADD '<xsd:schema>...</xsd:schema>'; COMMIT;
  • Update application connection strings or ORM configurations to include retry logic (e.g., Entity Framework’s EnableRetryOnFailure()) for transient SQL errors like 6351.

Step 4: Check for Lock Contention or Blocking Processes on Windows Server 2025

  • Open Performance Monitor (perfmon.exe) and add the SQLServer:Locks counter set to monitor XML Schema Collection lock waits in real time.
  • Use SQL Server Management Studio’s Activity Monitor to identify and, if necessary, terminate (KILL <session_id>) any long-running blocking session that is altering the schema.

Step 5: Validate SQL Server 2025 Patch Level and Configuration

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as schema-binding concurrency handling has been refined in recent builds.
  • Check via: SELECT @@VERSION; and compare against Microsoft’s latest CU release notes.
  • Apply any pending updates through Windows Update or SQL Server Setup on Windows Server 2025 / Windows 11.

Alternative or Verification Steps

  • To verify the fix, re-run the original failing batch/stored procedure call multiple times under load using a tool like SQLQueryStress to confirm Error 6351 no longer surfaces.
  • As an alternative, if the schema collection changes infrequently, consider caching the module’s execution plan dependency separately or refactoring the procedure to avoid binding directly to a frequently altered XML schema collection.

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

Troubleshooting Guide: Error 6347 — Specified Collection Cannot Be Altered

Why This Error Happens

Error 6347 occurs when SQL Server cannot locate the specified Extended Events collection (session) in the current scope, typically because the session name is misspelled, was dropped, or was never created in the target database/server context. This can also happen when the login executing the ALTER EVENT SESSION statement lacks the ALTER ANY EVENT SESSION server-level permission. Additionally, attempting to alter a session that exists only at a different scope (e.g., referencing a database-scoped session while connected to a different database context) will trigger this error.

Step-by-Step Resolution Guide

Step 1: Verify the Event Session Exists

  • Run the following query to list all active sessions on the server:
  SELECT name FROM sys.server_event_sessions;
  • Confirm the exact spelling and casing of the collection/session name referenced in your ALTER EVENT SESSION statement.
  • If the session is missing, it may have been dropped or never committed; recreate it using CREATE EVENT SESSION instead of ALTER.

Step 2: Check Current Permissions on the Login

  • Confirm the executing login has the required server-level permission:
  SELECT * FROM sys.fn_my_permissions(NULL, 'SERVER')
  WHERE permission_name = 'ALTER ANY EVENT SESSION';
  • If missing, grant the permission using an account with sysadmin or securityadmin role:
  GRANT ALTER ANY EVENT SESSION TO [YourLoginName];
  • Restart the SQL Server session (not the service) to ensure permission changes take effect.

Step 3: Validate Scope and Context (Server vs. Database)

  • Ensure you are not confusing a Server-scoped Extended Events session with a Database-scoped Extended Events session (introduced for lightweight diagnostics in later SQL Server versions).
  • Use USE [YourDatabaseName]; before executing the ALTER statement if the session is database-scoped.
  • Check sys.database_event_sessions if working within a specific database context rather than sys.server_event_sessions.

Step 4: Rebuild the Session Definition

  • If the XML/configuration metadata for the session is corrupted (rare but possible after a failed patch or in-place upgrade to SQL Server 2025), drop and recreate the session:
  DROP EVENT SESSION [YourSessionName] ON SERVER;
  GO
  CREATE EVENT SESSION [YourSessionName] ON SERVER
  ADD EVENT sqlserver.error_reported
  ADD TARGET package0.event_file(SET filename=N'YourSession.xel');
  • Restart the SQL Server Agent service via Windows Server 2025 Services console (services.msc) if the session was agent-dependent.

Alternative or Verification Steps

  • Verify the fix: Re-run the original ALTER EVENT SESSION command; it should execute without throwing Error 6347. Additionally, check SQL Server Error Logs (via SSMS Object Explorer > Management > SQL Server Logs) to confirm no residual metadata errors exist.
  • Alternative solution: If permissions appear correct but the error persists, use SSMS’s Management > Extended Events > Sessions GUI to manually inspect and edit the session properties, bypassing potential T-SQL syntax or context issues.

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

Troubleshooting Guide: SQL Server Error 6348 – Collection Creation Failure

Why This Error Happens

Error 6348 occurs when SQL Server attempts to create an XML collection (schema collection) or Service Broker message type collection that conflicts with an existing object of the same name in the target schema. This typically happens due to leftover metadata from a previous failed deployment, a naming collision between database schemas, or insufficient CREATE XML SCHEMA COLLECTION permissions on the user’s login. In Windows Server 2025 / Windows 11 environments, this can also surface after in-place upgrades to SQL Server 2025 where system catalog views retain stale references.

Step-by-Step Resolution Guide

Step 1: Verify If the Collection Already Exists

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check existing collections:
  SELECT name, schema_id, xml_collection_id 
  FROM sys.xml_schema_collections 
  WHERE name = 'YourCollectionName';
  • If a result is returned, the object already exists under that schema and is causing the conflict.

Step 2: Drop or Rename the Conflicting Collection

  • If the existing collection is obsolete or from a failed script execution, drop it safely:
  DROP XML SCHEMA COLLECTION dbo.YourCollectionName;
  • If the collection is still needed, rename your new incoming collection instead to avoid overwriting production data.
  • Re-run your original CREATE XML SCHEMA COLLECTION script to confirm the conflict is resolved.

Step 3: Check and Correct User Permissions

  • Open SQL Server Configuration Manager or SSMS and navigate to Security > Logins.
  • Ensure the executing user has the ALTER SCHEMA or CREATE XML SCHEMA COLLECTION permission on the target database:
  GRANT CREATE XML SCHEMA COLLECTION TO [YourUserName];
  • On Windows Server 2025, also verify the SQL Server service account has sufficient NTFS permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA to prevent metadata write failures.

Step 4: Clear Cached Metadata (If Issue Persists)

  • Restart the SQL Server service via Services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This clears any stale plan cache or schema metadata that Windows Server 2025’s memory management may have retained after the failed creation attempt.

Alternative or Verification Steps

  • Verify the fix: Re-execute the original deployment script or application call that triggered Error 6348; confirm no error is returned and query sys.xml_schema_collections to validate the new entry exists.
  • Alternative solution: If the error persists across restarts, export the schema definition, fully drop the associated database schema (if non-production), and recreate it from a clean script to eliminate any orphaned catalog entries.

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

Troubleshooting Guide: Error 6345 – Sparse Column Set Cannot Be Indexed by an XML Index

Why This Error Happens

This error occurs because SQL Server does not support creating an XML index directly on a column set that aggregates sparse columns within a table. The column set is a computed, virtual representation of all sparse columns in XML format, and SQL Server’s XML indexing engine is designed to work only against genuine xml typed columns, not this derived structure. Attempting to apply an XML index to this virtual column triggers Error 6345 because the underlying storage mechanism for sparse column sets is incompatible with the internal node-table structure required by XML indexes.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Set

  • Open SQL Server Management Studio (SSMS) and connect to your Microsoft SQL Server 2025 instance.
  • Run the following query to locate the column set and its parent table:
SELECT c.name AS ColumnSetName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.is_column_set = 1;
  • Confirm that the column referenced in the Error 6345 message matches a is_column_set = 1 entry.

Step 2: Remove or Modify the Invalid Index Definition

  • Script out the failing CREATE XML INDEX statement to review its target column.
  • Drop the erroneous index creation attempt if it was partially applied:
DROP INDEX IF EXISTS [IX_InvalidXMLIndex] ON [dbo].[YourTable];
  • Do not attempt to re-target the column set itself in the CREATE XML INDEX syntax.

Step 3: Apply the XML Index to the Correct Underlying Column

  • Identify the actual xml data type column definition that exists independently of the sparse column set (if applicable).
  • If no standalone xml column exists, you cannot use an XML index on sparse data; instead, create a standard non-clustered index on specific sparse columns if indexing is required.
  • Execute the corrected syntax:
CREATE PRIMARY XML INDEX [PXML_Index] ON [dbo].[YourTable] ([StandaloneXmlColumn]);

Step 4: Validate Sparse Column Configuration

  • Navigate to Table Properties in SSMS Object Explorer to review the “Storage” tab for sparse column settings.
  • Ensure that sparse columns required for business logic remain untouched, as removing SPARSE properties may be necessary if column sets must be eliminated entirely.
  • Run DBCC CHECKTABLE on the affected table to ensure structural integrity following any schema modifications:
DBCC CHECKTABLE ('YourTable');

Alternative or Verification Steps

  • Verify the fix by re-running the CREATE INDEX statement against the standalone XML column (not the column set); it should complete without triggering Error 6345.
  • If XML indexing capability is strictly required on sparse data, consider refactoring the table schema to split sparse columns into a separate related table containing a standard xml column, avoiding the column set limitation entirely.

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

Troubleshooting Guide: Error 6346 – Cannot Convert Primary XML Index Using DROP_EXISTING

Why This Error Happens

This error occurs because SQL Server’s DROP_EXISTING option is designed to rebuild or modify an index of the same type, but it cannot be used to change a primary XML index into a secondary XML index in a single operation. The underlying architecture requires a primary XML index to exist as the base structure before any secondary (PATH, VALUE, or PROPERTY) XML index can reference it, so attempting to overwrite the primary index definition with a secondary one via DROP_EXISTING violates this dependency chain. This is a logical/syntax limitation in T-SQL rather than a corruption or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Existing Index Type

  • Run the following query to confirm the index is primary and gather its metadata:
SELECT i.name, i.type_desc, xi.using_xml_index_id, xi.secondary_type_desc
FROM sys.indexes i
JOIN sys.xml_indexes xi ON i.object_id = xi.object_id AND i.index_id = xi.index_id
WHERE i.object_id = OBJECT_ID('YourTableName');
  • Note the exact index name and the column it is built on, as you will need this for recreation.

Step 2: Drop the Primary XML Index Manually

  • Since DROP_EXISTING cannot convert index types, you must explicitly drop the primary index first.
  • Execute: DROP INDEX PrimaryXmlIndexName ON YourTableName;
  • Be aware that dropping a primary XML index will automatically drop all associated secondary XML indexes on that column, so script out any secondary indexes you wish to recreate later.

Step 3: Recreate the Index as Secondary (If Intended)

  • If your goal was actually to create a secondary index, ensure a primary XML index still exists on the column, then create the secondary index with a new, distinct name.
  • Use: CREATE XML INDEX NewSecondaryIndexName ON YourTableName (XmlColumn) USING XML INDEX PrimaryIndexName FOR PATH;
  • Do not reuse the exact name of the dropped primary index in the same batch without verifying the primary index was successfully recreated first.

Step 4: Recreate the Primary Index if Required

  • If the intent was simply to rebuild the primary index (not convert it), omit the DROP_EXISTING clause referencing a secondary type and use the standard primary syntax instead.
  • Run: CREATE PRIMARY XML INDEX PrimaryIndexName ON YourTableName (XmlColumn) WITH (DROP_EXISTING = ON);
  • Ensure the index type specified in the CREATE statement matches the type you are trying to preserve (Primary-to-Primary only).

Alternative or Verification Steps

  • Verify the fix by re-running the query from Step 1 to confirm the type_desc and secondary_type_desc columns match your intended configuration (NULL for primary, or PATH/VALUE/PROPERTY for secondary).
  • If you need to “convert” an index type without downtime concerns, the only supported alternative is to drop all XML indexes on the column entirely and rebuild the complete hierarchy (Primary first, then Secondary) in two separate batches.