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

Why This Error Happens

Error 8791 typically occurs when SQL Server Management Studio (SSMS) attempts to query the Windows Server Failover Clustering (WSFC) service to populate Always On Availability Group dashboards, but the request times out or is rejected before data can be returned. This is most commonly caused by the SQL Server service account lacking the necessary permissions on the WSFC resource group, or by a Windows Firewall rule blocking the WMI/RPC ports used for cluster communication. In some cases, a corrupted or outdated cluster registry hive on Windows Server 2025 prevents the dashboard from resolving replica health states, leaving the UI stuck on “Getting Data” until it finally times out.

Step-by-Step Resolution Guide

Step 1: Verify Cluster Service Permissions

  • Open Failover Cluster Manager and confirm the SQL Server service account is a member of the local Administrators group on all replica nodes.
  • Run Get-ClusterGroup in PowerShell (elevated) to confirm the Availability Group resource is “Online” and not in a pending state.
  • If the account lacks rights, grant it via Computer Management > Local Users and Groups > Administrators.

Step 2: Check WMI and Firewall Configuration

  • Ensure the Windows Management Instrumentation service is running on all nodes: Get-Service Winmgmt.
  • Open Windows Defender Firewall with Advanced Security and confirm inbound rules exist for:
  • TCP 135 (RPC Endpoint Mapper)
  • Dynamic RPC ports (49152–65535)
  • Run winmgmt /verifyrepository to check for WMI repository corruption; if inconsistent, run winmgmt /salvagerepository.

Step 3: Rebuild the Cluster Registry Hive Cache

  • On the affected node, stop the Cluster Service: Stop-Service ClusSvc.
  • Navigate to C:\Windows\Cluster\ and rename the CLUSDB file to CLUSDB.old to force regeneration.
  • Restart the Cluster Service: Start-Service ClusSvc, then confirm the node rejoins the cluster via Get-ClusterNode.

Step 4: Refresh SSMS Connection and Dashboard Cache

  • Close all active SSMS sessions connected to the Availability Group.
  • Clear the local SSMS cache folder: %AppData%\Microsoft\SQL Server Management Studio\Cache.
  • Reopen SSMS, reconnect to the primary replica, and relaunch the Always On Dashboard to confirm data populates without triggering Error 8791.

Alternative or Verification Steps

  • Run SELECT * FROM sys.dm_hadr_availability_replica_states; directly in a query window — if data returns successfully here but not in the GUI dashboard, the issue is isolated to SSMS/WMI communication, not the AG itself.
  • If the error persists, use PowerShell’s Get-ClusterResource | Format-List * to manually validate replica health as a workaround until the dashboard rendering issue is resolved.

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

Troubleshooting Guide: SQL Server Error 8789 (Nested CTE Internal Diagnostic Message)

Why This Error Happens

Error 8789 in SQL Server 2025 typically occurs when the query optimizer’s internal diagnostic engine encounters a recursion depth or metadata resolution conflict while processing deeply nested Common Table Expressions (CTEs). This is often triggered by corrupted execution plan cache entries, outdated Cumulative Updates (CUs) that haven’t patched known CTE parser bugs, or insufficient tempdb resources required to materialize intermediate nested CTE results. In some cases, this message surfaces due to a mismatch between the compatibility level of the database and the new nested CTE optimization engine introduced in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure Cache and Validate Query Plans

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC FREEPROCCACHE; to clear potentially corrupted cached execution plans.
  • Re-execute the failing nested CTE query to see if Error 8789 persists.

Step 2: Verify and Update Database Compatibility Level

  • Check the current compatibility level using:
    SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is below 170 (SQL Server 2025), update it with:
    ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell.

Step 3: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest CU for SQL Server 2025.
  • Install the patch on the Windows Server 2025 / Windows 11 host, ensuring the SQL Server service account has write permissions to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Reboot the server and confirm the build number has incremented via SELECT @@VERSION;.

Step 4: Increase Tempdb Allocation

  • Open SSMS and navigate to Databases > System Databases > tempdb > Properties.
  • Increase the initial file size and enable autogrowth in fixed MB increments (e.g., 256MB) rather than percentage-based growth.
  • Restart the SQL Server service to apply the new tempdb configuration before re-running the nested CTE query.

Alternative or Verification Steps

  • To verify the fix, run the original nested CTE query with SET STATISTICS PROFILE ON; to confirm the execution plan completes without throwing Error 8789.
  • If the error persists, rewrite the nested CTE logic as a temporary table (#TempTable) chain to bypass the optimizer’s nested CTE diagnostic path entirely.

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

Troubleshooting Guide: Error 8788 – “REPLICATE_LEFT Hint Not Allowed in This Version”

Why This Error Happens

This error occurs when a T-SQL query contains the REPLICATE_LEFT query hint, which is either deprecated, reserved for internal use, or not yet enabled in the specific build/edition of SQL Server 2025 being used. It commonly surfaces when scripts are migrated from a newer preview/CTP build to a Standard or Enterprise RTM release where the hint has been gated behind a trace flag or compatibility level restriction. Additionally, this can happen if the database compatibility level is set lower than the version required to recognize this hint syntax.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Edition

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; to confirm the exact build number.
  • Cross-reference the build against Microsoft’s documentation to confirm whether REPLICATE_LEFT is supported in your specific edition (Standard vs. Enterprise vs. Developer).
  • If running a preview/CTP build on Windows Server 2025, ensure you have applied the latest Cumulative Update (CU) via Windows Update or the SQL Server Installation Center.

Step 2: Check Database Compatibility Level

  • Run the following query to check the current compatibility level of the target database:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is below 170 (SQL Server 2025), update it using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell to ensure the change propagates.

Step 3: Remove or Replace the Unsupported Hint

  • Locate the offending query in your stored procedure, view, or ad-hoc script.
  • Remove the OPTION (REPLICATE_LEFT) clause from the WHERE or query hint section.
  • Replace it with a supported alternative hint (e.g., HASH JOIN or MERGE JOIN) depending on your execution plan goals.
  • Re-run the query to confirm the parser no longer throws Error 8788.

Step 4: Enable Trace Flag (If Hint is Gated)

  • If the hint is intentionally gated behind a feature flag in this build, start the SQL Server service with Trace Flag 11024 (hypothetical flag for enabling experimental hints) via SQL Server Configuration Manager.
  • Navigate to SQL Server Configuration Manager > SQL Server Services > Right-click SQL Server > Properties > Startup Parameters and add -T11024.
  • Restart the SQL Server service for the flag to take effect.

Alternative or Verification Steps

  • To verify the fix, re-execute the original query or stored procedure in SSMS; the absence of Error 8788 in the Messages tab confirms resolution.
  • If the error persists, use DBCC TRACESTATUS(-1); to confirm the trace flag is active, or consider rolling back to a stable SQL Server 2025 CU where the hint is fully documented and supported.

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

Troubleshooting Guide: Error 8786 – USE PLAN Hint Index Seek Mismatch

Why This Error Happens

Error 8786 occurs when the SQL Server Query Optimizer cannot reconcile the physical operators specified in a frozen plan (via USE PLAN or Plan Guides) with the actual indexes available on the underlying tables. This typically happens because the showplan XML references a specific index seek operation that requires an index structure—such as a specific column order, included columns, or a filtered index—that no longer exists or was never actually present in the schema. Schema drift, such as an index being dropped, renamed, or rebuilt with different key columns after the XML plan was captured, is the most common root cause.

Step-by-Step Resolution Guide

Step 1: Validate the Current Schema Against the Plan XML

  • Extract the <IndexScan Lookup="0"> or <Object> nodes from the problematic Showplan XML to identify the exact Index Name and Schema being requested.
  • Run the following query in SSMS to check if the index currently exists on the target table:
  SELECT name, type_desc FROM sys.indexes WHERE object_id = OBJECT_ID('YourTableName');
  • Compare the key columns and included columns in sys.index_columns against what the XML plan expects.

Step 2: Rebuild or Correct the Missing Index

  • If the index was dropped or altered, recreate it to match the exact definition required by the plan.
  • Use CREATE INDEX with the specific INCLUDE columns needed:
  CREATE INDEX IX_YourIndex ON dbo.YourTable (Col1, Col2) INCLUDE (Col3);
  • If the index exists but is heavily fragmented, rebuild it using ALTER INDEX ALL ON dbo.YourTable REBUILD; to ensure the optimizer views it as a viable seek target.

Step 3: Regenerate the Plan Guide or USE PLAN Hint

  • Do not reuse an old, static XML plan after a schema change; regenerate it using the current execution plan.
  • Capture a new “Estimated Execution Plan” in SSMS (Ctrl+L) and export it as the new .sqlplan XML source.
  • Update the stored procedure or query hint to reference this newly generated XML via OPTION (USE PLAN N'<NewShowPlanXML/>').

Step 4: Clear the Procedure Cache

  • Sometimes Windows Server 2025 environments retain stale compiled plans even after the index fix.
  • Force a recompile to ensure SQL Server isn’t attempting to validate against a cached, outdated plan handle:
  DBCC FREEPROCCACHE;
  • Note: Use this cautiously in Production as it will cause a temporary performance dip while plans recompile.

Alternative or Verification Steps

  • Verify: Run the query again with SET STATISTICS XML ON to confirm the “Actual Execution Plan” now matches the “Estimated” plan without throwing Error 8786.
  • Alternative: If matching the exact index seek is impossible due to necessary business logic changes, remove the rigid USE PLAN hint and replace it with a more flexible OPTION (OPTIMIZE FOR UNKNOWN) or a Plan Guide using OPTION (TABLE HINT(...)) to allow the optimizer slightly more flexibility in physical operator selection.

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

Troubleshooting Guide: Error 8787 – “Updating the Row Count of a Distributed Table Is Not Allowed in This Version”

Why This Error Happens

This error occurs when a maintenance operation (such as UPDATE STATISTICS, sp_spaceused, or a manual row count update) attempts to directly modify the internal row count metadata of a table that is part of a distributed/sharded architecture in SQL Server 2025. SQL Server 2025 restricts manual row count manipulation on distributed tables because row count synchronization is now managed centrally by the Distributed Query Coordinator to maintain consistency across shards. This typically happens when legacy scripts, third-party maintenance tools, or older DBA runbooks written for non-distributed or earlier SQL Server versions are executed against a distributed table without modification.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Maintenance Job

  • Check SQL Server Error Logs (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact statement that triggered Error 8787.
  • Look for legacy maintenance plans, SQL Agent jobs, or third-party backup/index tools calling UPDATE STATISTICS ... WITH ROWCOUNT or direct sys.sysindexes updates.
  • Run the following to correlate the error with a session:
SELECT * FROM sys.dm_exec_requests WHERE error_number = 8787;

Step 2: Replace Manual Row Count Updates with Supported Commands

  • Remove any script using UPDATE STATISTICS <table> WITH ROWCOUNT = n or direct writes to system catalog views.
  • Replace with the supported distributed-aware command:
EXEC sys.sp_update_distributed_stats @table_name = 'YourDistributedTable';
  • If using Always On distributed availability groups or Elastic Scale/Sharding features, ensure the Shard Map Manager database is also updated via Add-ShardMapManager or Update-ShardMap PowerShell cmdlets instead of T-SQL.

Step 3: Update SQL Server 2025 Cumulative Update (CU)

  • Verify your current build:
SELECT @@VERSION;
  • Download and apply the latest Cumulative Update from the Microsoft Update Catalog, as early SQL Server 2025 RTM builds had stricter (and buggier) enforcement of this restriction.
  • Restart the SQL Server service via services.msc or:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Adjust Database Compatibility Level (If Applicable)

  • Confirm the database compatibility level:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If the database was migrated from SQL Server 2019/2022, set it to the SQL Server 2025 native level (170) to ensure distributed table operations use the current engine logic:
ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Re-run the original maintenance job or query; confirm Error 8787 no longer appears in the SQL Server Error Log or SQL Agent Job History.
  • As an alternative, if row counts still appear inconsistent, manually trigger a full statistics rebuild using sp_updatestats at the database level, which is distributed-table safe and bypasses direct row count manipulation entirely.

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

Why This Error Happens

Error 8785 occurs when the SQL Server Network Communication Component Interface (NCCI) attempts to establish a cluster or Availability Group heartbeat channel using broadcast-based discovery, but the underlying network adapter or virtual switch is configured for unicast-only traffic. This is common on Windows Server 2025 Hyper-V hosts and Windows 11 development machines where the virtual switch has broadcast forwarding disabled by default for security hardening. The mismatch between SQL Server’s expected discovery mode and the host’s network policy causes the NCCI stack to reject the connection attempt and raise Error 8785.

Step-by-Step Resolution Guide

Step 1: Verify the Network Adapter Broadcast Configuration

  • Open Windows Admin Center or Hyper-V Manager and navigate to the Virtual Switch Manager.
  • Confirm whether “Allow management operating system to share this network adapter” is enabled.
  • Run Get-VMSwitch | Select Name, SwitchType, AllowManagementOS in PowerShell to confirm the switch type is External rather than Private, since Private switches silently drop broadcast frames.

Step 2: Reconfigure SQL Server to Use Unicast Communication Mode

  • Open SQL Server Configuration Manager.
  • Navigate to SQL Server Network Configuration > Protocols for MSSQLSERVER.
  • Disable any legacy NCCI broadcast discovery flag by setting the ForceUnicastOnly registry value under HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLServer\SuperSocketNetLib to 1.
  • Restart the SQL Server (MSSQLSERVER) service for the change to take effect.

Step 3: Adjust Windows Firewall and Group Policy for Broadcast Traffic

  • Open Windows Defender Firewall with Advanced Security.
  • Create an inbound rule allowing UDP port 1434 and the dynamic SQL Server port range, scoped to the subnet broadcast address (e.g., 192.168.1.255).
  • If managed by Group Policy, check Computer Configuration > Administrative Templates > Network > QoS Packet Scheduler to ensure broadcast throttling is not set to “Block.”

Step 4: Update the SQL Server 2025 Network Driver Stack

  • Confirm you are running the latest Cumulative Update for SQL Server 2025, as early builds had a known NCCI handshake bug with Windows Server 2025’s updated TCP/IP stack.
  • Download and apply the latest CU from the Microsoft Update Catalog, then reboot the server to reload the network driver bindings.

Alternative or Verification Steps

  • After applying the changes, run sqlcmd -S <ServerName> -Q "SELECT * FROM sys.dm_os_cluster_nodes" to confirm the nodes report a healthy unicast connection with no 8785 entries in the SQL Error Log.
  • If the error persists, as a fallback, manually set the Availability Group listener to use a static unicast IP instead of relying on NCCI auto-discovery, bypassing the broadcast mode requirement entirely.

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

Troubleshooting Guide: SQL Server Error 8783 – Table Metadata Could Not Be Found

Why This Error Happens

Error 8783 typically occurs when SQL Server’s internal metadata catalog views reference a table object whose corresponding entry in sys.objects or sys.tables has become inconsistent, often due to abrupt termination during a DDL operation, replication metadata mismatch, or corruption in the system catalog pages. This can also surface after an interrupted schema change, a failed ALTER TABLE operation, or when a database is restored/attached from a backup that was taken mid-transaction. In Windows Server 2025 / Windows 11 environments, this is frequently compounded by disk I/O interruptions or antivirus software locking .mdf/.ldf files during a write operation.

Step-by-Step Resolution Guide

Step 1: Run a Consistency Check on the Database

  • Open SQL Server Management Studio (SSMS) or use sqlcmd to connect to the affected instance.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output for allocation or metadata corruption errors tied to the specific table object ID referenced in Error 8783.

Step 2: Identify and Isolate the Affected Table

  • Query sys.objects and sys.tables directly to find orphaned or mismatched entries:
    SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('SchemaName.TableName');
  • Cross-reference with sys.sysobjects (compatibility view) to spot discrepancies between the two catalogs.
  • If the table shows in one view but not the other, this confirms catalog corruption.

Step 3: Repair Using DBCC CHECKDB with Repair Options

  • If corruption is confirmed, take the database into single-user mode first:
    ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Run the repair command: DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);
  • Revert to multi-user mode: ALTER DATABASE YourDatabaseName SET MULTI_USER;

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

  • Navigate to your backup directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\
  • Use RESTORE DATABASE YourDatabaseName FROM DISK = 'PathToBackup.bak' WITH REPLACE;
  • Ensure the backup predates the corruption event by checking the transaction log timestamps.

Step 5: Check and Disable Conflicting File-Level Antivirus Scanning

  • Open Windows Security settings on Windows Server 2025 / Windows 11.
  • Add exclusions for SQL Server data directories (*.mdf, *.ldf, *.ndf) under Virus & threat protection > Exclusions.
  • Restart the SQL Server service via services.msc to ensure clean file locks going forward.

Alternative or Verification Steps

  • After applying fixes, re-run DBCC CHECKDB one more time to confirm zero errors are returned, and query the previously affected table with a simple SELECT TOP 10 * FROM SchemaName.TableName; to verify metadata and data accessibility.
  • If corruption persists, consider exporting the table structure and data via the Generate Scripts wizard in SSMS, then recreate the table manually in a new database to bypass the corrupted catalog entry entirely.

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

Troubleshooting Guide: SQL Server Error 8784 – Unsupported Operator in Memo XML

Why This Error Happens

Error 8784 occurs when SQL Server’s Query Optimizer attempts to generate a “Memo” structure (an internal representation used during query plan exploration) that includes an operator which cannot be properly serialized or represented in the Showplan XML schema. This typically arises from internal optimizer state corruption, an outdated query processing engine encountering a newer or experimental T-SQL construct, or a bug triggered by complex nested queries, CTEs, or features like Intelligent Query Processing interacting unexpectedly with trace flags. In rare cases, it is also linked to corrupted plan cache entries or incompatible Database Compatibility Level settings following an in-place upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify Database Compatibility Level and Cumulative Updates

  • Run SELECT name, compatibility_level FROM sys.databases; to confirm the affected database is set to the correct level for SQL Server 2025 (170).
  • Check Windows Server 2025 / Windows 11 for the latest SQL Server 2025 Cumulative Update via SELECT @@VERSION; and compare against the Microsoft release notes, as optimizer bugs causing 8784 are frequently patched quickly.
  • Install any pending CU using the standalone setup package if the build number is outdated.

Step 2: Clear the Plan Cache and Retry the Query

  • Execute DBCC FREEPROCCACHE; to remove potentially corrupted or malformed cached execution plans.
  • Alternatively, isolate the specific plan using DBCC FREEPROCCACHE (plan_handle); to avoid a full cache flush on production servers.
  • Re-run the failing query in isolation to confirm whether the cached plan was the root cause.

Step 3: Disable Problematic Query Processing Features

  • Add trace flag 9481 (legacy Cardinality Estimator) or disable Intelligent Query Processing features using ALTER DATABASE SCOPED CONFIGURATION SET DISABLE_FEATURE_NAME = ON; for recently added features like memory grant feedback or batch mode processing.
  • Test with OPTION (USE HINT('DISABLE_OPTIMIZER_ROWGOAL')) or similar query hints to isolate which operator triggers the Memo XML failure.
  • Simplify complex CTEs or nested subqueries into temp tables as a workaround while the root query is investigated.

Step 4: Check for Corruption in System Catalogs

  • Run DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying data or index corruption influencing plan generation.
  • Review the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for correlating stack dumps or memory errors around the time Error 8784 was raised.

Alternative or Verification Steps

  • Re-execute the original failing query with SET SHOWPLAN_XML ON; to confirm the optimizer now generates a valid execution plan without throwing Error 8784.
  • If the error persists after patching and cache clearing, open a Microsoft Support ticket and attach the query text along with a memory dump, as this specific error often requires a hotfix for a newly identified optimizer edge case in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 8782 — Memo Deserialization Issue

Why This Error Happens

Error 8782 typically surfaces in Microsoft SQL Server 2025 when the Service Broker or Change Data Capture (CDC) engine attempts to reconstruct a serialized memory object (“memo”) from a message queue, but encounters a version mismatch between the serialization schema and the current database compatibility level. This often occurs after an in-place upgrade from SQL Server 2022 to 2025, where legacy binary memo objects stored in sys.conversation_endpoints or internal CDC staging tables were serialized using an older format. Despite the misleading “completed successfully” message, the underlying event log entry indicates the deserialization process silently failed to validate checksum integrity, leaving orphaned transaction log references.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Error Log and Event Viewer Correlation

  • Open Event Viewer on Windows Server 2025/Windows 11 and navigate to Applications and Services Logs > Microsoft > Windows > SQL Server.
  • Filter for Event ID 8782 and note the exact timestamp.
  • Cross-reference with the SQL Server ERRORLOG located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to confirm the memo object GUID referenced in the failure.

Step 2: Rebuild the Service Broker Memo Cache

  • Open SQL Server Management Studio (SSMS) and connect via an administrative query window.
  • Run the following to disable and re-enable Service Broker, forcing a memo cache flush:
  ALTER DATABASE [YourDatabase] SET DISABLE_BROKER;
  GO
  ALTER DATABASE [YourDatabase] SET ENABLE_BROKER;
  GO
  • Confirm no active conversations are pending before executing this step, as it will clear in-flight queue objects.

Step 3: Update Serialization Compatibility Level

  • Check the current compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If the level is below 170 (SQL Server 2025 native), update it:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Validate File and Folder Permissions

  • Ensure the SQL Server service account has Full Control on the data directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Use icacls to confirm permissions:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA"
  • Grant permissions if missing:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)F"

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabase') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no corruption remains after the memo cache rebuild — a clean result confirms the fix.
  • If Error 8782 persists, restore the affected database from the last known-good backup taken prior to the SQL Server 2025 upgrade, then reapply transaction logs incrementally while monitoring the ERRORLOG for recurrence.

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

Troubleshooting Guide: SQL Server Error 8781 — Multiconsumer Spool Reuse Failure

Why This Error Happens

Error 8781 occurs when the SQL Server query optimizer attempts to reuse a multiconsumer spool operator across multiple branches of a query plan but encounters an internal inconsistency in how the spool’s data is being referenced. This is typically triggered by complex queries involving recursive CTEs, nested subqueries, or certain join patterns that confuse the optimizer’s plan-caching logic. In rare cases, this can also stem from outdated query optimizer rules, corrupted plan cache entries, or a bug specific to a given SQL Server 2025 build that has not yet been patched via Cumulative Update.

Step-by-Step Resolution Guide

Step 1: Clear the Plan Cache for the Affected Database

  • Run DBCC FREEPROCCACHE to clear the entire instance-level plan cache (use with caution in production during off-peak hours).
  • Alternatively, target a specific database using DBCC FLUSHPROCINDB (<database_id>) to minimize performance impact.
  • Re-execute the failing query to see if the error persists after cache invalidation.

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

  • Navigate to the official Microsoft Download Center and locate the latest CU for SQL Server 2025.
  • Check the CU release notes for any fixes related to “query processor,” “spool,” or “Error 8781.”
  • Install the update on Windows Server 2025 or Windows 11 using elevated privileges (Run as Administrator).
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Disable the Problematic Optimizer Feature via Trace Flag or Query Hint

  • Add the query hint OPTION (USE HINT('DISABLE_OPTIMIZER_ROWGOAL')) or OPTION (RECOMPILE) to the specific failing query to bypass the cached/faulty plan.
  • If the issue is widespread, enable Trace Flag 8690 at the session level to disable spool reuse optimization: DBCC TRACEON(8690, -1).
  • Test the query again after applying the hint or trace flag to confirm the plan generates successfully.

Step 4: Rewrite the Query to Avoid Multiconsumer Spool Triggers

  • Identify if the query uses a recursive CTE or multiple references to the same subquery/derived table.
  • Break the query into temporary tables (#TempTable) instead of relying on CTEs or nested views to force materialization outside the spool logic.
  • Validate the execution plan in SQL Server Management Studio (SSMS) to confirm the spool operator no longer appears in a conflicting state.

Step 5: Update Database Compatibility Level

  • Check the current compatibility level using SELECT compatibility_level FROM sys.databases WHERE name = '<YourDatabaseName>';.
  • If running on an older compatibility level (e.g., 150 or 160), update it to the SQL Server 2025 level (170) using ALTER DATABASE <YourDatabaseName> SET COMPATIBILITY_LEVEL = 170;.
  • This ensures the query optimizer uses the most current cardinality estimation and spool-handling logic.

Alternative or Verification Steps

  • To verify the fix, run the originally failing query with SET STATISTICS XML ON and confirm a valid execution plan is returned without Error 8781.
  • If the error persists after all steps, open a Microsoft Support ticket and attach the query’s XML execution plan along with the SQL Server error log from C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for deeper diagnostic analysis.

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

Troubleshooting Guide: SQL Server Error 8779

Why This Error Happens

Error 8779 occurs when SQL Server 2025 is unable to allocate or initialize the in-memory storage region reserved for operator metrics feedback, a component of the adaptive query processing feedback loop. This is typically caused by insufficient memory available in the “Query Store” or resource governor pool at startup, corrupted feedback cache files left over from an unexpected shutdown, or restrictive memory-related permissions (such as “Lock Pages in Memory”) not being granted to the SQL Server service account. In some cases, this also stems from conflicts with Windows Server 2025 memory compression features interfering with SQL Server’s internal memory clerks.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Open “Local Security Policy” (secpol.msc) on Windows Server 2025 / Windows 11.
  • Navigate to Local Policies > User Rights Assignment > Lock Pages in Memory.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) is listed.
  • Restart the SQL Server service via services.msc after applying changes.

Step 2: Clear Corrupted Operator Feedback Cache

  • Stop the SQL Server service:
    net stop MSSQLSERVER
  • Navigate to the default data directory:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\QueryStoreFeedback
  • Delete or rename the .feedbackcache files found in this directory.
  • Restart the service:
    net start MSSQLSERVER

Step 3: Adjust Minimum Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and connect via “New Query”.
  • Run the following to check current memory allocation:
  EXEC sp_configure 'min server memory';
  • Increase the minimum memory threshold to ensure enough headroom for metrics feedback initialization:
  EXEC sp_configure 'min server memory (MB)', 2048;
  RECONFIGURE;

Step 4: Disable Windows Memory Compression (If Applicable)

  • Open PowerShell as Administrator.
  • Check current memory compression status:
    Get-MMAgent
  • If enabled, disable it to prevent conflicts with SQL Server’s memory clerks:
    Disable-MMAgent -mc
  • Restart the Windows Server 2025 host for the change to take effect.

Alternative or Verification Steps

  • After restarting the SQL Server service, check the SQL Server Error Log (via SSMS > Management > SQL Server Logs) to confirm Error 8779 no longer appears during startup.
  • If the error persists, disable the adaptive feedback feature entirely as a temporary workaround by running ALTER DATABASE SCOPED CONFIGURATION SET OPERATOR_FEEDBACK = OFF; on the affected database.

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

Troubleshooting Guide: Error 8780 – Schema Mismatch During Native Data Movement

Why This Error Happens

Error 8780 typically occurs when SQL Server 2025’s native data movement engine detects a discrepancy between the source and destination table schemas, such as mismatched column data types, lengths, or ordinal positions. This can also be triggered by corrupted metadata cache entries left over from a previous schema change that wasn’t properly propagated. Additionally, insufficient permissions on the destination schema can prevent SQL Server from validating or altering the table structure mid-transfer, causing the engine to throw this error as a safety fallback.

Step-by-Step Resolution Guide

Step 1: Validate Source and Destination Schemas

  • Run sp_help 'TableName' on both the source and destination databases to compare column definitions.
  • Pay close attention to data type precision (e.g., VARCHAR(50) vs VARCHAR(100)), nullability, and column order.
  • Use SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTable' for a side-by-side export into Excel or a diff tool.

Step 2: Clear the Metadata Cache

  • Open SQL Server Management Studio (SSMS) 2025 and connect to the instance.
  • Execute DBCC FREESYSTEMCACHE('ALL') to clear stale schema metadata that may be causing false mismatch detection.
  • Restart the SQL Server service via Services.msc (search for “SQL Server (MSSQLSERVER)”) or run net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 3: Verify Destination Schema Permissions

  • Navigate to Security > Logins in SSMS and confirm the service account has ALTER and CONTROL permissions on the target schema.
  • On Windows Server 2025, check that the SQL Server service account (found in Services.msc under “Log On” tab) is not restricted by Group Policy or Windows Defender Application Control.
  • Grant permissions if needed: GRANT ALTER ON SCHEMA::dbo TO [YourServiceAccount].

Step 4: Rebuild the Data Movement Task

  • If using SSIS or Azure Data Factory native connectors, delete and recreate the data flow task to force a fresh schema mapping.
  • In the task properties, manually remap columns instead of relying on auto-mapping, which can carry over outdated schema references.

Alternative or Verification Steps

  • To verify the fix, re-run the data movement job and check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the absence of Error 8780.
  • If the issue persists, drop and recreate the destination table from the current source schema using SELECT INTO to guarantee a byte-for-byte schema match before retrying the transfer.

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

Troubleshooting Guide: SQL Server Error 8778 — ABORTQUERYEXECUTION Hint Triggered

Why This Error Happens

Error 8778 occurs when the Query Optimizer in SQL Server 2025 detects that a query’s estimated cost, plan compilation behavior, or resource usage exceeds the threshold defined by the ABORT_QUERY_EXECUTION query hint. This hint is typically applied intentionally through Query Store plan forcing, Resource Governor workload policies, or explicit OPTION clauses to prevent runaway queries from consuming excessive CPU, memory, or tempdb resources. The error surfaces when a query—often due to outdated statistics, a missing index, or a parameter sniffing issue—generates a plan that breaches the safety threshold the hint was designed to enforce.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Hint

  • Check whether the hint was applied via the query text itself (OPTION (ABORT_QUERY_EXECUTION)), a Query Store forced plan, or a Resource Governor workload group policy.
  • Run the following to check Query Store forced plans:
SELECT qsp.query_id, qsp.plan_id, qsp.is_forced_plan, qsp.force_failure_count
FROM sys.query_store_plan qsp
WHERE qsp.is_forced_plan = 1;
  • Review the SQL Server Error Log and Extended Events session system_health for the exact query_hash tied to Error 8778.

Step 2: Update Statistics and Rebuild Fragmented Indexes

  • Outdated statistics are the most common trigger for threshold breaches since they cause bad cardinality estimates.
  • Run UPDATE STATISTICS <TableName> WITH FULLSCAN; on the affected tables.
  • Rebuild fragmented indexes using SQL Server Management Studio (SSMS) 21 or via:
ALTER INDEX ALL ON dbo.YourTable REBUILD WITH (ONLINE = ON);

Step 3: Adjust or Remove the ABORTQUERYEXECUTION Threshold

  • Navigate to SSMS → Resource Governor → Workload Groups and review the REQUEST_MAX_CPU_TIME_SEC or MAX_DOP settings tied to the group executing the query.
  • If the hint is embedded in application code or a stored procedure, locate and temporarily remove it:
-- Example: remove hint from a stored procedure definition
ALTER PROCEDURE dbo.YourProc
AS
SELECT * FROM dbo.YourTable
OPTION (RECOMPILE); -- removed ABORT_QUERY_EXECUTION
  • If using Query Store forced plans, unforce the problematic plan:
EXEC sp_query_store_unforce_plan @query_id = <id>, @plan_id = <id>;

Step 4: Validate Server and Database Compatibility Level

  • Confirm the database is running under Compatibility Level 170 (SQL Server 2025) via:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDB';
  • A mismatched compatibility level can cause the optimizer to misjudge cost thresholds, inadvertently triggering the abort hint.

Alternative or Verification Steps

  • Re-run the original query manually in SSMS 21 with SET STATISTICS TIME, IO ON; to confirm it completes without triggering Error 8778 and executes within expected resource bounds.
  • If the error persists, as a temporary workaround, raise the Resource Governor CPU/memory threshold for the specific workload group or disable the hint at the session level using OPTION (USE HINT('DISABLE_ABORT_QUERY_EXECUTION')) while you investigate the root query plan regression further.

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

Why This Error Happens

SQL Server Error 8777 typically occurs when the Database Engine is unable to complete a data retrieval operation because the underlying OLE DB provider, linked server connection, or Change Data Capture (CDC) session cannot establish a stable handshake with the source. This is most commonly caused by expired or insufficient service account permissions on the target resource, a corrupted or orphaned CDC/replication metadata entry, or a network-level timeout between Windows Server 2025 and the remote data source. In some cases, a mismatched authentication protocol (NTLM vs. Kerberos) after a Windows Server 2025 security update can also trigger this failure mid-query.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open SQL Server Configuration Manager and confirm the account running the SQL Server (MSSQLSERVER) service.
  • Ensure this account has db_datareader rights on the source database and is not locked out in Active Directory.
  • Run the following in SSMS to check current login mappings:
  SELECT name, type_desc, is_disabled FROM sys.server_principals WHERE name LIKE '%YourServiceAccount%';

Step 2: Reset the Linked Server / CDC Connection

  • Navigate to Object Explorer > Server Objects > Linked Servers in SSMS.
  • Right-click the affected linked server and select Delete, then recreate it using the correct provider string (e.g., MSOLEDBSQL19 for SQL Server 2025 compatibility).
  • If using Change Data Capture, run:
  EXEC sys.sp_cdc_disable_db;
  EXEC sys.sp_cdc_enable_db;

Step 3: Clear Authentication Protocol Conflicts

  • On Windows Server 2025, open secpol.msc and confirm Network Security: LAN Manager authentication level is set to “Send NTLMv2 response only.”
  • Restart the SQL Server and SQL Server Agent services via services.msc to force a clean Kerberos ticket renewal.
  • Clear cached tickets using:
  klist purge

Step 4: Check Firewall and Port Configuration

  • Confirm TCP port 1433 (or your custom instance port) is open between the Windows 11 client and Windows Server 2025 host.
  • Use Test-NetConnection -ComputerName <ServerName> -Port 1433 in PowerShell to validate connectivity.
  • Update firewall rules in Windows Defender Firewall with Advanced Security if the connection times out.

Alternative or Verification Steps

  • Re-run the original query or data import job and check the SQL Server Error Log (EXEC sp_readerrorlog) to confirm Error 8777 no longer appears.
  • If the issue persists, fail over to a secondary replica (if using Always On Availability Groups) to isolate whether the fault is server-specific or data-source-specific.

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

Why This Error Happens

Error 8776 in SQL Server 2025 typically occurs when the Database Engine encounters a mismatch between index metadata and the underlying statistics object while attempting to resolve a data retrieval request. This is most commonly triggered by corrupted non-clustered index statistics, an interrupted automatic statistics update, or a permissions gap that prevents the SQL Server service account from reading temporary workspace files in TempDB. When this metadata mismatch occurs mid-query, the client application (such as SSMS or a reporting tool) appears to hang indefinitely on the “Getting Data” status because the server-side cursor never receives a valid completion signal.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11 and confirm the SQL Server (MSSQLSERVER) service is running under a valid domain or managed service account.
  • Right-click the data and log file directories (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA) and ensure the service account has Full Control.
  • Restart the SQL Server service after any permission change: net stop MSSQLSERVER && net start MSSQLSERVER

Step 2: Rebuild Corrupted Statistics and Indexes

  • Open a new query window in SQL Server Management Studio (SSMS) connected to the affected database.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORS; to identify corruption.
  • If errors are returned, execute EXEC sp_updatestats; followed by ALTER INDEX ALL ON dbo.YourTable REBUILD; to regenerate statistics and index pages.

Step 3: Clear and Reset TempDB Workspace

  • Stop the SQL Server service.
  • Navigate to the TempDB file location (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\tempdb.mdf) and confirm the files are not marked Read-only.
  • Restart the service to force SQL Server to regenerate a clean TempDB instance, which clears any orphaned workspace causing the 8776 handshake failure.

Step 4: Apply the Latest Cumulative Update

  • Check your current build via SELECT @@VERSION;.
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as this specific metadata-resolution bug is addressed in recent servicing releases.
  • Reboot the Windows Server 2025 / Windows 11 host after installation to fully apply engine-level binary changes.

Alternative or Verification Steps

  • Re-run the original query or report that previously hung on “Getting Data” — it should now return results within normal execution time (check via Activity Monitor in SSMS for active, non-blocked sessions).
  • If the error persists, restore the affected database from the last known good backup using RESTORE DATABASE to bypass potentially unrecoverable statistics corruption.

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

Why This Error Happens

Error 8775 in SQL Server 2025 is typically raised when the Storage Engine detects a mismatch between an index’s metadata and the underlying data pages while a client (such as SSMS’s “Edit Top 200 Rows” grid, a reporting tool, or an ADO.NET consumer) is actively attempting to retrieve data. This most often surfaces as the client appearing to hang on “Getting Data” before the error is thrown. The root cause is usually one of three things: a corrupted non-clustered index left over from an in-place upgrade, insufficient disk space or permissions in tempdb needed to build internal worktables for the scan, or stale/corrupted statistics that cause the query optimizer to request data pages that no longer match the current schema definition.

Step-by-Step Resolution Guide

Step 1: Verify Database and Index Integrity

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to scan for page-level or index-level corruption.
  • If corruption is found, run DBCC CHECKTABLE on the specific object to isolate the faulty index before considering a repair option.

Step 2: Rebuild Affected Indexes and Update Statistics

  • Identify the table/index referenced in the error log (check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact Object ID).
  • Rebuild the index using ALTER INDEX ALL ON dbo.YourTable REBUILD WITH (ONLINE = ON);
  • Refresh statistics with UPDATE STATISTICS dbo.YourTable WITH FULLSCAN; to ensure the optimizer uses accurate row/page estimates.

Step 3: Check tempdb Configuration and Permissions

  • Confirm tempdb has sufficient free space and autogrowth enabled via SSMS → Databases → tempdb → Properties → Files.
  • Validate that the SQL Server service account has Modify permissions on the tempdb data/log file directory (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) to clear any corrupted worktable allocations.

Step 4: Reapply the Latest Cumulative Update

  • Since this is a fresh Windows Server 2025 / Windows 11 environment, confirm SQL Server 2025 is patched to the latest Cumulative Update via SSMS → Help → About.
  • Download and apply the newest CU from the Microsoft Update Catalog if the build number is outdated, as early 2025 builds had known metadata caching issues tied to this error.

Alternative or Verification Steps

  • After applying fixes, re-run the original data retrieval operation (e.g., re-open “Edit Top 200 Rows” or re-run the SELECT query) and confirm it completes without hanging or throwing Error 8775.
  • If the error persists, restore the affected database from the most recent clean backup to a test instance and compare DBCC CHECKDB results to confirm whether corruption originated at the storage layer (disk/SAN) rather than SQL Server itself.

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

Why This Error Happens

Error 8774 in SQL Server 2025 typically occurs when the Database Engine fails to retrieve data from a linked server, external data source, or PolyBase connection due to a broken authentication chain or expired credential mapping. This is commonly triggered by Kerberos delegation failures, mismatched SQL Server service account permissions, or corrupted connection metadata in the sys.servers catalog. In Windows Server 2025 environments, Group Managed Service Account (gMSA) token refresh issues are also a frequent root cause, especially after a password rotation cycle.

Step-by-Step Resolution Guide

Step 1: Verify Linked Server and Credential Configuration

  • Open SQL Server Management Studio (SSMS) and expand Server Objects > Linked Servers.
  • Right-click the linked server reporting the “Getting Data” failure and select Properties > Security.
  • Confirm the mapping uses a valid login with “Be made using this security context” and re-enter the password to force a credential refresh.

Step 2: Check Service Account and Kerberos Delegation

  • Open Active Directory Users and Computers on the Windows Server 2025 domain controller.
  • Locate the SQL Server service account (or gMSA) and confirm “Trust this computer for delegation to specified services only” is enabled under the Delegation tab.
  • Run klist from an elevated Command Prompt on the SQL Server host to confirm a valid Kerberos ticket exists for the target data source.

Step 3: Repair Corrupted Linked Server Metadata

  • In SSMS, run the following to drop and recreate the broken linked server entry:
EXEC sp_dropserver 'LinkedServerName', 'droplogins';
EXEC sp_addlinkedserver 'LinkedServerName', 'SQLNCLI';
EXEC sp_addlinkedsrvlogin 'LinkedServerName', 'false', NULL, 'RemoteUser', 'RemotePassword';
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to clear cached connection handles.

Step 4: Validate Firewall and Port Accessibility

  • On Windows Server 2025, open Windows Defender Firewall with Advanced Security.
  • Confirm inbound/outbound rules allow TCP port 1433 (or the custom port configured) between the SQL Server instance and the remote data source.
  • Use Test-NetConnection -ComputerName RemoteServer -Port 1433 in PowerShell to confirm connectivity.

Alternative or Verification Steps

  • Run SELECT * FROM OPENQUERY(LinkedServerName, 'SELECT 1') in SSMS to confirm the “Getting Data” operation completes without triggering Error 8774.
  • If the issue persists, temporarily switch the linked server authentication to a SQL login (instead of Windows Authentication) to isolate whether the fault lies in Kerberos delegation or the data source itself.

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

Troubleshooting Guide: Error 8772 — Recompile for Trident Result Set Cache Creation

Why This Error Happens

Error 8772 occurs when SQL Server 2025’s Trident Result Set Cache engine attempts to materialize a cached execution plan but encounters a schema or statistics mismatch that forces an immediate recompile before the cache object can be committed to the buffer pool. This typically stems from the Trident caching subsystem lacking sufficient metadata lock priority on the target table, or from the RESULT_SET_CACHING database-scoped configuration being toggled mid-session while active queries hold references to stale cache descriptors. In most cases, this is compounded by insufficient permissions on the TRIDENT_CACHE_STORE filegroup, preventing the engine from writing the serialized result set to disk.

Step-by-Step Resolution Guide

Step 1: Verify Trident Cache Service Permissions

  • Open SQL Server Configuration Manager and confirm the SQL Server service account has read/write access to the Trident cache directory (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\TridentCache).
  • Run the following T-SQL to check current grants:
  SELECT * FROM sys.dm_db_trident_cache_permissions;
  • Grant db_datareader and db_cacheadmin roles if missing:
  ALTER ROLE db_cacheadmin ADD MEMBER [DOMAIN\SQLServiceAccount];

Step 2: Disable and Re-enable Result Set Caching at the Database Level

  • Execute the following to reset the caching subsystem cleanly:
  ALTER DATABASE SCOPED CONFIGURATION SET RESULT_SET_CACHING = OFF;
  GO
  ALTER DATABASE SCOPED CONFIGURATION SET RESULT_SET_CACHING = ON;
  GO
  • This clears any orphaned cache descriptors left in memory from a previous crashed or forcibly-killed session.

Step 3: Update Statistics and Force a Clean Recompile

  • Outdated statistics are a common trigger for recompile loops in Trident caching.
  • Run:
  UPDATE STATISTICS <TableName> WITH FULLSCAN;
  DBCC FREEPROCCACHE;
  • Restart the SQL Server Trident Cache Manager service via PowerShell:
  Restart-Service -Name "MSSQLTridentCacheMgr"

Step 4: Validate Filegroup Integrity

  • Run DBCC CHECKFILEGROUP against the TRIDENT_CACHE_STORE filegroup to rule out page-level corruption:
  DBCC CHECKFILEGROUP ('TRIDENT_CACHE_STORE');
  • If corruption is detected, rebuild the filegroup and re-initialize the cache store using sp_trident_cache_rebuild.

Alternative or Verification Steps

  • Confirm resolution by re-running the original query and checking sys.dm_exec_trident_cache_stats for a HIT status instead of RECOMPILE_PENDING.
  • If the error persists, disable Trident Result Set Caching entirely at the instance level (sp_configure 'trident cache enabled', 0;) as a temporary workaround while escalating to Microsoft Support with the latest TridentCache_*.log files from the LOG directory.

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

Troubleshooting Guide: SQL Server Error 8773

Why This Error Happens

Error 8773 is classified as a reserved internal error code within the SQL Server Database Engine and is explicitly documented as a placeholder that “should never be issued” during normal operation. If this error surfaces, it typically indicates a corrupted system catalog, a severe internal metadata inconsistency, or a flawed query execution plan that triggers an undefined internal code path. In rare cases, it can also appear due to a corrupted SQL Server installation or a bug in a specific build that incorrectly maps an internal state to this reserved error number.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Apply Latest Cumulative Update

  • Check your current version by running SELECT @@VERSION; in a query window.
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the update via the setup wizard, ensuring the SQL Server service account has sufficient permissions on C:\Program Files\Microsoft SQL Server\.
  • Restart the SQL Server service via services.msc after installation completes.

Step 2: Run Database Consistency Checks (DBCC CHECKDB)

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to scan for corruption.
  • Review the output for allocation or consistency errors that may be triggering the reserved error path.
  • If corruption is found, run DBCC CHECKDB ('YourDatabaseName', REPAIR_REBUILD); in single-user mode.

Step 3: Review the SQL Server Error Log for Context

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG (adjust instance folder name as needed).
  • Search for the timestamp surrounding the 8773 occurrence to identify the triggering query or process (e.g., a specific stored procedure or DDL statement).
  • Cross-reference the preceding error lines, as Error 8773 often follows a more descriptive root-cause error (such as a metadata corruption code).
  • Isolate and re-run the triggering statement in a test environment to confirm reproducibility.

Step 4: Repair or Reinstall the SQL Server Instance

  • Open “Control Panel” > “Programs and Features,” select Microsoft SQL Server 2025, and choose “Repair.”
  • Follow the Installation Wizard prompts, selecting the specific instance exhibiting the error.
  • If the repair does not resolve it, perform a full uninstall and clean reinstall, ensuring the Setup Bootstrap logs in C:\Program Files\Microsoft SQL Server\170\Setup Bootstrap\Log are clear of errors.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or transaction that triggered Error 8773 and confirm it completes without exception; also re-run DBCC CHECKDB to ensure zero allocation or consistency errors are reported.
  • If the error persists after patching and repair, open a Microsoft Support (CSS) ticket and attach the ERRORLOG and a SQL Server dump file (.mdmp) from C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\LOG\, as this indicates a potential engine-level bug requiring a hotfix.

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

Troubleshooting Guide: SQL Server Error 8771 – Unsupported Operator for Resource Actuals Feedback

Why This Error Happens

Error 8771 typically occurs when SQL Server’s Query Optimizer encounters an incompatible or deprecated operator while attempting to log actual resource usage statistics back into the Query Store or adaptive feedback mechanism. This is commonly triggered by corrupted Query Store metadata, a mismatch between the cardinality estimator version and the execution plan operator, or an incomplete upgrade from a previous SQL Server version where legacy plan operators are no longer recognized by the new feedback engine. In some cases, this stems from corrupted system catalog views responsible for tracking actual vs. estimated resource consumption.

Step-by-Step Resolution Guide

Step 1: Verify Query Store and Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check the current compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the compatibility level matches SQL Server 2025 (160 or higher). If it is set to an older level (e.g., 130 or 140), legacy operators may conflict with the new feedback engine.
  • Update the compatibility level if needed:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160;

Step 2: Clear and Rebuild Query Store Data

  • Corrupted Query Store entries are a primary cause of operator mismatches during feedback logging.
  • Navigate to Database Properties > Query Store in SSMS and set the operation mode to OFF, then back to READ_WRITE.
  • Alternatively, run the following T-SQL command to purge stale data:
  ALTER DATABASE YourDatabaseName SET QUERY_STORE CLEAR;
  • Restart the SQL Server service via services.msc or PowerShell:
  Restart-Service -Name MSSQLSERVER -Force

Step 3: Disable Adaptive Feedback Temporarily via Trace Flag

  • If the error persists, disable the Intelligent Query Processing (IQP) feedback loop that triggers the actuals comparison.
  • Add Trace Flag 9476 (or the relevant IQP-disabling flag for 2025 builds) to the SQL Server startup parameters:
  • Open SQL Server Configuration Manager > SQL Server Services > Right-click instance > Properties > Startup Parameters.
  • Add: -T9476
  • Restart the SQL Server service for the change to take effect.

Step 4: Apply the Latest Cumulative Update (CU)

  • Check your current build version:
  SELECT @@VERSION;
  • Download and install the latest Cumulative Update for SQL Server 2025 from the Microsoft Update Catalog, as this specific operator bug is often patched in incremental servicing releases.
  • Reboot the Windows Server 2025 / Windows 11 host after installation to ensure all binaries are properly replaced.

Alternative or Verification Steps

  • To verify the fix, run the previously failing query or workload again and monitor the SQL Server Error Log (Management > SQL Server Logs in SSMS) to confirm Error 8771 no longer appears.
  • If the error persists after patching, as a fallback, force the legacy Cardinality Estimator for the specific database using ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = ON; to bypass the new feedback operator entirely.

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

Troubleshooting Guide: SQL Server Error 8769 – Estimated Result Set Size Warning

Why This Error Happens

This warning is triggered by SQL Server’s query optimizer when it estimates that a query will return a result set large enough to cause significant memory grant pressure, network saturation, or client-side processing bottlenecks. It is not a fatal error but a proactive alert, often surfacing when queries lack a WHERE clause, use broad SELECT * statements, or join large tables without adequate filtering. The underlying cause is typically poor query design combined with outdated or missing statistics that prevent the optimizer from suggesting more efficient execution paths.

Step-by-Step Resolution Guide

Step 1: Analyze the Query Execution Plan

  • Open SQL Server Management Studio (SSMS) and enable “Include Actual Execution Plan” (Ctrl+M).
  • Run the offending query and look for the warning icon on the SELECT operator.
  • Check the “Estimated Number of Rows” vs “Actual Number of Rows” to confirm if statistics are skewed.

Step 2: Apply Explicit Filtering and Pagination

  • Rewrite the query to include a specific WHERE clause targeting indexed columns.
  • Implement OFFSET-FETCH or TOP (N) clauses to limit result sets for ad-hoc reporting.
  • Example syntax:
  SELECT * FROM Sales.OrderDetails 
  WHERE OrderDate >= '2025-01-01' 
  ORDER BY OrderID 
  OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY;

Step 3: Update Statistics and Rebuild Indexes

  • Navigate to the specific database in SSMS Object Explorer.
  • Run the following T-SQL command to force a full scan update on the table statistics:
  UPDATE STATISTICS [TableName] WITH FULLSCAN;
  • If fragmentation is high (check via sys.dm_db_index_physical_stats), rebuild the clustered index to improve the optimizer’s row estimation accuracy.

Step 4: Redirect Output for Bulk Data Operations

  • If the large result set is intentional (e.g., a data migration), do not stream it to the SSMS grid.
  • Use the bcp utility via Command Prompt to export data directly to a flat file, bypassing the client memory limit warning:
  bcp "SELECT * FROM LargeTable" queryout "C:\Exports\data.csv" -c -t, -S ServerName -T
  • Alternatively, configure an External Table (PolyBase) if the data needs to be queried again without loading it into SQL Server memory.

Alternative or Verification Steps

  • Verification: Re-run the query with “Actual Execution Plan” enabled; the Warning 8769 icon should no longer appear if the row estimate is now below the server’s configured threshold.
  • Alternative: If performance remains inconsistent, check the Resource Governor settings on Windows Server 2025 to ensure the workload group assigned to the user has sufficient MAX_MEMORY_PERCENT to handle the query grant without triggering estimation warnings.

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

Troubleshooting Guide: SQL Server Error 8770 – “Unsupported Expression in Memo XML”

Why This Error Happens

Error 8770 typically occurs when the SQL Server Query Optimizer encounters an internal inconsistency while generating or parsing the Memo XML structure used during query plan caching and optimization. This is often triggered by corrupted plan cache entries, outdated or buggy cardinality estimation logic, or malformed query constructs (such as deeply nested CTEs, unsupported hints, or incompatible collation expressions) that the optimizer cannot translate into a valid internal representation. In some cases, this error surfaces after applying a Cumulative Update (CU) that introduces a regression in the Query Optimizer’s expression-handling module.

Step-by-Step Resolution Guide

Step 1: Clear the Plan Cache and Retry the Query

  • Open SQL Server Management Studio (SSMS) connected to the affected instance.
  • Run DBCC FREEPROCCACHE; to remove potentially corrupted cached execution plans.
  • Re-execute the failing query to see if the error persists outside of a cached (and possibly corrupted) plan.
  • If the issue is isolated to a single query, run DBCC FREESYSTEMCACHE('ALL'); for a more thorough cache reset.

Step 2: Identify and Isolate the Offending Query Construct

  • Review the query for complex elements such as nested Common Table Expressions (CTEs), OUTER APPLY/CROSS APPLY with scalar subqueries, or non-standard OPTION query hints.
  • Temporarily simplify the query by removing hints like OPTION (RECOMPILE) or OPTION (USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION')).
  • Test with OPTION (QUERYTRACEON 9481) to force the legacy Cardinality Estimator (CE), as this frequently bypasses the issue in newer CE models under SQL Server 2025.

Step 3: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest CU for SQL Server 2025.
  • Verify your current build number by running SELECT @@VERSION; in a query window.
  • Install the update via the standalone installer, ensuring you run it with elevated (Administrator) privileges on Windows Server 2025 / Windows 11.
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER after installation.

Step 4: Rebuild Statistics and Check Database Consistency

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption.
  • Execute EXEC sp_updatestats; to refresh outdated statistics that may be feeding bad metadata into the optimizer.
  • If corruption is found, restore from the last known good backup rather than attempting an in-place repair on production data.

Alternative or Verification Steps

  • To verify the fix, re-run the original query with SET STATISTICS XML ON; and confirm that a valid execution plan is generated without triggering Error 8770.
  • If the error persists after patching, as a workaround, rewrite the query to avoid the specific optimizer path (e.g., replace a CTE with a temp table) while you open a support ticket with Microsoft CSS, attaching the Memo XML dump found in the SQL Server ERRORLOG.

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

Troubleshooting Guide: Error 8768 — Recursive CTEs Unsupported in Synapse SQL

Why This Error Happens

Error 8768 occurs when a T-SQL query containing a recursive Common Table Expression (CTE) is executed against a database or compute pool operating under Synapse SQL compatibility mode, which does not support recursive query plans. This typically happens when a database was migrated to or created under a Synapse-targeted compatibility level, or when a client application mistakenly routes a query to a Serverless/Dedicated SQL pool endpoint instead of a standard SQL Server 2025 engine instance. It can also surface if the database compatibility level was set incorrectly during an upgrade from an older SQL Server version to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the Target Engine and Connection Endpoint

  • Confirm you are connecting to a genuine SQL Server 2025 instance and not a Synapse SQL pool endpoint.
  • Check the connection string or SSMS “Server name” field — Synapse endpoints typically resemble yourworkspace.sql.azuresynapse.net.
  • Run SELECT SERVERPROPERTY('Edition'), SERVERPROPERTY('ProductVersion'); to confirm the engine type.

Step 2: Check and Correct Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to check current compatibility level:
  • SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is incorrectly set to a Synapse-mapped value, update it:
  • ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 3: Review and Rewrite the Query Execution Context

  • Inspect the query or stored procedure for the recursive CTE syntax (WITH cte AS (... UNION ALL ...)).
  • Ensure the query is not being executed inside a context forwarded to a linked Synapse resource (check linked servers via sp_linkedservers).
  • If using Polybase or external tables pointing to Synapse, isolate the recursive CTE logic to run locally against the SQL Server 2025 engine instead.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 / Windows 11 to confirm the installed SQL Server build.
  • Download and apply the latest Cumulative Update (CU) from the Microsoft Update Catalog, as early SQL Server 2025 builds had misclassified engine-mode flags affecting recursive CTE support.
  • Restart the SQL Server service via services.msc after patching.

Step 5: Restart SQL Server Services

  • Open services.msc on Windows Server 2025 / Windows 11.
  • Restart SQL Server (MSSQLSERVER) and SQL Server Agent services to ensure configuration changes take effect.

Alternative or Verification Steps

  • Re-run the original recursive CTE query after applying the compatibility level fix; a successful result set confirms resolution.
  • If the error persists, temporarily rewrite the recursive CTE using a WHILE loop with a temporary table as a functional workaround while further diagnosing the engine routing issue.

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

Troubleshooting Guide: SQL Server Error 8767 – Metadata Read Failure from Distribution

Why This Error Happens

Error 8767 typically occurs when SQL Server’s distributed query engine encounters corrupted or inaccessible metadata while attempting to read partition or distribution statistics from a scaled-out or PolyBase-enabled data source. This is commonly caused by a mismatch between the cached execution plan and the actual schema of the distributed table, stale statistics on the Data Movement Service (DMS), or network interruptions between compute and storage nodes during metadata retrieval. In some cases, this also stems from insufficient permissions on the distribution system view, preventing SQL Server from validating the metadata structure correctly.

Step-by-Step Resolution Guide

Step 1: Clear and Rebuild the Distributed Query Cache

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC FREEPROCCACHE to clear cached execution plans that may reference outdated distribution metadata.
  • Execute UPDATE STATISTICS [schema].[table_name] WITH FULLSCAN on the affected distributed table to refresh metadata.

Step 2: Verify Data Movement Service (DMS) Health

  • Open Services.msc on Windows Server 2025 and locate SQL Server Data Movement Service.
  • Confirm the service status is “Running”; if not, restart it and monitor the DMS logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\DMS\.
  • Check for .xel trace files indicating timeout or corruption errors during metadata handshake.

Step 3: Validate Permissions on System Metadata Views

  • Run the following query to confirm the executing login has correct access:
  SELECT * FROM sys.fn_my_permissions('sys.dm_db_distributed_sql_requests', 'OBJECT');
  • Ensure the service account running SQL Server has db_datareader rights on system catalog views.
  • Grant missing permissions using GRANT VIEW DATABASE STATE TO [user] if required.

Step 4: Rebuild Corrupted Distribution Metadata

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ and check for orphaned .ndf files tied to distributed partitions.
  • Run DBCC CHECKDB (YourDatabaseName) WITH DATA_PURITY to identify and repair structural inconsistencies.
  • If corruption is confirmed, restore the affected filegroup from the most recent verified backup.

Step 5: Restart SQL Server Instance and Validate Network Path

  • Restart the SQL Server (MSSQLSERVER) service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.
  • Confirm no firewall rules on Windows Server 2025 are blocking internal node communication on port 1433 or the DMS internal ports (default range 16450–16460).

Alternative or Verification Steps

  • Re-run the original distributed query that triggered Error 8767; if it completes without exception, the metadata cache and permissions are correctly restored.
  • If the error persists, use Extended Events (xevents) to capture the exact distribution ID (%d) referenced in the error and cross-check it against sys.dm_exec_distributed_request_steps for orphaned or mismatched entries.

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

Troubleshooting Guide: SQL Server Error 8765

Why This Error Happens

Error 8765 occurs when SQL Server’s distributed query or replication engine fails to establish or maintain a connection between distribution databases during a cross-distribution operation. This is typically caused by network latency, firewall restrictions blocking inter-node communication, expired or misconfigured linked server credentials, or corrupted distribution database metadata. In SQL Server 2025 running on Windows Server 2025 or Windows 11, this can also stem from TLS/encryption mismatches between distributor instances or exhausted connection pools under high replication load.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity Between Distribution Nodes

  • Use Test-NetConnection -ComputerName <DistributorServerName> -Port 1433 in PowerShell to confirm the port is reachable.
  • Check Windows Firewall rules via wf.msc and ensure inbound/outbound rules allow SQL Server traffic (default TCP 1433, or custom port if configured).
  • Confirm no intermediate network ACLs or Windows Defender Firewall with Advanced Security policies are silently dropping packets.

Step 2: Validate Linked Server and Distribution Credentials

  • Open SQL Server Management Studio (SSMS) and navigate to Server Objects > Linked Servers.
  • Right-click the relevant linked server, select Properties, and verify the Security tab credentials are current and not expired.
  • Run EXEC sp_testlinkedserver 'YourLinkedServerName'; to confirm the connection succeeds.
  • If using Windows Authentication, ensure the SQL Server service account has proper permissions on both distribution servers.

Step 3: Inspect and Repair Distribution Database Metadata

  • Run EXEC sp_helpdistributor; to confirm the distributor configuration is intact.
  • Check for corruption using DBCC CHECKDB('distribution') WITH NO_INFOMSGS; on the distribution database.
  • If corruption is found, restore the distribution database from a known good backup located in your standard backup path (e.g., D:\SQLBackups\Distribution\).

Step 4: Review TLS/Encryption Configuration

  • Open SQL Server Configuration Manager, navigate to SQL Server Network Configuration > Protocols, and confirm the “Force Encryption” setting matches on both source and destination servers.
  • Update or reissue TLS certificates if they are expired or mismatched, using the Certificates MMC snap-in (certlm.msc).
  • Restart the SQL Server service after applying certificate changes: Restart-Service -Name MSSQLSERVER.

Step 5: Increase Connection Timeout and Pool Settings

  • In SSMS, right-click the server instance, go to Connections, and increase the Remote query timeout value (default 600 seconds) if replication jobs are timing out under load.
  • Adjust max pool size in the connection string if using a custom replication agent.

Alternative or Verification Steps

  • Re-run the failing query or replication job and monitor the SQL Server Error Log (EXEC xp_readerrorlog;) to confirm Error 8765 no longer appears.
  • If the issue persists, drop and recreate the linked server/distribution relationship entirely using sp_dropdistributor followed by sp_adddistributor, then reconfigure publications from scratch.

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

Why This Error Happens

Error 8766 typically occurs in distributed or partitioned database architectures when data exchange between distribution nodes is interrupted mid-transfer. This is commonly caused by network latency spikes, a corrupted temporary buffer file used during the data shuffle operation, or insufficient memory grants causing the receiving distribution to drop the incoming data stream. In Microsoft SQL Server 2025’s enhanced distributed query engine, this can also stem from a mismatch in the Data Movement Service (DMS) configuration between nodes in the pool.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity Between Distribution Nodes

  • Open PowerShell as Administrator and run Test-NetConnection -ComputerName <NodeName> -Port 1433 to confirm the SQL port is open between nodes.
  • Check for packet loss using ping <NodeName> -t for at least 60 seconds during a reproduction attempt.
  • Ensure Windows Firewall rules on Windows Server 2025 allow inbound/outbound traffic for the Data Movement Service (default port range 16450-16460).

Step 2: Clear and Rebuild the Temporary Data Movement Cache

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\DMS_TEMP and stop the SQL Server service before proceeding.
  • Run net stop MSSQLSERVER followed by net stop SQLDMS in an elevated Command Prompt.
  • Delete all .tmp and .buffer files within the DMS_TEMP directory to clear corrupted shuffle artifacts.
  • Restart services using net start SQLDMS then net start MSSQLSERVER.

Step 3: Increase Memory Grant for Distributed Queries

  • Open SQL Server Management Studio (SSMS) and connect to the Control Node.
  • Run the following query to check current memory grant settings:
  EXEC sp_configure 'min memory per query', '2048';
  RECONFIGURE;
  • Adjust the max server memory setting under Server Properties > Memory to ensure at least 20% headroom is reserved for distribution data transfers.

Step 4: Re-sync Distribution Metadata

  • Run DBCC CHECKDISTRIBUTION against the affected database to validate node-to-node mapping consistency.
  • If inconsistencies are found, execute ALTER DATABASE [YourDB] REBUILD DISTRIBUTION MAP; to force a metadata resync across all nodes.

Alternative or Verification Steps

  • Re-run the original failing query and monitor sys.dm_exec_distributed_request_steps in real time to confirm the data movement phase completes without timeout or disconnection errors.
  • If the error persists after these steps, failover to a single-node execution plan temporarily by setting SET DISTRIBUTED_QUERY_MODE = OFF; at the session level to isolate whether the issue is node-specific or query-specific.

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

Troubleshooting Guide: SQL Server Error 8764

Why This Error Happens

Error 8764 occurs when SQL Server’s distributed query processor fails to transmit metadata between distribution nodes during a parallel query execution, typically due to network instability or packet loss between the nodes involved. This can also be triggered by corrupted communication buffers, mismatched SQL Server patch levels across nodes in a distributed configuration, or insufficient memory resources preventing proper metadata serialization. In some cases, firewall rules or security software on Windows Server 2025 may be intermittently blocking or throttling the internal communication ports used for distribution traffic.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity Between Distribution Nodes

  • Open PowerShell as Administrator and run Test-NetConnection -ComputerName <TargetNodeName> -Port 1433 to confirm the SQL Server port is reachable.
  • Check for packet loss using ping <TargetNodeIP> -t over an extended period and look for timeouts.
  • Review the Windows Event Viewer under Windows Logs > System for any NIC or network adapter errors coinciding with the failure timestamp.

Step 2: Check and Align SQL Server Patch Levels

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; on each node participating in the distributed query.
  • Ensure all nodes are running the same Cumulative Update (CU) build for SQL Server 2025 by cross-referencing with Microsoft’s official build list.
  • If mismatched, download and apply the latest matching CU from the Microsoft Update Catalog to all nodes.

Step 3: Review Firewall and Security Software Configuration

  • Navigate to Control Panel > Windows Defender Firewall > Advanced Settings on both Windows Server 2025 and Windows 11 machines.
  • Confirm that inbound and outbound rules exist for sqlservr.exe and the specific TCP ports used for distributed query traffic (commonly 1433 and dynamic ports above 49152).
  • Temporarily disable third-party antivirus/security software to rule out packet inspection interference, then re-test the query.

Step 4: Increase Network Packet Size and Timeout Settings

  • In SSMS, right-click the server instance, select Properties > Connections, and verify the “Remote query timeout” value is not too restrictive (default is 600 seconds; consider increasing to 1200 for large distributed queries).
  • Under Server Properties > Advanced, check the “Network Packet Size (B)” setting and increase it from the default 4096 to 8192 if large metadata payloads are involved.
  • Restart the SQL Server service via Restart-Service -Name MSSQLSERVER for changes to take effect.

Step 5: Rebuild or Refresh Distribution Statistics

  • Run DBCC SHOW_STATISTICS on the relevant distributed tables to check for corruption or outdated statistics.
  • Execute UPDATE STATISTICS <TableName> WITH FULLSCAN; on both source and target distribution nodes.
  • Re-run the original failing query to confirm metadata now transmits successfully.

Alternative or Verification Steps

  • Re-execute the original query that triggered Error 8764 and monitor SQL Server Profiler or Extended Events for successful completion without network-related warnings.
  • If the error persists after all steps, consider isolating the distributed query to a single node temporarily (removing the second distribution target) to confirm whether the issue is network-specific or related to the query’s metadata structure itself.

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

Troubleshooting Guide: Error 8762 – Table-Valued Function Not Supported in Synapse SQL

Why This Error Happens

This error occurs when a T-SQL query references a table-valued function (TVF) against a Synapse-connected database or external table endpoint that does not support the full T-SQL surface area available in standard SQL Server 2025 engines. Synapse SQL (serverless or dedicated pools) enforces a restricted subset of functions for distributed query compatibility, and multi-statement or certain system TVFs fall outside this supported list. This typically surfaces when PolyBase connectors, linked servers, or Synapse Link for SQL Server 2025 route a query through the Synapse compute layer instead of the native SQL Server engine.

Step-by-Step Resolution Guide

Step 1: Identify the Query Execution Context

  • Check whether the query is being executed against a Synapse-linked database, external table, or a standard local SQL Server 2025 database.
  • Run SELECT SERVERPROPERTY('EngineEdition') to confirm if the session is routed through Synapse (EngineEdition = 6) rather than the standard SQL Server engine (EngineEdition = 3).
  • Review the connection string or application DSN used by the client to confirm the target endpoint (e.g., *.sql.azuresynapse.net vs. local instance name).

Step 2: Replace Unsupported TVF Calls

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio and locate the offending function call referenced in the error (%s placeholder will show the actual function name in the error details pane).
  • Rewrite multi-statement table-valued functions (MSTVFs) as inline table-valued functions (iTVFs), since Synapse SQL only supports inline TVFs.
  • If the function is a system TVF (e.g., sys.dm_exec_query_stats), replace it with a supported Dynamic Management View or move the logic to a stored procedure executed outside the Synapse compute path.

Step 3: Adjust Compatibility Level and Connector Settings

  • On Windows Server 2025, open SSMS, right-click the database, go to Properties > Options, and verify Compatibility Level is set to 170 (SQL Server 2025) for native execution rather than being downgraded for Synapse interoperability.
  • If using PolyBase or Synapse Link, navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\polybase and confirm the connector version supports native TVFs; update via Setup if outdated.
  • Restart the PolyBase Data Movement Service: net stop MSSQLSERVER then net start MSSQLSERVER to apply connector configuration changes.

Step 4: Isolate the Query from Synapse Routing

  • If the function must run natively, force local execution using OPTION (USE HINT('DISABLE_EXTERNAL_PUSHDOWN')) at the end of the query to prevent SQL Server from offloading execution to Synapse.
  • Validate this by checking the actual execution plan in SSMS (Ctrl+M) for a “Remote Query” or “Synapse Compute” operator; it should no longer appear after applying the hint.

Alternative or Verification Steps

  • Re-run the original query after rewriting the TVF as inline and confirm Error 8762 no longer appears in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • As a fallback, execute the function locally via a linked server pointing to a non-Synapse instance, bypassing the Synapse SQL restriction entirely while preserving the original function logic.

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

Troubleshooting Guide: Error 8763 – TABLESAMPLE with ‘ROWS’ Clause Unsupported in Synapse SQL

Why This Error Happens

This error occurs because Microsoft SQL Server 2025’s query engine is routing the TABLESAMPLE operation through a Synapse SQL compatibility layer that does not support the ROWS keyword syntax, only the PERCENT clause. This typically happens when a database is configured with a compatibility level or connection driver that targets Azure Synapse Analytics semantics rather than native SQL Server 2025 T-SQL parsing. It can also surface if a migration script written for a different engine (such as a data warehouse export) was executed as-is without rewriting sampling logic for on-premises SQL Server syntax.

Step-by-Step Resolution Guide

Step 1: Identify the Query Context Triggering the Error

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact query using TABLESAMPLE (n ROWS).
  • Check the database compatibility level by running:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the connection string or endpoint is pointing to a Synapse-style serverless pool instead of a standard SQL Server 2025 instance.

Step 2: Rewrite the TABLESAMPLE Clause Using Supported Syntax

  • Replace the unsupported ROWS clause with the PERCENT equivalent, since Synapse SQL and many compatibility modes only parse percentage-based sampling.
  • Example fix:
  -- Unsupported
  SELECT * FROM Sales.Orders TABLESAMPLE (1000 ROWS);

  -- Supported rewrite
  SELECT * FROM Sales.Orders TABLESAMPLE (10 PERCENT);
  • Save and re-run the query to confirm the parser accepts it.

Step 3: Correct the Database Compatibility Level (If Applicable)

  • If the database was inadvertently set to a Synapse-compatible level during migration, reset it to the native SQL Server 2025 level:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc or run:
  Restart-Service -Name 'MSSQLSERVER'
  • Re-test the original ROWS-based query to see if native parsing now accepts it correctly.

Step 4: Verify Connection Endpoint and Driver Version

  • In your application or SSMS connection dialog, confirm the server name does not point to a .sql.azuresynapse.net endpoint.
  • Update the SQL Server Native Client or ODBC driver to the latest version matching SQL Server 2025 requirements via Windows Update or the official Microsoft Download Center.
  • Re-establish the connection and re-execute the query.

Alternative or Verification Steps

  • To verify the fix, run the corrected query in a new session and confirm Error 8763 no longer appears in the SSMS Messages tab or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, if PERCENT sampling does not meet row-count precision needs, use TOP (n) combined with ORDER BY NEWID() to achieve a comparable random row sample without triggering the Synapse parser restriction.

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

Troubleshooting Guide: SQL Server Error 8761 – “Unsupported Virtual Column in Memo XML”

Why This Error Happens

This error typically occurs when the SQL Server Query Optimizer encounters a corrupted or incompatible memo structure while generating execution plan XML, often due to a mismatch between computed/virtual column metadata and the internal plan cache. It can also surface after an in-place upgrade to SQL Server 2025 where legacy virtual column definitions (from older compatibility levels) are not fully normalized against the new Memo XML schema. In some cases, corrupted statistics or an outdated query plan cached prior to a cumulative update can trigger this inconsistency.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure and Plan Cache

  • Open SQL Server Management Studio (SSMS) connected to the affected instance.
  • Run DBCC FREEPROCCACHE; to purge invalid cached execution plans.
  • If the issue is isolated to one database, use DBCC FLUSHPROCINDB (<database_id>); instead of a full cache flush to minimize performance impact on other workloads.

Step 2: Update Statistics and Rebuild Virtual/Computed Columns

  • Run EXEC sp_updatestats; on the affected database to refresh outdated statistics.
  • Identify tables with persisted computed columns using:
    SELECT name, is_persisted FROM sys.computed_columns WHERE is_persisted = 1;
  • Drop and recreate any computed columns flagged with is_persisted = 1 that reference deprecated functions incompatible with SQL Server 2025 compatibility level 170.

Step 3: Verify Database Compatibility Level

  • Check the current compatibility level:
    SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the database is running on compatibility level 150 or lower, update it to 170 (SQL Server 2025) using:
    ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via Services.msc (Windows Server 2025/Windows 11) to ensure the Query Optimizer reloads cleanly.

Step 4: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update for SQL Server 2025.
  • Install the update using the standalone setup file (e.g., SQLServer2025-KB5XXXXXX-x64.exe) with administrative privileges.
  • Reboot Windows Server 2025/Windows 11 if prompted to finalize the patch installation.

Step 5: Run DBCC CHECKDB for Corruption

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying page-level corruption affecting the memo structure.
  • Review the output log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for related warnings.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 8761 and confirm the execution plan generates without exceptions in the Actual Execution Plan tab of SSMS.
  • If the error persists, isolate the query using SET SHOWPLAN_XML ON; to manually inspect the generated XML for the specific virtual column causing the conflict, then refactor the query to avoid referencing that column directly.

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

Troubleshooting Guide: Error 8759 – “Get Length of Node List from XML DOM Node Failed” in SQL Server 2025

Why This Error Happens

Error 8759 occurs when SQL Server’s internal XML parser (MSXML/SQLXML engine) fails to traverse or enumerate nodes within an XML DOM tree, typically due to a malformed or truncated XML document being passed into an OPENXML or XML data type method. This can also result from memory pressure or resource constraints on the server, causing the DOM handle to become invalid mid-operation. In some cases, corrupted XML schema collections or an outdated XML parser component on Windows Server 2025 can trigger this failure even when the source XML appears structurally valid.

Step-by-Step Resolution Guide

Step 1: Validate the XML Input Source

  • Run the XML string through an external validator (e.g., xmllint or Visual Studio XML Editor) before passing it to sp_xml_preparedocument.
  • Check for unclosed tags, invalid encoding declarations, or mismatched namespaces.
  • Confirm the XML does not exceed the 2GB internal DOM representation limit, which can silently corrupt node traversal.

Step 2: Clear Orphaned XML Document Handles

  • Execute sp_xml_removedocument immediately after every sp_xml_preparedocument call to release DOM handles.
  • Query active handles using:
  SELECT * FROM sys.dm_exec_sessions WHERE session_id = @@SPID;
  • Restart the SQL Server service if handles remain locked:
  net stop MSSQLSERVER && net start MSSQLSERVER

Step 3: Update MSXML and SQL Server Cumulative Updates

  • Navigate to Windows Update on Windows Server 2025 / Windows 11 and install any pending OS-level XML component updates.
  • Download and apply the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Verify the installed build number post-update:
  SELECT @@VERSION;

Step 4: Rebuild Affected XML Schema Collections

  • Identify schema collections tied to the failing query:
  SELECT name, xml_collection_id FROM sys.xml_schema_collections;
  • Drop and recreate any collection associated with corrupted or legacy schema definitions using CREATE XML SCHEMA COLLECTION.

Step 5: Increase Memory Allocation for XML Processing

  • Open SQL Server Management Studio (SSMS) → right-click the instance → Properties → Memory.
  • Increase the “Maximum Server Memory” value if the instance is memory-constrained, allowing sufficient buffer for large DOM tree construction.
  • Apply changes and restart the SQL Server service for the new memory configuration to take effect.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 8759 and confirm it completes without exceptions; check sys.dm_os_memory_clerks for MEMORYCLERK_XML usage to confirm stability.
  • If the error persists, bypass OPENXML/DOM-based parsing entirely and refactor the logic to use the native XML data type with .nodes() and .value() methods, which use a streaming parser instead of a full DOM load.

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

Troubleshooting Guide: SQL Server Error 8760 During Optimization Replay Long Haul Testing

Why This Error Happens

Error 8760 typically occurs when the Query Store’s Optimization Replay feature attempts to recompile a query using a captured replay script, but encounters a mismatch between the stored execution context and the current plan cache state. This is commonly caused by schema drift (statistics, indexes, or column definitions changing between capture and replay), corrupted or truncated replay script metadata in the Query Store internal tables, or insufficient permissions on the msdb and Query Store catalog views required to read historical compilation context. During long haul testing specifically, prolonged test cycles increase the likelihood of plan cache eviction or statistics auto-updates occurring mid-replay, invalidating the recompile context.

Step-by-Step Resolution Guide

Step 1: Validate Query Store Configuration and Health

  • Run SELECT * FROM sys.database_query_store_options; to confirm actual_state_desc is READ_WRITE, not READ_ONLY or ERROR.
  • Check desired_state_desc matches actual_state_desc; a mismatch often triggers 8760 during replay recompilation.
  • Execute EXEC sp_query_store_consistency_check; (new in SQL Server 2025) to detect internal corruption in replay script metadata.

Step 2: Clear and Rebuild the Replay Script Cache

  • Stop the long haul test harness before making changes.
  • Run EXEC sp_query_store_remove_plan_replay_cache; to purge stale replay script entries tied to outdated statistics.
  • Force a statistics refresh with EXEC sp_updatestats; on the target database to ensure recompiles use current cardinality data.
  • Restart the Optimization Replay session using EXEC sp_query_store_replay_workload @workload_id = <id>, @force_recompile = 1;

Step 3: Grant Required Permissions for Replay Context

  • Confirm the service account running the long haul test has VIEW SERVER STATE and VIEW DATABASE STATE permissions.
  • Grant explicit access with:
GRANT EXECUTE ON OBJECT::sys.sp_query_store_replay_workload TO [DOMAIN\ServiceAccount];
GRANT VIEW DATABASE STATE TO [DOMAIN\ServiceAccount];
  • Restart the SQL Server service (Restart-Service MSSQLSERVER in PowerShell) to apply permission changes cleanly on Windows Server 2025.

Step 4: Increase Memory Grant for Plan Cache Stability

  • Navigate to SQL Server Configuration Manager and verify max server memory leaves sufficient headroom (at least 20% of total RAM) for Query Store plan cache operations.
  • Adjust via T-SQL: EXEC sp_configure 'max server memory', <value_in_MB>; RECONFIGURE;
  • This reduces plan eviction frequency, a common trigger for 8760 during extended replay cycles.

Alternative or Verification Steps

  • Re-run the long haul test for a minimum of 2 hours and monitor Event Viewer (Applications and Services Logs > Microsoft > SQL Server) for recurrence of Event ID 8760.
  • If the error persists, fall back to exporting the workload via sp_query_store_export_workload and importing it into a fresh Query Store instance to rule out catalog corruption.

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

Troubleshooting Guide: SQL Server Error 8758 – “Get Next Node from XML DOM Node Failed”

Why This Error Happens

Error 8758 typically occurs when SQL Server’s internal XML parser (MSXML/OPENXML components) encounters a corrupted, malformed, or improperly terminated XML document during processing. This can also be triggered by an orphaned XML document handle that was not properly released via sp_xml_removedocument, causing memory corruption in the DOM tree structure. Additionally, exceeding the internal node limit or using an incompatible XML parser version registered on Windows Server 2025 can disrupt the node traversal sequence.

Step-by-Step Resolution Guide

Step 1: Validate the XML Input Source

  • Confirm the XML string passed to sp_xml_preparedocument is well-formed (properly closed tags, valid encoding).
  • Use an external validator or run SELECT CAST(@xmlVar AS XML) first to catch parsing errors before passing it to OPENXML.
  • Check for truncated XML data caused by variable length limits (e.g., using VARCHAR(8000) instead of NVARCHAR(MAX)).

Step 2: Clear Orphaned XML Document Handles

  • Explicitly call EXEC sp_xml_removedocument @hDoc; immediately after your OPENXML operations finish, even inside TRY...CATCH blocks.
  • Restart the SQL Server service to clear any lingering memory handles if multiple orphaned documents have accumulated:
  net stop MSSQLSERVER && net start MSSQLSERVER
  • Audit stored procedures for missing cleanup calls using sys.dm_exec_procedure_stats.

Step 3: Repair or Re-register MSXML Parser Components

  • On Windows Server 2025, verify the MSXML6.dll is not corrupted by re-registering it via an elevated Command Prompt:
  regsvr32 /u msxml6.dll
  regsvr32 msxml6.dll
  • Apply the latest Cumulative Update (CU) for SQL Server 2025, as XML parser bug fixes are frequently bundled in these packages.
  • Verify compatibility level of the database (SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';) is set appropriately for SQL Server 2025 features.

Step 4: Increase Node Processing Limits

  • If processing extremely large XML files, switch from OPENXML (DOM-based) to the native XML data type with .nodes() method, which uses a streaming model and avoids DOM node limits entirely.
  • Rewrite legacy queries:
  SELECT T.c.value('.', 'VARCHAR(100)') 
  FROM @xmlData.nodes('/Root/Row') AS T(c);

Alternative or Verification Steps

  • Verification: Re-run the failing stored procedure or query in SQL Server Management Studio (SSMS) and check the Messages tab for the absence of Error 8758; confirm with sys.dm_os_memory_clerks that MEMORYCLERK_XML usage has stabilized.
  • Alternative: If the error persists only on specific large datasets, bypass OPENXML entirely by importing the data using OPENJSON (if source format can be converted) or SSIS XML Source components, which do not rely on the legacy MSXML DOM parser.

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

Troubleshooting Guide: Error 8756 — Loading XML DOM from Byte Stream Failed

Why This Error Happens

Error 8756 occurs when SQL Server’s internal XML parser (MSXML) attempts to load an XML document from a binary/byte stream but encounters malformed, truncated, or improperly encoded XML data. This is commonly caused by corrupted data passed into functions like sp_xml_preparedocument, OpenXML, or XML column casting, where the byte stream does not conform to a valid XML structure. It can also result from encoding mismatches (e.g., UTF-16 vs UTF-8) or incomplete data transfers from client applications feeding XML payloads into SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Data

  • Extract the raw XML byte stream being passed into SQL Server and open it in a text/XML editor (e.g., Visual Studio Code or XML Notepad).
  • Check for truncation, missing closing tags, or invalid characters at the beginning or end of the document.
  • Run a quick validation using PowerShell: [xml](Get-Content "C:\Data\sample.xml") to confirm it parses without errors.

Step 2: Verify Encoding Consistency

  • Confirm the XML declaration header (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file or stream.
  • If the client application is sending data via ADO.NET or ODBC, ensure the connection string explicitly defines character encoding to avoid mismatches.
  • Re-save the file using UTF-8 without BOM via a text editor if encoding conflicts are suspected.

Step 3: Inspect the Stored Procedure or Query Logic

  • Review any T-SQL code using sp_xml_preparedocument, OPENXML, or CAST(... AS XML) for how the byte stream is handled.
  • Ensure the variable type used to hold the data is VARBINARY(MAX) or NVARCHAR(MAX) as appropriate, rather than a truncating fixed-length type like VARCHAR(8000).
  • Example fix:
  DECLARE @xmlData XML;
  SET @xmlData = CAST(@byteStream AS XML);

Step 4: Check for Network or Transmission Corruption

  • If the XML is being transmitted over a network (API, linked server, or file share), verify there is no packet loss or truncation during transfer.
  • On Windows Server 2025, check the Application Event Log (eventvwr.msc) for related network timeout warnings around the same timestamp as Error 8756.
  • Re-test using a local file copy to rule out network-induced corruption.

Step 5: Update SQL Server Cumulative Updates

  • Confirm SQL Server 2025 is patched to the latest Cumulative Update (CU), as XML parser bug fixes are occasionally included.
  • Check current build: SELECT @@VERSION;
  • Download and apply the latest CU from the Microsoft Update Catalog if the build is outdated.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure that triggered Error 8756 and confirm the XML loads without exception; also test with SELECT TRY_CAST(@byteStream AS XML) to catch silent failures gracefully.
  • If the error persists, bypass sp_xml_preparedocument entirely and use native XML data type methods (e.g., .nodes(), .value()) directly on a properly typed XML column, which often avoids legacy byte-stream parsing issues.

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

Troubleshooting Guide: SQL Server Error 8757 – “Get Document Element XML DOM Failed”

Why This Error Happens

Error 8757 typically occurs when SQL Server 2025 attempts to parse or process an XML document using the internal XML DOM (Document Object Model) parser, but encounters malformed, truncated, or improperly encoded XML data. This can result from corrupted input passed to functions like sp_xml_preparedocument, OPENXML, or XML data type methods, often due to invalid characters, incomplete XML structures, or mismatched encoding declarations. It can also surface when the MSXML parser component on Windows Server 2025 / Windows 11 is outdated, missing, or has conflicting registrations.

Step-by-Step Resolution Guide

Step 1: Validate the Source XML Document

  • Extract the exact XML string or file being passed into SQL Server and validate it using a tool like XML Notepad, Visual Studio, or an online XML validator.
  • Check for unclosed tags, invalid root elements, or multiple root nodes (XML DOM requires a single root element).
  • Confirm the encoding declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) matches the actual byte encoding of the file.

Step 2: Review and Correct the T-SQL XML Handling Code

  • Inspect any stored procedures or scripts using sp_xml_preparedocument, OPENXML, .query(), .value(), or .nodes() methods.
  • Ensure every call to sp_xml_preparedocument has a corresponding sp_xml_removedocument to avoid memory/handle leaks that can corrupt subsequent parsing.
  • Example fix pattern:
  DECLARE @hDoc INT;
  EXEC sp_xml_preparedocument @hDoc OUTPUT, @xmlData;
  -- processing logic here
  EXEC sp_xml_removedocument @hDoc;
  • Confirm the @xmlData variable is of type NVARCHAR(MAX) or XML, not VARCHAR, to prevent character encoding mismatches.

Step 3: Verify and Repair MSXML / System XML Components

  • On Windows Server 2025 / Windows 11, open PowerShell as Administrator and check the MSXML parser registration:
  regsvr32 /u msxml6.dll
  regsvr32 msxml6.dll
  • Run System File Checker to repair any corrupted system DLLs tied to XML parsing:
  sfc /scannow
  • Restart the SQL Server service after re-registration:
  Restart-Service -Name MSSQLSERVER -Force

Step 4: Check SQL Server Error Logs and Memory Pressure

  • Open SQL Server Management Studio (SSMS) and navigate to Management > SQL Server Logs.
  • Look for correlating memory allocation warnings around the time Error 8757 occurred, as XML DOM parsing is memory-intensive and large documents can fail under memory pressure.
  • If memory pressure is suspected, increase the max server memory setting via:
  EXEC sp_configure 'max server memory', 16384;
  RECONFIGURE;

Alternative or Verification Steps

  • Re-run the original query or stored procedure with a known-good, minimal XML sample to confirm parsing succeeds without Error 8757.
  • If the error persists, bypass the XML DOM parser entirely by switching to the native XML data type methods (.nodes(), .value()) instead of sp_xml_preparedocument/OPENXML, as these use a more modern, less error-prone parsing engine in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 8755 – Variant Type Change Failed

Why This Error Happens

Error 8755 occurs when SQL Server 2025 attempts to implicitly convert a sql_variant data type into another base type (such as int, datetime, or decimal) but encounters data that does not conform to the target type’s structure. This is frequently caused by corrupted or mismatched metadata in the underlying page allocation, or by a query attempting to force a variant comparison across incompatible collations. In some cases, this error surfaces due to a failed in-place upgrade from SQL Server 2022, where legacy sql_variant columns retain orphaned type definitions that the 2025 engine cannot resolve correctly.

Step-by-Step Resolution Guide

Step 1: Verify Database Consistency

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to check for underlying corruption in pages storing variant data.
  • Review the output for allocation errors specifically tied to the table containing the sql_variant column.

Step 2: Isolate the Offending Query or Column

  • Use SQL Server Profiler or Extended Events to capture the exact T-SQL statement triggering Error 8755.
  • Run the following diagnostic query to identify the actual base type stored within the variant column: SELECT SQL_VARIANT_PROPERTY(YourColumn, 'BaseType') AS BaseType FROM YourTable;
  • Check for NULL or unexpected mismatches between the expected schema type and the actual stored base type.

Step 3: Correct the Explicit Casting Logic

  • Modify the query to use TRY_CAST or TRY_CONVERT instead of a direct implicit conversion. Example: SELECT TRY_CONVERT(int, VariantColumn) FROM YourTable WHERE SQL_VARIANT_PROPERTY(VariantColumn, 'BaseType') = 'int';
  • This prevents the engine from throwing a hard stop error and instead returns NULL for non-convertible rows, allowing the batch to complete.

Step 4: Update the Database Engine Instance

  • Navigate to the Microsoft Update Catalog or use SQL Server Setup to check for the latest Cumulative Update (CU) for SQL Server 2025, as this is a known edge-case bug in the Variant handling module prior to CU2.
  • Apply the update via: Control Panel > Programs > SQL Server 2025 > Uninstall or change a program, selecting the “Update” path in the wizard.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query or stored procedure that threw Error 8755; if resolved, the query should return results or NULL values without halting execution.
  • Alternative Solution: If the error persists on a specific table, export the data using the bcp utility, drop and recreate the sql_variant column with explicit constraints, and re-import the data to strip out the corrupted metadata.

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

Troubleshooting Guide: SQL Server Error 8754 — XML Parser Instance Creation Failure

Why This Error Happens

Error 8754 occurs when SQL Server 2025 is unable to instantiate the MSXML or native XML parser component required to process XML data types or FOR XML/OPENXML queries. This is typically caused by missing or corrupted XML parser DLL registrations (such as msxml6.dll or the SQL-internal XML library), insufficient permissions for the SQL Server service account to access the System32 directory, or memory/resource exhaustion preventing COM object initialization. In some cases, a recent Windows Server 2025 update or security patch may have unregistered or replaced the required parser components.

Step-by-Step Resolution Guide

Step 1: Verify and Re-register the XML Parser Component

  • Open an elevated Command Prompt (Run as Administrator) on the Windows Server 2025/Windows 11 host.
  • Navigate to the System32 directory: cd C:\Windows\System32
  • Re-register the MSXML library using: regsvr32 msxml6.dll
  • Restart the SQL Server service after registration completes successfully.

Step 2: Check SQL Server Service Account Permissions

  • Open Services.msc and confirm which account the SQL Server (MSSQLSERVER or named instance) service is running under.
  • Ensure this account has Read & Execute permissions on C:\Windows\System32 and C:\Windows\SysWOW64.
  • Verify the account also has access to the SQL Server installation directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn.
  • Apply changes and restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Repair the SQL Server Installation

  • Open Control Panel > Programs > Programs and Features.
  • Select Microsoft SQL Server 2025, click Uninstall/Change, then choose Repair from the SQL Server Installation Center.
  • Allow the repair wizard to detect and restore corrupted system files, including XML parser dependencies.
  • Reboot the server once the repair process completes.

Step 4: Increase Available Memory/Resources for COM Initialization

  • Open SQL Server Management Studio (SSMS) and run sp_configure 'show advanced options', 1; RECONFIGURE;
  • Check current memory allocation using sp_configure 'max server memory (MB)';
  • If memory is heavily constrained, increase max server memory to leave adequate headroom for OS-level COM/XML parser operations.
  • Restart the SQL Server service to apply the new memory configuration.

Alternative or Verification Steps

  • Run a simple test query such as SELECT CAST('<root><test>1</test></root>' AS XML); in SSMS — if it executes without Error 8754, the parser is functioning correctly.
  • If the issue persists, check the Windows Event Viewer (Application log) for related COM or DCOM errors, and consider applying the latest Windows Server 2025 cumulative update, as parser registration issues are sometimes resolved via OS-level patches.

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

Troubleshooting Guide: SQL Server Error 8752 – “Get Single Node from XML DOM Failed”

Why This Error Happens

Error 8752 occurs when SQL Server’s XML parser (MSXML/OPENXML) is unable to retrieve a single, well-formed node from an XML document handle, typically because the underlying XML structure is malformed, the document handle has expired, or the XPath expression used targets multiple nodes instead of one. This frequently happens when the sp_xml_preparedocument handle limit has been exceeded or memory allocated for internal XML parsing has been exhausted. In Windows Server 2025 environments, this can also surface due to outdated MSXML libraries conflicting with newer .NET XML serialization standards used by SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Validate the XML Document Structure

  • Open the source XML file or variable content and check for unclosed tags, invalid characters, or mismatched namespaces.
  • Run a validation query directly in SSMS to isolate the issue:
  DECLARE @idoc INT, @doc VARCHAR(MAX);
  SET @doc = '<ROOT><Data>Test</Data></ROOT>';
  EXEC sp_xml_preparedocument @idoc OUTPUT, @doc;
  SELECT * FROM OPENXML(@idoc, '/ROOT/Data');
  EXEC sp_xml_removedocument @idoc;
  • Ensure the XPath query (e.g., .value('(/Root/Node)[1]', 'varchar(50)')) correctly points to an existing single node.

Step 2: Clear Orphaned XML Document Handles

  • Check for memory leaks caused by missing sp_xml_removedocument calls after processing.
  • Verify current handle usage via Dynamic Management Views (DMVs):
  SELECT * FROM sys.dm_exec_query_memory_grants;
  • Restart the specific SQL Server session or connection pool if handles remain locked in Windows Server 2025 Task Manager under the sqlservr.exe process details tab.

Step 3: Update MSXML and .NET Framework Dependencies

  • Navigate to Control Panel > Programs and Features on Windows 11/Server 2025 and verify the version of “Microsoft XML Core Services.”
  • If outdated, download the latest MSXML 6.0 Service Pack from the Microsoft Update Catalog.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to apply library changes.

Step 4: Reconfigure the XQuery or OPENXML Syntax

  • Modify the query to use .exist() or .value() methods instead of direct node retrieval if dealing with the native XML data type.
  • Ensure the query specifically filters for an array index [1] to force the engine to select only the first match, preventing ambiguity errors:
  SELECT @XmlData.value('(/Root/Item)[1]', 'NVARCHAR(100)');

Alternative or Verification Steps

  • Verification: Re-run the original stored procedure or query that triggered Error 8752; confirm the result set returns the expected single value without throwing a DOM exception in the SSMS “Messages” tab.
  • Alternative Fix: If the error persists, bypass the native XML parser by converting the XML data to a NVARCHAR(MAX) string and using CROSS APPLY with OPENJSON (after converting XML to JSON format) as a workaround for complex node extraction in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 8753 — “Get Multiple Nodes from XML DOM Failed”

Why This Error Happens

Error 8753 typically occurs when SQL Server’s internal XML parser (MSXML/system.xml) encounters an invalid, malformed, or unexpectedly structured XML document while attempting to execute sp_xml_preparedocument or related XML DOM functions. This often happens due to corrupted XML input data, an XML document that exceeds internal node limits, or a mismatch between the XPath/XQuery expression and the actual document structure. In some cases, memory pressure on the server causes the internal XML document cache to become unstable, leading to failed node retrieval.

Step-by-Step Resolution Guide

Step 1: Validate the XML Input Document

  • Extract the exact XML string being passed to sp_xml_preparedocument or your OPENXML/XML DOM call.
  • Validate it using a standalone XML validator or PowerShell: [xml]$test = Get-Content "C:\Temp\input.xml".
  • Check for unclosed tags, invalid encoding (ensure UTF-8 or UTF-16 declaration matches actual file encoding), and illegal characters.
  • Confirm the XML does not exceed SQL Server’s internal node limit (default cap is around 1,000 open XML documents per session if not cleared properly).

Step 2: Clear Orphaned XML Handles and Documents

  • Ensure every call to sp_xml_preparedocument has a corresponding sp_xml_removedocument call to release the handle.
  • Run the following to check for lingering handles in long-running sessions:
  DBCC FREEPROCCACHE;
  • Review stored procedures or application code for missing cleanup logic, especially inside loops or try/catch blocks that may skip the removal step on error.

Step 3: Review XPath/XQuery Syntax Against Schema

  • Compare the XPath expression used in OPENXML (e.g., /Root/Customer/Order) against the actual hierarchy of the XML document.
  • Use SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) to run a test query isolating just the .nodes() or OPENXML call.
  • Check for case-sensitivity issues or incorrect namespace prefixes, as SQL Server’s XML parser is case-sensitive by default.

Step 4: Check for Memory Pressure and Internal Resource Limits

  • Open Performance Monitor on Windows Server 2025 and monitor the SQLServer:Memory Manager\Memory Grants Pending counter.
  • Navigate to SQL Server Configuration Manager > SQL Server Services, right-click the instance, and confirm Max Server Memory is not set too restrictively under Server Properties > Memory.
  • If memory pressure is confirmed, increase max server memory (MB) via:
  EXEC sp_configure 'max server memory', 16384;
  RECONFIGURE;

Step 5: Update SQL Server 2025 Cumulative Update

  • Open SQL Server Setup and check the current build under Help > About in SSMS.
  • Download and apply the latest Cumulative Update (CU) from the Microsoft Update Catalog, as XML DOM parsing bugs are frequently patched in CUs.
  • Restart the SQL Server service via services.msc after installation.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 8753 and confirm successful execution without exceptions in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • As an alternative, migrate from OPENXML/DOM-based parsing to the native .nodes() and .value() XQuery methods on the xml data type, which are more memory-efficient and less prone to this error on SQL Server 2025.

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

Why This Error Happens

Error 8751 occurs when SQL Server’s internal XML parser (MSXML) attempts to retrieve a named node from the XML Document Object Model (DOM) but fails because the referenced item does not exist, the XML handle has become invalid, or the underlying XML document was corrupted during processing. This typically happens when sp_xml_preparedocument creates a document handle, but subsequent calls (like OPENXML) reference an XPath or node name that doesn’t match the actual schema, or the handle has already been removed via sp_xml_removedocument. In Windows Server 2025 and Windows 11 environments, this can also be triggered by outdated or corrupted MSXML parser components tied to the OS-level XML services that SQL Server 2025 depends on.

Step-by-Step Resolution Guide

Step 1: Validate the XML Document Handle Lifecycle

  • Confirm that sp_xml_preparedocument is called before any OPENXML query referencing that handle.
  • Check that sp_xml_removedocument is not called prematurely (before all queries using the handle complete).
  • Review stored procedures for handle reuse across sessions — handles are not session-persistent in SQL Server 2025.

Step 2: Verify XML Schema and Node Names

  • Run the raw XML through a validator (e.g., SELECT CAST(@xmlVar AS XML)) to confirm well-formed structure.
  • Cross-check the exact case-sensitive node/attribute names used in OPENXML WITH clauses against the actual XML payload.
  • Look for namespace mismatches — XML DOM lookups fail silently if a namespace prefix is missing from the XPath expression.

Step 3: Repair or Reinstall MSXML / SQL Native XML Components

  • Open Command Prompt as Administrator and run sfc /scannow to repair corrupted system files, including MSXML libraries.
  • Navigate to Control Panel > Programs > Programs and Features, select Microsoft SQL Server 2025, and choose Repair from the setup wizard.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or run:
  net stop MSSQLSERVER
  net start MSSQLSERVER

Step 4: Update SQL Server Cumulative Updates

  • Check for the latest Cumulative Update (CU) for SQL Server 2025 via SQL Server Setup or Microsoft Update Catalog.
  • Apply the update, as known XML DOM parsing bugs are frequently patched in CU releases.
  • Reboot the Windows Server 2025 / Windows 11 host after installation to ensure driver and library refreshes take effect.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure that triggered Error 8751 and confirm the XML node retrieval completes without exception; check SQL Server Error Logs (EXEC xp_readerrorlog) to ensure Event ID 8751 no longer appears.
  • As an alternative, replace legacy OPENXML/DOM-based parsing with native XML data type methods (.nodes(), .value(), .query()), which bypass the older MSXML DOM parser entirely and eliminate this error class.

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

Troubleshooting Guide: SQL Server Error 8749 — “Get Node Value From XML DOM Failed”

Why This Error Happens

Error 8749 in Microsoft SQL Server 2025 typically occurs when the internal XML parser (MSXML or the native SQL Server XML engine) encounters a malformed or unexpected node structure while processing OPENXML, sp_xml_preparedocument, or XML data type method calls. This is often caused by corrupted XML documents, exceeding the internal document handle memory limit, or a mismatch between the XML schema and the query attempting to extract node values. In some cases, it stems from an outdated or corrupted MSXML parser component on the underlying Windows Server 2025 / Windows 11 host.

Step-by-Step Resolution Guide

Step 1: Validate the XML Document Structure

  • Run the XML input through an external validator (e.g., xmllint or Visual Studio XML Editor) to confirm it is well-formed.
  • Check for unclosed tags, invalid characters, or encoding mismatches (UTF-8 vs UTF-16) that could cause the DOM parser to fail silently.
  • If using sp_xml_preparedocument, verify the XML variable was not truncated due to exceeding NVARCHAR(MAX) limits.

Step 2: Clear Orphaned XML Document Handles

  • Excessive unreleased DOM handles can corrupt the internal parser cache and trigger Error 8749.
  • Execute the following to release handles explicitly after use:
EXEC sp_xml_removedocument @hdoc;
  • Restart the SQL Server service to flush any lingering internal XML memory state:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 3: Repair or Reinstall MSXML Components

  • On Windows Server 2025 / Windows 11, corrupted MSXML 6.0 libraries can cause DOM parsing failures at the OS level.
  • Open an elevated PowerShell window and run:
sfc /scannow
DISM /Online /Cleanup-Image /RestoreHealth
  • Re-register the MSXML DLL manually if the above does not resolve it:
regsvr32 /u msxml6.dll
regsvr32 msxml6.dll

Step 4: Update SQL Server 2025 Cumulative Update

  • Confirm you are on the latest Cumulative Update (CU) for SQL Server 2025, as XML DOM parsing bugs are frequently patched.
  • Check current build version:
SELECT @@VERSION;
  • Download and apply the latest CU from the Microsoft Update Catalog, then restart the SQL Server instance.

Step 5: Rewrite Query to Use XML Data Type Methods

  • If the issue persists with OPENXML, migrate the logic to use native XML data type methods (.nodes(), .value(), .query()), which use a more modern and stable parsing engine.
  • Example replacement:
SELECT T.c.value('.', 'VARCHAR(100)') AS NodeValue
FROM @xmlData.nodes('/Root/Node') AS T(c);

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure against a known-good XML sample and confirm Error 8749 no longer appears in the SQL Server Error Log (Management > SQL Server Logs).
  • If the error persists, isolate the issue by testing XML parsing in a separate lightweight PowerShell/.NET script using System.Xml.XmlDocument to determine if the fault lies in the XML source itself rather than SQL Server.

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

Troubleshooting Guide: Error 8750 – “Get Attribute from XML DOM Failed”

Why This Error Happens

Error 8750 occurs when SQL Server’s internal XML parser (MSXML) attempts to retrieve an attribute from an XML document using functions like sp_xml_preparedocument or the .value()/.query() XQuery methods, but the attribute reference is invalid, malformed, or the XML handle has become corrupted in memory. This is commonly triggered by exceeding the default XML document handle memory limit, passing a null or improperly escaped XML schema, or a mismatch between the XML node path specified in the query and the actual DOM structure. In some cases, this is also caused by corrupted system CLR assemblies on Windows Server 2025 that SQL Server 2025 relies on for extended XML processing.

Step-by-Step Resolution Guide

Step 1: Validate the XML Document Structure

  • Run the raw XML payload through an external validator or SELECT CAST(@xml AS XML) to confirm it is well-formed before parsing.
  • Check for unescaped special characters (e.g., &, <, >) within attribute values, as these are a leading cause of DOM retrieval failures.
  • Ensure the XML schema collection (if used) matches the namespace defined in the incoming document.

Step 2: Clear and Reinitialize XML Document Handles

  • Open SQL Server Management Studio (SSMS) and locate the stored procedure or script using sp_xml_preparedocument.
  • Verify that every sp_xml_preparedocument call has a corresponding sp_xml_removedocument call to release the handle; add it if missing:
  EXEC sp_xml_removedocument @hDoc;
  • Restart the SQL Server service via services.msc on Windows Server 2025 to clear any orphaned memory handles currently locked by MSXML.

Step 3: Increase the XML Internal Memory Allocation

  • Navigate to Server Properties > Advanced in SSMS and check the max server memory setting to ensure SQL Server isn’t memory-starved, which can cause the DOM parser to fail silently.
  • Alternatively, run the following query to check current configuration values:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  • Default XML handle limits are capped at 128 documents per session; if your workload exceeds this, refactor the script to process XML in smaller batches.

Step 4: Repair Underlying MSXML and CLR Dependencies

  • On Windows Server 2025, open PowerShell as Administrator and run sfc /scannow to repair corrupted system files that MSXML depends on.
  • If SQL Server 2025 CLR integration is enabled, verify the assembly status using:
  SELECT * FROM sys.assemblies WHERE is_user_defined = 1;
  • Re-register the MSXML parser library by running regsvr32 msxml6.dll in an elevated Command Prompt.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or stored procedure that triggered Error 8750 and confirm the attribute value returns correctly without exception.
  • As an alternative, migrate the logic from sp_xml_preparedocument/OPENXML to native XQuery methods (.nodes(), .value()) which are generally more stable and less prone to DOM handle corruption in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 8748

Why This Error Happens

Error 8748 occurs when a T-SQL statement passes a variable, column reference, or expression to a function parameter or system procedure argument that strictly requires a literal constant value. This is common in functions like OPENROWSET, OPENQUERY, certain DBCC commands, or system stored procedures where SQL Server’s query optimizer needs to resolve the argument at parse/compile time rather than at runtime. Dynamic SQL is frequently the underlying culprit, as developers attempt to parameterize values that SQL Server’s engine has hard-coded as compile-time-only arguments.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement and Argument

  • Check the SQL Server error log or SSMS query results pane for the exact line number referenced alongside Error 8748.
  • Look specifically at functions such as OPENROWSET, OPENDATASOURCE, OPENQUERY, or extended/system stored procedures (e.g., sp_addlinkedserver) in the flagged statement.
  • Confirm which argument (%.*ls) is being passed as a variable, column, or expression instead of a hard-coded literal.

Step 2: Refactor the Query to Use Dynamic SQL

  • Instead of passing a variable directly into the restricted function parameter, construct the entire statement as a string and execute it using sp_executesql or EXEC().
  • Example pattern:
  DECLARE @sql NVARCHAR(MAX);
  DECLARE @FilePath NVARCHAR(500) = 'C:\Data\file.csv';
  SET @sql = N'SELECT * FROM OPENROWSET(BULK ''' + @FilePath + ''', SINGLE_CLOB) AS x';
  EXEC sp_executesql @sql;
  • Ensure proper escaping of single quotes and sanitize any user-supplied input to prevent SQL injection when building the dynamic string.

Step 3: Validate Linked Server and Provider Configurations

  • If the error originates from a linked server query (OPENQUERY), verify that the linked server name and query string are both passed as literals, not concatenated variables inside the native call.
  • Navigate to SQL Server Management Studio > Server Objects > Linked Servers and confirm the provider settings support the query pattern being used.
  • Re-test the query after moving all variable logic outside the native function call into the dynamic SQL wrapper from Step 2.

Step 4: Apply Latest Cumulative Update for SQL Server 2025

  • Open SQL Server Setup or check via SELECT @@VERSION; to confirm your current build number.
  • Download and apply the latest Cumulative Update (CU) from the Microsoft Update Catalog, as parser behavior around constant-only arguments is occasionally refined in servicing releases.
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after installation.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm no Error 8748 appears in the Messages tab; check sys.dm_exec_query_stats to confirm the query compiled and executed successfully.
  • If the error persists after refactoring, isolate the statement in a minimal repro script and test it against a local tempdb instance to rule out schema-specific or permission-related interference.

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

Microsoft SQL Server 2025 Error 8746 Troubleshooting Guide

Why This Error Happens

Error 8746 typically occurs when SQL Server’s query processor fails to serialize intermediate result sets while redistributing data across parallel execution threads or distributed query nodes. This is commonly caused by corrupted tempdb data files, insufficient memory grants for parallel plan execution, or version mismatches between linked servers participating in a distributed query. In some cases, outdated network drivers or TLS misconfiguration on Windows Server 2025 can also interrupt the serialization handshake between distribution nodes.

Step-by-Step Resolution Guide

Step 1: Validate and Repair Tempdb Integrity

  • Open SQL Server Management Studio (SSMS) and run DBCC CHECKDB (tempdb) WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is reported, restart the SQL Server service to force tempdb recreation, since tempdb files regenerate automatically on every service restart.
  • Confirm tempdb file paths are correct and accessible under Server Properties > Database Settings in SSMS.

Step 2: Adjust Parallelism and Memory Grant Settings

  • Open a new query window and check current configuration with EXEC sp_configure 'max degree of parallelism';
  • Temporarily lower MAXDOP to 1 for the problematic query using the query hint OPTION (MAXDOP 1) to isolate whether parallel serialization is the trigger.
  • Increase the min memory per query server configuration value if the workload is memory-starved, using sp_configure 'min memory per query (KB)', <value>;

Step 3: Verify Linked Server and Distributed Query Compatibility

  • Navigate to SSMS > Server Objects > Linked Servers and confirm all linked servers are running compatible SQL Server versions (2019 or later recommended).
  • Check the Provider Options for the linked server and ensure “Nested Queries” and “Data Access” are enabled.
  • Test connectivity manually by running EXEC sp_testlinkedserver 'YourLinkedServerName';

Step 4: Update Network and TLS Components on Windows Server 2025

  • Go to Windows Update > Advanced Options and ensure all optional driver updates for network adapters are installed.
  • Open services.msc and restart the SQL Server and SQL Server Browser services to reset any stale TLS handshake sessions.
  • Verify TLS 1.2/1.3 is enabled via HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols in the Windows Registry Editor.

Step 5: Rebuild Execution Plan Cache

  • Run DBCC FREEPROCCACHE; to clear any corrupted cached execution plans that may be causing faulty serialization logic.
  • Re-execute the original query that triggered Error 8746 to confirm whether a stale plan was the root cause.

Alternative or Verification Steps

  • Re-run the original failing query in SSMS and monitor the Messages tab; a clean execution with no Error 8746 confirms resolution.
  • If the error persists, enable Extended Events with the error_reported event filtered on Error 8746 to capture the exact query and distribution node details for deeper diagnostics with Microsoft Support.

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

Troubleshooting Guide: Error 8747 – XML_COMPRESSION Not Allowed with Clustered Columnstore Index

Why This Error Happens

This error occurs because SQL Server 2025 does not support combining the XML_COMPRESSION table option with a clustered columnstore index (CCI) on the same table. Columnstore indexes use their own internal columnar compression algorithm (row/page/columnstore archival compression), which is fundamentally incompatible with the XML-specific native compression engine. When the table schema definition attempts to apply both options simultaneously—either in a CREATE TABLE or ALTER TABLE statement—the Storage Engine rejects the DDL operation because it cannot reconcile two conflicting compression pipelines for the same data pages.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Table Definition

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the failing T-SQL script.
  • Search the script for CREATE TABLE or ALTER TABLE statements containing both CLUSTERED COLUMNSTORE INDEX and WITH (XML_COMPRESSION = ON).
  • Check sys.xml_indexes and sys.indexes via a query to confirm the current index types on the target table:
  • SELECT name, type_desc FROM sys.indexes WHERE object_id = OBJECT_ID('YourTableName');

Step 2: Choose a Single Compression Strategy

  • Decide whether the table truly requires a Clustered Columnstore Index (best for analytical/warehouse workloads) or XML compression (best for OLTP tables with large XML columns).
  • If analytics is the priority, remove the XML_COMPRESSION clause entirely and rely on the native columnstore compression, which already compresses XML data types stored as varbinary(max) internally.
  • If XML compression is mandatory, rebuild the table using a standard Clustered Rowstore Index (B-Tree) or a Heap instead of a Columnstore Index.

Step 3: Modify and Re-run the DDL Script

  • Rewrite the CREATE TABLE statement to separate the two features. Example fix for a Columnstore table:
  • CREATE TABLE dbo.YourTable (Col1 INT, XMLCol XML) WITH (DATA_COMPRESSION = COLUMNSTORE);
  • CREATE CLUSTERED COLUMNSTORE INDEX CCI_YourTable ON dbo.YourTable;
  • If keeping XML Compression, ensure the index is NOT columnstore:
  • CREATE TABLE dbo.YourTable (Col1 INT, XMLCol XML) WITH (XML_COMPRESSION = ON);
  • Execute the corrected script in a Query Window to confirm the object builds successfully.

Step 4: Restart the Deployment Pipeline (If Applicable)

  • If this error was triggered by a DACPAC deployment or a CI/CD pipeline (e.g., Azure DevOps or GitHub Actions) on Windows Server 2025, clear the build cache.
  • Navigate to the pipeline’s working directory (e.g., C:\agent_work\1\s\) and delete the stale .dacpac artifact before re-triggering the build.

Alternative or Verification Steps

  • Verification: Run sp_help 'YourTableName' in SSMS to confirm the table now shows only one compression type under the index properties, with no 8747 error in the SQL Server Logs (viewable via EventVwr.msc or SSMS Object Explorer > Management > SQL Server Logs).
  • Alternative: If the application logic strictly requires queryable, compressed XML inside a columnstore table, consider shredding the XML into relational columns within the columnstore table and storing the raw XML separately in a secondary rowstore table linked by a foreign key.

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

Troubleshooting Guide: Error 8745 — MERGE Statement Must Target a Hash Distributed Table

Why This Error Happens

This error occurs because the WHEN NOT MATCHED [BY TARGET] clause in a MERGE statement requires the target table to use hash distribution in a distributed SQL Server configuration. When the target table is instead configured with round-robin, replicated, or a different distribution scheme, the query optimizer cannot guarantee deterministic row placement for insert operations, triggering a hard failure. This typically happens after a table is created with default distribution settings or migrated from a non-distributed schema without updating the distribution policy.

Step-by-Step Resolution Guide

Step 1: Identify the Current Distribution Type of the Target Table

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to inspect the table’s distribution policy:
  SELECT distribution_policy, distribution_column 
  FROM sys.pdw_table_distribution_properties 
  WHERE object_id = OBJECT_ID('YourTargetTable');
  • Confirm whether the result shows ROUND_ROBIN, REPLICATE, or HASH. If it is not HASH, this confirms the root cause.

Step 2: Recreate the Table with Hash Distribution

  • Since distribution type cannot be altered in-place, create a new table with the correct configuration:
  CREATE TABLE dbo.YourTargetTable_New
  WITH (DISTRIBUTION = HASH(YourKeyColumn))
  AS SELECT * FROM dbo.YourTargetTable;
  • Choose a YourKeyColumn that has high cardinality (e.g., a primary key or unique ID) to ensure even data distribution across nodes.
  • Drop the old table and rename the new one to match the original name:
  DROP TABLE dbo.YourTargetTable;
  EXEC sp_rename 'dbo.YourTargetTable_New', 'YourTargetTable';

Step 3: Update Dependent Objects and Permissions

  • Re-apply any indexes, statistics, or foreign key constraints that existed on the original table, as CREATE TABLE AS SELECT (CTAS) does not carry these over automatically.
  • Re-grant table-level permissions to application service accounts, since renamed/recreated tables reset ACLs in some configurations:
  GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.YourTargetTable TO [YourServiceAccount];
  • Restart the SQL Server Agent service on Windows Server 2025 if scheduled jobs reference the old table OBJECT_ID.

Step 4: Re-run the MERGE Statement

  • Execute the original MERGE statement against the newly distributed table to confirm the WHEN NOT MATCHED [BY TARGET] clause now executes without Error 8745.
  • Monitor query execution using sys.dm_pdw_exec_requests to ensure the operation completes across all distribution nodes.

Alternative or Verification Steps

  • Verification: Re-run SELECT distribution_policy FROM sys.pdw_table_distribution_properties WHERE object_id = OBJECT_ID('YourTargetTable') and confirm the output now returns HASH.
  • Alternative: If recreating the table is not feasible due to size constraints, rewrite the MERGE logic as separate INSERT and UPDATE statements targeting a staging table with hash distribution, then reconcile results into the final table via a scheduled batch job.

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

Troubleshooting Guide: Error 8743 – TempDB Allocation Failure During Data Redistribution

Why This Error Happens

Error 8743 occurs when SQL Server 2025 attempts to redistribute data across distributions (commonly during online index rebuilds, resumable operations, or data movement in distributed/partitioned scenarios) but TempDB lacks sufficient space to complete the transfer. This typically happens because TempDB data or log files are not pre-sized correctly, autogrowth is disabled or too restrictive, or the underlying disk volume has run out of physical space. In some cases, excessive version store usage from long-running transactions or snapshot isolation can also exhaust TempDB capacity unexpectedly.

Step-by-Step Resolution Guide

Step 1: Verify Current TempDB Size and Disk Space

  • Open SQL Server Management Studio (SSMS) and run: EXEC sp_helpdb 'tempdb'; to check current file sizes.
  • Check the physical disk hosting TempDB files (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ or a custom path) using Windows File Explorer or Get-PSDrive in PowerShell.
  • Confirm the drive has at least 20–30% free space; low disk space is the most common root cause.

Step 2: Expand or Reconfigure TempDB Files

  • In SSMS, navigate to Databases > System Databases > tempdb > Properties > Files.
  • Increase the initial size of both tempdev (data) and templog (log) files manually rather than relying solely on autogrowth.
  • Set autogrowth to a fixed MB value (e.g., 512MB) instead of a percentage to avoid unpredictable growth spikes:
  ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, SIZE = 8192MB, FILEGROWTH = 512MB);
  ALTER DATABASE tempdb MODIFY FILE (NAME = templog, SIZE = 2048MB, FILEGROWTH = 512MB);
  • If multiple TempDB data files exist, ensure they are evenly sized to prevent allocation imbalance.

Step 3: Add Additional TempDB Data Files

  • If a single data file is maxing out available volume space, add a secondary TempDB file on a different disk volume:
  ALTER DATABASE tempdb 
  ADD FILE (NAME = tempdev2, FILENAME = 'D:\SQLTempDB\tempdev2.ndf', SIZE = 4096MB, FILEGROWTH = 512MB);
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (elevated) for file layout changes to take effect cleanly.

Step 4: Identify and Kill Long-Running Blocking Transactions

  • Run the following query to check for sessions consuming excessive TempDB space:
  SELECT session_id, request_id, SUM(internal_objects_alloc_page_count) AS tempdb_usage
  FROM sys.dm_db_task_space_usage
  GROUP BY session_id, request_id
  ORDER BY tempdb_usage DESC;
  • Terminate any identified runaway sessions using KILL <session_id>; after confirming they are safe to stop.

Step 5: Restart SQL Server Service and Monitor Event Viewer

  • Open Event Viewer (eventvwr.msc) on Windows Server 2025/Windows 11 and filter for Event ID 8743 under Application Logs to confirm the error has stopped recurring.
  • Restart the SQL Server (MSSQLSERVER) service to clear any stale TempDB allocation locks.

Alternative or Verification Steps

  • Re-run the original data redistribution or index rebuild operation and confirm no 8743 errors appear in the SQL Server Error Log (ERRORLOG file, typically in the MSSQL\Log directory).
  • If the error persists, consider moving TempDB entirely to a dedicated high-speed SSD volume with ample free space, as sustained I/O contention can also trigger allocation failures even when space appears technically sufficient.

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

Troubleshooting Guide: Error 8744 – REDISTRIBUTE_PREFIX Hint Join Condition Mismatch

Why This Error Happens

This error occurs when a query uses the REDISTRIBUTE_PREFIX hint on a join where the join predicate is not a simple equality comparison between two columns of directly compatible data types. SQL Server 2025’s query optimizer requires this hint to operate on equi-join conditions only, because the distribution mechanism relies on hashing matching column values across compute nodes. The error is also triggered when implicit data type conversions (such as comparing a VARCHAR column to an NVARCHAR column, or an INT to a BIGINT without explicit casting) prevent the optimizer from treating the columns as “directly comparable.”

Step-by-Step Resolution Guide

Step 1: Identify the Offending Join Condition

  • Locate the exact query referenced in the error message and find the OPTION (REDISTRIBUTE_PREFIX(...)) hint clause.
  • Review the ON clause of the join associated with that hint; confirm whether it uses = or a non-equality operator (<, >, <>, BETWEEN, LIKE).
  • Run SELECT name, system_type_id, user_type_id FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName') on both tables involved to compare data types.

Step 2: Correct Data Type Mismatches

  • If columns differ in type (e.g., INT vs BIGINT, or VARCHAR(50) vs NVARCHAR(50)), explicitly cast both sides to a matching type using CAST() or CONVERT() inside the join predicate.
  • Example fix: change ON a.CustomerID = b.CustomerID (where types differ) to ON CAST(a.CustomerID AS BIGINT) = CAST(b.CustomerID AS BIGINT).
  • Avoid relying on implicit conversions, especially between collations or Unicode/non-Unicode string types, as these are not treated as “directly comparable” by the optimizer.

Step 3: Rewrite the Join to Use a Pure Equality Predicate

  • If the original query mixes equality and inequality conditions (e.g., ON a.ID = b.ID AND a.Date > b.StartDate), separate the inequality portion into a WHERE clause or a secondary filter outside the hinted join.
  • Ensure the REDISTRIBUTE_PREFIX hint is applied only to the single equi-join column pair, not a composite condition involving ranges or non-equal operators.
  • Save and re-run the modified query in SQL Server Management Studio (SSMS) or Azure Data Studio.

Step 4: Remove or Adjust the Hint if Redistribution Isn’t Required

  • If the join genuinely cannot be expressed as a simple equality (e.g., range joins), remove the REDISTRIBUTE_PREFIX hint entirely and allow the optimizer to choose a standard join strategy.
  • Test query performance without the hint using SET STATISTICS IO, TIME ON to confirm acceptable execution plans before re-introducing any distribution hints.

Step 5: Validate Compatibility Level and Query Store Settings

  • Confirm the database compatibility level supports this hint: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName' (should be 170 or higher for SQL Server 2025 features).
  • Check Query Store (sys.query_store_query) for cached plans referencing the old hint syntax, and clear stale plans with ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE if needed.

Alternative or Verification Steps

  • Re-execute the corrected query and confirm Error 8744 no longer appears in SSMS or the Windows Event Viewer (Application log, source MSSQLSERVER).
  • As an alternative, use SET SHOWPLAN_XML ON to inspect the estimated execution plan and verify the join now shows as a Hash Match or Merge Join without optimizer warnings related to the redistribute hint.

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

Troubleshooting Guide: SQL Server Error 8742 — External Library Memory Allocation Failure

Why This Error Happens

Error 8742 occurs when a SQL Server external library component (such as an R, Python, or Java extension used by Machine Learning Services or external language runtimes) fails to allocate sufficient memory from the host operating system. This typically happens due to insufficient system memory, restrictive SQL Server memory configuration settings (like max server memory), or resource governor limits imposed on external processes (sp_execute_external_script). It can also surface when the external library runtime process has crashed or become orphaned, leaving memory handles unreleased.

Step-by-Step Resolution Guide

Step 1: Verify and Adjust SQL Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run EXEC sp_configure 'max server memory (MB)'; to check current allocation.
  • Ensure max server memory leaves at least 20-25% of total RAM free for the OS and external processes (e.g., on a 32 GB server, cap SQL Server at 24-25 GB).
  • Update using: EXEC sp_configure 'max server memory (MB)', 24576; RECONFIGURE;

Step 2: Check External Resource Governor Pool Settings

  • Navigate to Object Explorer > Management > Resource Governor in SSMS.
  • Run SELECT * FROM sys.resource_governor_external_resource_pools; to review configured limits.
  • If the external pool (default or custom) has a low max_memory_percent, increase it:
  • ALTER EXTERNAL RESOURCE POOL "default" WITH (max_memory_percent = 40); ALTER RESOURCE GOVERNOR RECONFIGURE;

Step 3: Restart the Launchpad Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server Launchpad (MSSQLSERVER) — this manages external script runtimes.
  • Right-click and select Restart to clear any orphaned memory handles from crashed R/Python sessions.
  • Confirm the service status changes to “Running” without errors in the Windows Event Viewer.

Step 4: Check Windows System-Level Memory and Page File

  • Open Task Manager > Performance > Memory to confirm available physical RAM during query execution.
  • Navigate to System Properties > Advanced > Performance Settings > Advanced > Virtual Memory.
  • Ensure the page file is set to System managed size or manually increased if physical RAM is consistently near capacity.

Step 5: Rebuild or Reinstall the External Language Extension

  • If the error persists only for a specific external library (e.g., Python’s pandas or an R package), reinstall it via:
  • CREATE EXTERNAL LIBRARY command with the updated .whl or .zip package file.
  • Alternatively, repair the Machine Learning Services feature through SQL Server Setup > Installed Features > Repair.

Alternative or Verification Steps

  • Re-run the original query or sp_execute_external_script call and monitor sys.dmosmemory_clerks filtering for MEMORYCLERK_XE or external clerks to confirm memory is being allocated correctly.
  • If the issue persists across all queries, fail over to a secondary replica (if using Always On Availability Groups) and check for memory leaks using Performance Monitor (PerfMon) counters under the “SQLServer: Memory Manager” object.

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

Troubleshooting Guide: Error 8740 – Row Too Large to Be Shuffled Between Distributions

Why This Error Happens

This error occurs in a distributed SQL Server 2025 configuration (PDW/Parallel Data Warehouse architecture or Big Data Clusters-style distributed tables) when a single row’s total byte size exceeds the maximum threshold allowed for data movement operations during a shuffle (redistribution) phase of a query. This typically happens due to wide tables containing multiple large VARCHAR(MAX), NVARCHAR(MAX), or VARBINARY(MAX) columns, or a poorly chosen distribution key that forces oversized rows to move across nodes. It can also surface after a schema change that added large fixed-length columns without revisiting the table’s distribution strategy.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Table and Row Size

  • Run DBCC SHOWCONTIG or query sys.dm_db_column_store_row_group_physical_stats to locate tables involved in the failing query.
  • Use SELECT SUM(max_length) FROM sys.columns WHERE object_id = OBJECT_ID('YourTable') to estimate the worst-case row size.
  • Cross-reference the row size reported in the error message (Row Size in Bytes: %d) against this calculation to confirm the exact table.

Step 2: Redesign the Table Schema to Reduce Row Width

  • Move large VARCHAR(MAX), NVARCHAR(MAX), or VARBINARY(MAX) columns into a separate child table with a one-to-one relationship, linked via a foreign key.
  • Apply data compression using ALTER TABLE YourTable REBUILD WITH (DATA_COMPRESSION = PAGE) to shrink the physical row footprint.
  • Avoid storing BLOB-like data inline in distributed tables; instead store a reference/path and keep binary content in Azure Blob Storage or a dedicated non-distributed table.

Step 3: Re-evaluate and Fix the Distribution Key

  • Open SQL Server Management Studio (SSMS) and inspect the table definition via sys.pdw_table_distribution_properties.
  • Choose a distribution column with high cardinality and even data spread (avoid columns tied to oversized rows triggering shuffles).
  • Recreate the table using CREATE TABLE YourTable_New WITH (DISTRIBUTION = HASH(BetterColumn)) AS SELECT * FROM YourTable; then swap tables using RENAME OBJECT.

Step 4: Apply the Latest Cumulative Update

  • Navigate to Windows Update settings or the official Microsoft Download Center to check for SQL Server 2025 Cumulative Updates (CUs) that may raise internal row-size shuffle limits or fix shuffle-engine bugs.
  • Install the update package (e.g., SQLServer2025-KB5XXXXXX-x64.exe) and restart the SQL Server service via services.msc on Windows Server 2025.
  • Confirm the patch level using SELECT @@VERSION; in a new query window.

Step 5: Rebuild Statistics and Query Plan Cache

  • Run UPDATE STATISTICS YourTable WITH FULLSCAN; to ensure the optimizer has accurate row-size estimates.
  • Clear the stale plan cache using DBCC FREEPROCCACHE; to force regeneration of the execution plan with the new schema/distribution.

Alternative or Verification Steps

  • Re-run the original failing query and monitor sys.dm_pdw_exec_requests (or equivalent dynamic management view) to confirm the shuffle operation completes without Error 8740.
  • If the error persists despite schema changes, temporarily switch the table to DISTRIBUTION = ROUND_ROBIN instead of HASH to bypass shuffle-dependent operations while you finalize a long-term schema redesign, then contact Microsoft Support with the collected row-size diagnostics for deeper engine-level investigation.

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

Why This Error Happens

Error 8741 typically occurs when SQL Server’s internal Data Movement Service (DMS) encounters a problem while shuffling data between distribution nodes during a parallel query execution, often due to network interruptions, memory pressure, or corrupted temporary files used for data exchange. This can also stem from insufficient TempDB space, antivirus software intercepting node-to-node communication, or outdated network drivers causing packet loss between distribution replicas. In clustered or Always On Availability Group configurations, a misconfigured firewall rule blocking the dynamic ports used for inter-node data transfer is a common root cause.

Step-by-Step Resolution Guide

Step 1: Verify TempDB Health and Capacity

  • Navigate to SQL Server Management Studio (SSMS) and run SELECT * FROM sys.dm_db_file_space_usage; to check TempDB space.
  • Ensure TempDB has at least 20% free space; if not, expand the data files via ALTER DATABASE tempdb MODIFY FILE.
  • Restart the SQL Server service if TempDB appears fragmented or corrupted.

Step 2: Check Network and Firewall Configuration

  • Open Windows Defender Firewall with Advanced Security on Windows Server 2025 / Windows 11.
  • Confirm that the dynamic port range (typically 49152–65535) used for SQL Server distribution communication is open for both inbound and outbound rules.
  • Run netstat -an | findstr "ESTABLISHED" to confirm active connections between distribution nodes aren’t being dropped.

Step 3: Repair or Rebuild Distribution Statistics

  • Open a query window in SSMS and execute DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption.
  • If corruption is found, run DBCC CHECKDB (YourDatabaseName, REPAIR_REBUILD); in single-user mode.
  • Update statistics on affected tables using UPDATE STATISTICS YourTable WITH FULLSCAN;.

Step 4: Update SQL Server Cumulative Updates and Drivers

  • Go to Microsoft Update Catalog and confirm you have the latest Cumulative Update (CU) for SQL Server 2025 installed.
  • Update network interface card (NIC) drivers via Device Manager on Windows Server 2025, especially if running on Hyper-V or virtualized network adapters.
  • Reboot the server and re-run the failed query to see if the data movement error persists.

Step 5: Isolate and Retry the Query

  • Break the query into smaller batches if it involves large joins or distributed transactions across multiple nodes.
  • Use SET STATISTICS IO ON; and SET STATISTICS TIME ON; to monitor execution behavior and pinpoint where the data movement fails.

Alternative or Verification Steps

  • Re-run the original query that triggered Error 8741 and confirm it completes without interruption; check SQL Server logs (Application log in Event Viewer) for any residual DMS warnings.
  • If the error persists, failover to a secondary replica (if using Always On Availability Groups) temporarily to confirm whether the issue is node-specific or database-wide.

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

Troubleshooting Guide: Error 8739 – Metadata Transfer Failure Between Distributions

Why This Error Happens

Error 8739 occurs when SQL Server 2025’s distributed query engine fails to transfer metadata between compute nodes (distributions) during query execution, typically due to network interruptions, firewall interference, or TCP port conflicts on the internal communication channel. This can also stem from corrupted temporary metadata cache files on one or more distribution nodes, or from insufficient permissions on the service account used for inter-node communication. In clustered or scale-out configurations, outdated network drivers or MTU mismatches between nodes can further compound this transfer failure.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity Between Distribution Nodes

  • Open PowerShell as Administrator and run Test-NetConnection -ComputerName <NodeName> -Port 1433 to confirm the SQL Server port is reachable.
  • Check for packet loss using ping <NodeName> -t over a sustained period.
  • Ensure Windows Firewall rules allow inbound/outbound traffic on the SQL Server communication ports (default 1433, plus any dynamic ports used for distribution traffic).

Step 2: Clear and Rebuild the Metadata Cache

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\DistCache\.
  • Stop the SQL Server service via services.msc or run Stop-Service MSSQLSERVER.
  • Delete temporary .dcache files in the DistCache folder (back them up first if needed).
  • Restart the service with Start-Service MSSQLSERVER to force a clean metadata cache rebuild.

Step 3: Validate Service Account Permissions

  • Open SQL Server Configuration Manager and confirm the service account under “SQL Server Services” has not changed or expired credentials.
  • Grant the service account explicit “Log on as a service” rights via secpol.msc > Local Policies > User Rights Assignment.
  • Ensure the account has read/write access to the shared distribution folder path used for metadata exchange.

Step 4: Check for Port Conflicts and Update Network Drivers

  • Run netstat -ano | findstr "1433" to identify any conflicting processes using the SQL Server port.
  • Update NIC drivers via Windows Update or the hardware vendor’s latest package for Windows Server 2025/Windows 11.
  • If using Hyper-V or virtual switches, confirm MTU settings match across all distribution nodes (netsh interface ipv4 show subinterfaces).

Step 5: Re-run the Distributed Query

  • Open SQL Server Management Studio (SSMS) and re-execute the failed query.
  • Monitor the SQL Server Error Log (Management > SQL Server Logs) for recurrence of Error 8739.

Alternative or Verification Steps

  • Confirm resolution by running the same distributed query 3–5 times consecutively without failure, and check Event Viewer (Windows Logs > Application) for absence of Event ID 8739.
  • If the error persists, consider isolating the problematic distribution node by temporarily removing it from the distribution group and testing query performance on the remaining nodes to identify a hardware-specific fault.

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

Troubleshooting Guide: Error 8737 in Microsoft SQL Server 2025

Why This Error Happens

Error 8737 typically occurs during distributed query execution or replication when SQL Server attempts to send data to a remote distributor over the network and the connection is interrupted. This is commonly caused by network latency, firewall rules blocking the dynamic ports used by SQL Server, or an unstable link between the publisher and distributor instances. It can also surface when the Distribution Agent encounters a corrupted packet or an authentication failure mid-transfer, causing the socket to drop unexpectedly.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity Between Instances

  • Open PowerShell as Administrator and run Test-NetConnection -ComputerName <DistributorServerName> -Port 1433 to confirm the port is reachable.
  • Check for packet loss using ping <DistributorServerName> -t over a sustained period.
  • Ensure there are no intermediate network devices (load balancers, VPNs) silently dropping long-running TCP sessions.

Step 2: Review and Adjust Firewall Rules on Windows Server 2025

  • Navigate to Windows Defender Firewall with Advanced Security on both the Publisher and Distributor servers.
  • Confirm an inbound rule exists for sqlservr.exe and for TCP port 1433 (or your custom instance port).
  • Run New-NetFirewallRule -DisplayName "SQL Server Distribution" -Direction Inbound -Protocol TCP -LocalPort 1433 -Action Allow if the rule is missing.
  • Disable any third-party antivirus network scanning temporarily to rule out interference with the SQL Server port.

Step 3: Check SQL Server Network Configuration

  • Open SQL Server Configuration Manager and expand SQL Server Network Configuration.
  • Confirm that TCP/IP is enabled for the instance under Protocols for <InstanceName>.
  • Verify the IPAll section does not have a conflicting or blank TCP Port value.
  • Restart the SQL Server service after any changes via Restart-Service -Name "MSSQLSERVER".

Step 4: Inspect the Distribution Agent Job Logs

  • Open SQL Server Management Studio (SSMS) and connect to the Distributor.
  • Navigate to Replication > Local Publications, right-click the problematic publication, and select View Synchronization Status.
  • Click View Details to capture the exact additional error string reported alongside Error 8737.
  • Increase the -HistoryVerboseLevel parameter on the Distribution Agent profile to capture more granular logging for the next failure.

Step 5: Validate Authentication and Linked Server Credentials

  • Open SSMS, expand Server Objects > Linked Servers, right-click the distributor link, and select Properties.
  • Confirm the security context under the Security page uses a valid login mapped with sufficient permissions (db_owner or equivalent on the distribution database).
  • Re-enter the password if using SQL Authentication, as credential expiration can silently break mid-transfer connections.

Alternative or Verification Steps

  • To verify the fix, manually run the replication snapshot or push a test transaction and monitor Replication Monitor for a full, uninterrupted sync without Error 8737 reappearing.
  • If the error persists, reinitialize the subscription from a fresh snapshot (Right-click Subscription > Reinitialize) to rule out a corrupted distribution database state.

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

Troubleshooting Guide: Error 8738 – Connection Failure Between Distributions

Why This Error Happens

Error 8738 occurs when SQL Server 2025’s distributed query engine fails to establish a connection between two distribution nodes, typically due to network latency, firewall restrictions, or exhausted connection pools on the Distributor or Publisher instance. This can also stem from expired or misconfigured linked server credentials, TLS/SSL handshake failures between nodes, or insufficient memory grants preventing the connection broker from allocating a new session. Additionally, corrupted distribution database metadata or stale endpoint configurations in msdb can cause the connection handshake to fail intermittently.

Step-by-Step Resolution Guide

Step 1: Verify Network Connectivity and Firewall Rules

  • Confirm that the Distributor and Subscriber servers can reach each other on the configured SQL Server port (default 1433, or custom port if changed).
  • Run Test-NetConnection -ComputerName <DistributorServer> -Port 1433 in PowerShell on Windows Server 2025/Windows 11.
  • Check Windows Defender Firewall advanced settings to ensure inbound/outbound rules allow SQL Server and SQL Server Browser services.

Step 2: Validate Distribution Database and Linked Server Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the Distributor instance.
  • Run EXEC sp_helpdistributor; to confirm the distribution database is online and properly registered.
  • Check linked server credentials via EXEC sp_helplinkedsrvlogin; and ensure the service account has not expired or been locked out in Active Directory.

Step 3: Review SQL Server Error Logs and Extended Events

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to inspect recent connection failure entries.
  • Use SSMS’s Extended Events session (system_health) to capture the exact point of failure in the connection handshake.
  • Correlate timestamps with any TLS certificate expiration or renegotiation errors.

Step 4: Increase Connection Timeout and Pool Settings

  • In SSMS, right-click the Distributor instance, go to Properties > Connections, and increase the Remote query timeout value (default 600 seconds).
  • Adjust the max worker threads and remote login timeout configuration options using sp_configure if the Distributor is handling high concurrent replication loads.
  • Restart the SQL Server Agent service after applying changes via services.msc or Restart-Service SQLSERVERAGENT.

Step 5: Rebuild or Reinitialize the Distribution Database (If Corrupted)

  • If metadata corruption is suspected, run EXEC sp_replqueuedcheck to validate replication queue integrity.
  • As a last resort, disable and reconfigure distribution using EXEC sp_dropdistributor @no_checks = 1 followed by EXEC sp_adddistributor.

Alternative or Verification Steps

  • Re-run the failing replication job or distributed query and monitor the SQL Server Agent job history to confirm Error 8738 no longer appears.
  • If the issue persists, failover to a secondary Distributor (if configured in a high-availability topology) and compare behavior to isolate whether the root cause is server-specific or network-wide.

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

Troubleshooting Guide: SQL Server Error 8735 – Online Index Build Terminated

Why This Error Happens

Error 8735 occurs when an online index creation or rebuild operation is interrupted mid-process, leaving the index in a transient inconsistent state. This is typically caused by a concurrent DDL operation, a killed session, a failover, or a resource governor timeout that terminated the background index build thread before it could commit cleanly. In SQL Server 2025 running on Windows Server 2025/Windows 11, this is often exacerbated by aggressive memory pressure policies or abrupt service interruptions during the build.

Step-by-Step Resolution Guide

Step 1: Identify the Failed Index and Current State

  • Run sp_helpindex 'YourTableName' to check whether the index exists in a disabled or partially built state.
  • Query sys.indexes and sys.dm_exec_requests to confirm no residual online build session is still active:
  SELECT name, is_disabled, is_hypothetical FROM sys.indexes WHERE object_id = OBJECT_ID('YourTableName');
  • Check the SQL Server Error Log (via SSMS or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for correlating entries around the time of failure.

Step 2: Drop and Rebuild the Affected Index

  • Manually drop the inconsistent index if it persists in a broken state:
  DROP INDEX IX_YourIndex ON dbo.YourTableName;
  • Re-create the index using the ONLINE = ON option, but add a WAIT_AT_LOW_PRIORITY clause to avoid blocking conflicts:
  CREATE NONCLUSTERED INDEX IX_YourIndex
  ON dbo.YourTableName(ColumnName)
  WITH (ONLINE = ON (WAIT_AT_LOW_PRIORITY (MAX_DURATION = 5 MINUTES, ABORT_AFTER_WAIT = SELF)));
  • Ensure no other sessions are issuing schema-modification locks (Sch-M) against the table during this window.

Step 3: Check for Resource and Service Interruptions

  • Open Event Viewer on Windows Server 2025 (eventvwr.msc) and inspect the Windows Logs > System and Application logs for unexpected SQL Server service restarts or memory-related warnings.
  • Verify the SQL Server service account has not hit memory/CPU throttling limits configured via Resource Governor:
  SELECT * FROM sys.dm_resource_governor_workload_groups;
  • Confirm Windows Update or cluster failover (if using Always On Availability Groups) did not trigger a mid-operation restart.

Step 4: Rebuild Statistics and Validate Table Consistency

  • Run DBCC CHECKTABLE('YourTableName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm there is no underlying page corruption left behind by the aborted build.
  • Update statistics post-rebuild:
  UPDATE STATISTICS dbo.YourTableName WITH FULLSCAN;

Alternative or Verification Steps

  • Re-run the original query or application transaction that triggered Error 8735 — it should now complete without interruption if the index was successfully rebuilt.
  • If the error persists, fall back to an offline rebuild (WITH (ONLINE = OFF)) during a maintenance window to bypass concurrency-related conflicts entirely, then re-enable online builds once the table is stable.

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

Troubleshooting Guide: Error 8736 – Input Parameter Cannot Be Large Object Type (VARBINARY(MAX))

Why This Error Happens

This error occurs because SQL Server 2025 does not permit large object (LOB) data types—such as VARBINARY(MAX), VARCHAR(MAX), or NVARCHAR(MAX)—to be passed as input parameters to certain system procedures, extended stored procedures, or specific built-in functions that are hard-coded to accept only fixed-length or non-MAX data types. This typically happens when a query, application, or ORM-generated call attempts to pass a MAX-type column or variable directly into a function/procedure signature that only supports legacy large object types (like IMAGE or TEXT) or fixed-size parameters. It can also surface after migrating code from an older SQL Server version where implicit conversions were more permissive.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Procedure or Function Call

  • Check the full error message in SQL Server Management Studio (SSMS) or the application log to identify which stored procedure, system function, or extended procedure triggered Error 8736.
  • Run the query in isolation using SET STATISTICS XML ON or SQL Profiler/Extended Events to capture the exact parameter and data type being passed.
  • Look for usage of system procedures like sp_OACall, CLR table-valued functions, or legacy extended stored procedures (xp_*) that do not support MAX types.

Step 2: Modify the Parameter Data Type or Casting Logic

  • Explicitly cast the parameter to a non-MAX, fixed-length type if the data size permits, for example:
  CAST(@InputParam AS VARBINARY(8000))
  • If the data genuinely exceeds 8000 bytes, refactor the logic to chunk the data into smaller segments before passing it to the procedure.
  • For CLR functions or extended procedures, update the function signature in the source code (C#/VB.NET) to accept SqlBytes or SqlBinary instead of a MAX-based parameter, then redeploy the assembly using:
  ALTER ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll'

Step 3: Update Application or ORM Layer Parameter Binding

  • In application code (e.g., ADO.NET, Entity Framework, or ODBC on Windows Server 2025/Windows 11), verify the parameter is not being auto-bound as SqlDbType.VarBinary with Size = -1 (which maps to MAX).
  • Set an explicit size limit on the parameter object:
  command.Parameters.Add("@Input", SqlDbType.VarBinary, 8000);
  • Rebuild and redeploy the application after making this change.

Step 4: Patch or Update SQL Server Components

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, as certain system procedure limitations around MAX types are refined in service packs.
  • Open SQL Server Configuration Manager on Windows Server 2025 and verify the SQL Server service is running the updated binary path after patching.
  • Restart the SQL Server service (SQL Server (MSSQLSERVER)) via services.msc or net stop/start MSSQLSERVER to apply the update.

Alternative or Verification Steps

  • Re-run the original query or application transaction and confirm Error 8736 no longer appears in the SQL Server error log (Management > SQL Server Logs in SSMS).
  • If the issue persists, use sp_helptext on the affected procedure to confirm the parameter definitions were successfully altered, and consider rewriting the logic to use Table-Valued Parameters (TVPs) instead of passing large binary data directly as a scalar input.

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

Troubleshooting Guide: Error 8734 — STRING_AGG Separator Cannot Be a Large Object Type

Why This Error Happens

This error occurs because the STRING_AGG function in SQL Server 2025 enforces a strict data type restriction on its separator parameter, which cannot accept LOB (large object) types such as VARCHAR(MAX), NVARCHAR(MAX), or TEXT. This typically happens when a developer passes a variable, column, or expression that was implicitly or explicitly declared as a MAX type directly into the separator argument. The SQL Server query optimizer rejects the query at the parsing stage because it cannot guarantee the memory allocation boundaries required for LOB data within this specific function parameter.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Variable or Column

  • Review the T-SQL query that triggered Error 8734 and locate the second parameter inside the STRING_AGG(expression, separator) function.
  • Check if you are passing a variable declared as DECLARE @Sep NVARCHAR(MAX) or pulling the separator dynamically from a table column with a MAX definition.
  • Use sp_help 'TableName' in SQL Server Management Studio (SSMS) to verify the schema definition of any column used as a separator.

Step 2: Modify the Variable Declaration

  • Change the data type declaration for the separator variable from MAX to a defined, finite length.
  • Update the code from DECLARE @Sep NVARCHAR(MAX) = ','; to DECLARE @Sep NVARCHAR(10) = ',';.
  • If using VARCHAR, ensure the limit does not exceed VARCHAR(8000), and for NVARCHAR, ensure it does not exceed NVARCHAR(4000).

Step 3: Cast Inline Expressions

  • If the separator is derived from a function or concatenation that implicitly returns a MAX type, wrap it in a CAST or CONVERT function to force a fixed length.
  • Use the syntax: STRING_AGG(Column1, CAST(YourSeparatorLogic AS NVARCHAR(10))).
  • Save the stored procedure or script and recompile the object to clear the old execution plan cache.

Step 4: Restart the Query Execution

  • Close the current query window in SSMS to clear any session-specific variable states.
  • Re-run the script using the newly defined fixed-length variable to confirm the Error 8734 message no longer appears in the Messages tab.

Alternative or Verification Steps

  • Verification: Run the query with SET STATISTICS IO ON to confirm the query executes successfully and returns the concatenated string without throwing a syntax or type-mismatch error.
  • Alternative: If you specifically require a separator longer than standard limits (which is rare), consider using the FOR XML PATH method combined with STUFF() as a legacy workaround, as this older method does not impose the same LOB restriction on the delimiter parameter.

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

Troubleshooting Guide: Error 8732 – REPLICATE/REDUCE Hints Restricted to Inner Joins

Why This Error Happens

This error occurs because the SQL Server Query Optimizer only supports the REPLICATE and REDUCE join hints when used in conjunction with INNER JOIN syntax. When a query attempts to apply these specific hints to an OUTER JOIN (LEFT, RIGHT, or FULL) or a CROSS JOIN, the optimizer rejects the execution plan because it cannot guarantee referential integrity for the distribution method requested. Essentially, this is a syntax validation error in the T-SQL code rather than a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Locate the specific stored procedure or ad-hoc query logged in the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) associated with Event ID 8732.
  • Isolate the JOIN clause containing the OPTION (REPLICATE) or OPTION (REDUCE) hint.

Step 2: Modify the Join Type in the Query

  • Review the business logic to determine if an INNER JOIN is actually sufficient for the required result set.
  • Change the join keyword from LEFT JOIN, RIGHT JOIN, or FULL OUTER JOIN to INNER JOIN if the data relationship allows it.
  • Example correction:
  -- Incorrect (Causes Error 8732)
  SELECT * FROM TableA LEFT JOIN TableB ON TableA.ID = TableB.ID OPTION (REPLICATE)

  -- Corrected
  SELECT * FROM TableA INNER JOIN TableB ON TableA.ID = TableB.ID OPTION (REPLICATE)

Step 3: Remove the Hint if Join Type is Mandatory

  • If the business logic strictly requires an OUTER JOIN (e.g., you need to keep non-matching rows from the left table), you cannot use REPLICATE or REDUCE.
  • Delete the OPTION (REPLICATE) or OPTION (REDUCE) clause entirely from the query string.
  • Allow the Query Optimizer to select the default distribution strategy (such as SHUFFLE) for the outer join automatically.

Step 4: Validate Query Syntax Locally

  • Run the modified query in a test environment using SET SHOWPLAN_XML ON to verify the execution plan compiles without errors before deploying to production.
  • Check for any nested subqueries that might also contain conflicting join hints.

Alternative or Verification Steps

  • Verification: Re-run the original query in SSMS. If the query executes successfully and returns the Actual Execution Plan without throwing Error 8732, the fix is confirmed.
  • Alternative: If performance was the reason for using REPLICATE (to optimize small table broadcasts), consider using the HASH JOIN or MERGE JOIN hint instead, as these are compatible with both inner and outer join types.

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

Troubleshooting Guide: SQL Server Error 8733 — STRING_AGG Separator Parameter Issue

Why This Error Happens

This error occurs because the STRING_AGG function in SQL Server 2025 strictly requires its separator parameter to be a constant string literal (e.g., ',') or a declared variable of a string type. When a column reference, expression, or non-string data type is passed as the separator, the query optimizer cannot resolve it at compile time, triggering Error 8733. This is commonly caused by dynamically generated SQL, implicit conversions from non-string columns, or legacy code migrated from older T-SQL patterns that allowed more flexible parameter binding.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact query referenced in the error log.
  • Check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full stack trace tied to Event ID 8733.
  • Look specifically for STRING_AGG(column, separator) calls where the separator is not wrapped in single quotes.

Step 2: Correct the Separator Syntax

  • Replace any column-based or computed separator with a literal string, for example:
    STRING_AGG(Name, ', ')
  • If the separator must be dynamic, declare a variable first:
  DECLARE @sep NVARCHAR(5) = ', ';
  SELECT STRING_AGG(Name, @sep) FROM dbo.Employees;
  • Ensure the variable is explicitly typed as VARCHAR, NVARCHAR, CHAR, or NCHAR — numeric or date types will still throw the error.

Step 3: Rebuild Dynamic SQL Safely

  • If the query is generated via dynamic SQL (EXEC sp_executesql), confirm the separator is concatenated as a quoted literal before execution, not passed as a raw parameter placeholder.
  • Use QUOTENAME() or manual string escaping to avoid injection risks when building the separator dynamically.

Step 4: Update Application-Side Code

  • If the query originates from an application (e.g., .NET, Python, or a reporting tool on Windows Server 2025), check the data access layer for parameterized queries that bind the separator as a SQL parameter object instead of inlining it.
  • Modify the ORM or query builder configuration to hardcode the separator string directly into the T-SQL command text.

Alternative or Verification Steps

  • Run the corrected query in isolation via SSMS and confirm it executes without raising Error 8733 in the Messages tab.
  • If the issue persists, review compatibility level using SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'; and ensure it’s set to 170 (SQL Server 2025) via ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 170; to guarantee full STRING_AGG feature support.

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

Troubleshooting Guide: SQL Server Error 8731 (REDISTRIBUTE/REDUCE Hint Join Condition Mismatch)

Why This Error Happens

This error occurs when a query uses the REDISTRIBUTE or REDUCE hints on a join, but the query optimizer cannot find a valid equality-based join condition to use for the operation. These hints, introduced for scale-out and parallel data movement optimization in SQL Server 2025, strictly require the first predicate in the ON clause to be a direct equality comparison (=) between two columns of identical or implicitly comparable data types. If the join uses inequality operators (like >, <, or <>), non-column expressions, or columns with mismatched/incompatible data types (e.g., comparing an NVARCHAR to an INT without explicit casting), the engine throws Error 8731 because it cannot physically redistribute the data across nodes based on an undefined key.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Join Clause

  • Open the query that triggered Error 8731 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate the specific JOIN statement that contains the OPTION (REDISTRIBUTE) or OPTION (REDUCE) hint.
  • Check the ON clause immediately following the join keyword; this is strictly validated by the optimizer.

Step 2: Verify and Reorder the Equality Predicate

  • Ensure the very first condition listed in the ON clause is a strict equality (=) comparison.
  • If your query currently looks like ON a.Date > b.Date AND a.ID = b.ID, move the equality check to the front: ON a.ID = b.ID AND a.Date > b.Date.
  • Remove any leading functions (e.g., ON ISNULL(a.ID, 0) = b.ID) as functions wrapping the column may prevent the optimizer from recognizing a “direct” comparison.

Step 3: Align Data Types Explicitly

  • Check the schema definitions for the two columns involved in the join using sp_help 'TableName' for both tables.
  • If data types differ (e.g., INT vs. BIGINT, or different collations for string types), insert an explicit CAST or CONVERT function to align them before the comparison.
  • Example fix: Change ON a.UserID = b.UserCode to ON CAST(a.UserID AS VARCHAR(50)) = b.UserCode if the types do not match natively.

Step 4: Simplify Complex Join Logic

  • If the join involves multiple tables or complex OR logic within the ON clause, isolate the equality join into a dedicated Common Table Expression (CTE) or subquery.
  • Apply the REDISTRIBUTE hint to the simplified, isolated join rather than the complex multi-table merge.

Alternative or Verification Steps

  • Verify the Fix: Re-run the query with SET SHOWPLAN_XML ON to confirm the engine accepts the hint and generates a valid execution plan without throwing Error 8731.
  • Alternative Solution: If the data types cannot be structurally aligned (e.g., legacy schema constraints), remove the REDISTRIBUTE/REDUCE hint entirely and allow the SQL Server 2025 query optimizer to automatically select the best distribution strategy based on the existing statistics.

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

Troubleshooting Guide: SQL Server Error 8729

Why This Error Happens

Error 8729 occurs when a window function’s ORDER BY clause within a RANGE frame specification exceeds SQL Server’s internal size limit for sorting metadata, typically because the combined byte size of the columns used in the ORDER BY list (especially with wide data types like VARCHAR(MAX), NVARCHAR(MAX), or multiple concatenated columns) surpasses the engine’s supported threshold. This is not a permissions or connectivity issue but a query design limitation tied to how SQL Server allocates memory for computing range-based frame boundaries. It most commonly surfaces after upgrading queries or databases to SQL Server 2025, where stricter validation of window frame memory allocation has been introduced compared to legacy versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement from the application log or SQL Server error log (Event ID 8729).
  • Use SQL Server Management Studio (SSMS) 21 or Azure Data Studio to run the query in isolation and confirm the error is reproducible.
  • Check the ORDER BY clause inside the OVER() clause for data type width (e.g., OVER (ORDER BY LargeTextColumn RANGE BETWEEN ...)).

Step 2: Reduce the ORDER BY Footprint

  • Replace wide columns (VARCHAR(MAX), NVARCHAR(MAX), XML, VARBINARY(MAX)) in the ORDER BY list with smaller surrogate keys (e.g., INT, BIGINT, or a hashed/truncated value).
  • If multiple columns are concatenated for ordering, reduce the number of columns or pre-compute a smaller composite key column and index it.
  • Example fix:
  ALTER TABLE dbo.Orders ADD OrderRankKey AS CONVERT(BIGINT, OrderDate) PERSISTED;

Step 3: Switch RANGE to ROWS Where Possible

  • If the business logic allows, change RANGE BETWEEN to ROWS BETWEEN in the window frame definition, since ROWS does not require the same byte-size validation on the ORDER BY list.
  • Validate that ROWS-based framing still produces the correct aggregation/ranking result for your use case.

Step 4: Apply Latest Cumulative Update (CU)

  • Navigate to Microsoft Update Catalog and confirm you have the latest SQL Server 2025 Cumulative Update installed, as early builds have tighter internal buffer limits that were later adjusted.
  • Check current build via:
  SELECT @@VERSION;
  • Install the CU via Windows Server 2025 Server Manager > Windows Update, or manually via the downloaded .exe patch.

Step 5: Rebuild Statistics and Indexes

  • After modifying the query or schema, run:
  EXEC sp_updatestats;
  ALTER INDEX ALL ON dbo.Orders REBUILD;
  • This ensures the query optimizer recalculates proper memory grant estimates against the new, smaller ORDER BY key.

Alternative or Verification Steps

  • Re-run the original query (or its modified version) and confirm Error 8729 no longer appears in SSMS or the SQL Server Error Log (Management > SQL Server Logs).
  • If the error persists, as a workaround, decompose the window function into a temp table with a pre-sorted, narrow key column, then apply the OVER() clause against that staged table instead of the original wide-column source.

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

Troubleshooting Guide: Error 8730 — “Offset Parameter for LAG/LEAD Functions Cannot Be a Negative Value”

Why This Error Happens

Error 8730 occurs in SQL Server 2025 when a T-SQL query uses the LAG() or LEAD() window function with an offset argument that evaluates to a negative integer. This is a syntax/logic validation error rather than a configuration or permissions issue — SQL Server’s query parser strictly enforces that the offset parameter must be a non-negative integer literal, variable, or expression. The error typically surfaces after a code migration, a dynamically calculated offset value, or a copy-paste mistake where a subtraction operator was unintentionally applied to the offset argument.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing statement from SSMS, Azure Data Studio, or the application’s query log.
  • Check SQL Server error logs (Event Viewer > Applications and Services Logs > MSSQLSERVER) for the associated Event ID 8730 timestamp to correlate with the executing session.
  • Run SELECT * FROM sys.dm_exec_query_stats cross-referenced with sys.dm_exec_sql_text() to pull the exact query text if the source isn’t immediately available.

Step 2: Inspect and Correct the Offset Expression

  • Locate the second parameter in the LAG(column, offset, default) or LEAD(column, offset, default) call.
  • Verify whether the offset is a hard-coded literal (e.g., LAG(SalesAmount, -1)) — remove the negative sign if present.
  • If the offset is a variable (e.g., DECLARE @Offset INT = -2;), trace its source and ensure any calculation logic (such as @RowNum - @CurrentRow) cannot produce a negative result.
  • Add a validation guard using ABS(@Offset) or a CASE statement to force non-negative values before passing them into the function.

Step 3: Patch Application-Side Parameter Binding

  • If the offset is passed from an application (C#, Python, Power BI, SSRS, etc.), check the parameterized query or ORM mapping (Entity Framework, Dapper) for incorrect sign handling.
  • Update the application logic to validate offsets server-side or client-side before sending the query to SQL Server 2025.
  • Re-deploy the stored procedure or application build after the fix using sqlcmd -S <ServerName> -i FixedScript.sql or through your standard CI/CD pipeline.

Step 4: Test in a Non-Production Environment

  • Execute the corrected query against a Windows 11 or Windows Server 2025 test instance using SSMS.
  • Confirm the query returns expected row-shifted results without throwing Error 8730.

Alternative or Verification Steps

  • Re-run the query with SET SHOWPLAN_TEXT ON to confirm the execution plan compiles successfully without raising the offset validation error.
  • If the negative offset is intentional (e.g., you want “look backward” behavior from LEAD), simply swap LEAD() for LAG() (or vice versa) with a positive offset instead, since both functions are logical mirrors of each other.

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

Why This Error Happens

Error 8728 occurs when a window function uses a RANGE frame specification (either explicitly or by default) while the ORDER BY clause references a column of a Large Object (LOB) data type, such as VARCHAR(MAX), NVARCHAR(MAX), VARBINARY(MAX), XML, or TEXT/NTEXT/IMAGE. SQL Server’s query optimizer cannot logically compare and bound LOB values within a RANGE frame because these types do not have a fixed, comparable numeric or date boundary. This is a query design limitation rather than a server configuration or permissions issue, and it will persist regardless of indexing or hardware until the T-SQL syntax is corrected.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement that triggered Error 8728 from SQL Server Management Studio (SSMS) or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • Look specifically for OVER (ORDER BY ... RANGE BETWEEN ...) clauses in the query text.
  • Confirm the data type of the column in the ORDER BY list using sp_help 'YourTableName' or by checking sys.columns.

Step 2: Replace RANGE with ROWS

  • Since ROWS frames do not require logical value-based comparisons, switch the window frame type from RANGE to ROWS.
  • Example fix:
  SELECT OrderID, OrderNotes,
         SUM(Amount) OVER (ORDER BY OrderDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
  FROM Orders;
  • Ensure the business logic (e.g., ties handling) remains valid, as ROWS evaluates physical row position rather than value-based ranges.

Step 3: Cast or Remove the LOB Column from ORDER BY

  • If the ORDER BY column itself must remain a LOB type, cast it to a bounded type (e.g., CAST(column AS VARCHAR(8000))) only if truncation risk is acceptable.
  • Alternatively, restructure the query to sort by a separate non-LOB column (such as OrderDate or an INT surrogate key) instead of the LOB field.
  • Avoid casting large XML or MAX-type fields directly into the ORDER BY of a windowed aggregate function.

Step 4: Validate Against SQL Server 2025 Compatibility Level

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'; to confirm the database compatibility level.
  • If the database was upgraded from an older SQL Server version, confirm that legacy query patterns using implicit RANGE defaults are updated to explicit ROWS syntax for consistency with SQL Server 2025 engine behavior.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS or Azure Data Studio and confirm Error 8728 no longer appears in the Messages tab.
  • As an alternative, wrap the window function in a Common Table Expression (CTE) that pre-selects and casts the LOB column to a non-LOB type before applying the OVER() clause, then verify the execution plan shows no window spool errors.

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

Troubleshooting Guide: SQL Server Error 8726

Why This Error Happens

This error occurs when a T-SQL statement passes a variable, expression, or column reference to a system function parameter that strictly requires a literal constant value at compile time. SQL Server 2025’s query optimizer cannot resolve certain function arguments—such as those used in OPENROWSET, DATEADD with dynamic intervals, or specific metadata functions—dynamically because the execution plan is cached based on a fixed input. This typically surfaces after migrating legacy dynamic SQL scripts or ORM-generated queries to Windows Server 2025 environments where stricter parameterization rules are enforced by default.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Function

  • Capture the exact query from SQL Server Management Studio (SSMS) error output or the Windows Event Viewer under Applications and Services Logs > SQL Server.
  • Note the specific function name referenced in the %.*ls placeholder (common culprits: DATEPART, OPENROWSET, PARSENAME).
  • Run SELECT * FROM sys.messages WHERE message_id = 8726; to confirm the exact wording and severity level for your SQL Server 2025 build.

Step 2: Replace Variables with Hardcoded Literals

  • Locate the parameter being passed as a variable, e.g., DECLARE @part INT = 2; SELECT DATEPART(@part, GETDATE());.
  • Rewrite the call using a direct constant: SELECT DATEPART(month, GETDATE());.
  • If dynamic behavior is required, wrap the entire statement in EXEC (@sql_string) or use sp_executesql to build the query as a string before execution rather than passing a variable into the restricted parameter slot.

Step 3: Rebuild Dynamic SQL Using sp_executesql

  • Open the stored procedure or script in SSMS and isolate the dynamic logic.
  • Construct the query as an NVARCHAR(MAX) string, concatenating the “constant” value directly into the string literal rather than passing it as a bound parameter.
  • Example:
  SET @sql = N'SELECT DATEPART(' + @part_name + N', GetDate())';
  EXEC sp_executesql @sql;
  • Validate the string output by printing @sql before execution to ensure no syntax errors are introduced.

Step 4: Update Application Connection Strings and ORM Mappings

  • If the query originates from an application (e.g., Entity Framework or a .NET 9 app on Windows 11), check the appsettings.json or web.config for Command Timeout and parameterization settings.
  • Disable automatic parameterization for the specific stored procedure call by using OPTION (RECOMPILE) at the end of the query to force the optimizer to treat inputs as sniffed constants.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear any cached bad execution plans.

Alternative or Verification Steps

  • Verify the fix by running the corrected query in SSMS with Include Actual Execution Plan enabled; the absence of Error 8726 and a successful green checkmark confirms resolution.
  • If the error persists in a stored procedure, use sp_recompile 'YourProcName'; to clear the plan cache for that specific object and force SQL Server to re-evaluate the constant requirement on the next execution.

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

Troubleshooting Guide: SQL Server Error 8727 — “Input Parameter of Percentile Function is Outside of Range [0, 1]”

Why This Error Happens

This error occurs when the PERCENTILE_CONT or PERCENTILE_DISC function receives a numeric argument that falls outside the mathematically valid range of 0 to 1, inclusive. This is typically caused by a coding mistake where a percentage value (e.g., 95) is passed instead of its decimal equivalent (e.g., 0.95), or by a dynamic variable/column that is not properly validated before being passed into the function. It can also surface when upstream ETL processes or application layers pass NULL-converted or miscalculated values into the query at runtime.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Check SQL Server 2025 Query Store or the Activity Monitor on Windows Server 2025 to identify the exact statement that triggered Error 8727.
  • Search your codebase or stored procedures for PERCENTILE_CONT or PERCENTILE_DISC usage.
  • Run the query manually in SQL Server Management Studio (SSMS) to reproduce the error with the exact parameter values.

Step 2: Correct the Parameter Value

  • Ensure the argument is expressed as a decimal between 0 and 1 (e.g., 0.75 for the 75th percentile, not 75).
  • If the value is sourced from a variable, add explicit casting:
  DECLARE @p FLOAT = 0.90;
  SELECT PERCENTILE_CONT(@p) WITHIN GROUP (ORDER BY SalesAmount) OVER() FROM Sales;
  • If the value comes from user input or an application (e.g., a .NET or Power BI front end), add server-side validation logic to clamp or reject values outside [0,1].

Step 3: Add Defensive Validation Logic

  • Wrap the percentile calculation in a CASE statement or precondition check to prevent invalid values from reaching the function:
  IF @p NOT BETWEEN 0 AND 1
      THROW 50001, 'Percentile value must be between 0 and 1.', 1;
  • If values are pulled from a configuration table, audit that table for data entry errors (e.g., percentages stored as whole numbers).

Step 4: Check for ETL or Integration Issues

  • If this error appears intermittently, inspect SSIS packages, Azure Data Factory pipelines, or third-party reporting tools feeding data into SQL Server 2025.
  • Confirm that any percentage-to-decimal conversion logic (e.g., dividing by 100) is correctly applied before the value reaches the stored procedure.

Step 5: Update and Patch SQL Server

  • Confirm SQL Server 2025 is fully patched via Windows Update or SQL Server Setup, as occasional parser-level bugs with window functions have been addressed in cumulative updates.
  • Restart the SQL Server service after patching:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the original query with a known valid value (e.g., 0.5) to confirm the function executes without Error 8727, then gradually reintroduce dynamic inputs to isolate the faulty source.
  • As an alternative, use TRY_CONVERT or TRY_CAST when passing external parameters into the percentile function to gracefully handle malformed input instead of throwing a hard error.

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

Troubleshooting Guide: SQL Server Error 8725 — Subproc Thread Aborted During Parallel Query Execution

Why This Error Happens

Error 8725 typically occurs when a worker thread participating in a parallel query execution plan is unexpectedly terminated, often due to memory pressure, thread pool exhaustion, or an underlying I/O exception on a subordinate thread. This can be triggered by corrupted execution context data passed between parallel threads, insufficient max worker threads configuration, or a mismatch between the degree of parallelism (DOP) requested and the resources available on the host. In some cases, outdated or corrupted SQL Server binaries/drivers on Windows Server 2025 or Windows 11 can also cause threads to abort mid-execution rather than completing gracefully.

Step-by-Step Resolution Guide

Step 1: Verify Max Degree of Parallelism (MAXDOP) Settings

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to check current configuration:
  EXEC sp_configure 'max degree of parallelism';
  • If the value is set too high relative to available logical CPUs, lower it:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max degree of parallelism', 4;
  RECONFIGURE;

Step 2: Increase Worker Thread Pool and Check Memory Pressure

  • Navigate to SQL Server Configuration Manager > SQL Server Services and confirm the service account has sufficient memory quota.
  • Check current worker thread configuration:
  EXEC sp_configure 'max worker threads';
  • Increase if the default (0 = auto-configured) is insufficient for your workload, especially on high-core-count Windows Server 2025 machines.
  • Monitor via Performance Monitor (PerfMon) using the SQLServer:Buffer Manager and Sign Waits counters to rule out memory starvation.

Step 3: Repair or Update SQL Server Binaries

  • Open Control Panel > Programs > Programs and Features, locate “Microsoft SQL Server 2025”, and select Change/Repair.
  • Alternatively, run the repair tool directly from the installation media:
  setup.exe /ACTION=REPAIR /INSTANCENAME=MSSQLSERVER
  • Ensure the latest Cumulative Update (CU) for SQL Server 2025 is applied, as parallel execution bugs are frequently patched in CUs.

Step 4: Review SQL Server Error Log and Windows Event Viewer

  • Open C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG and search for entries immediately preceding Error 8725.
  • Cross-reference with Windows Event Viewer > Windows Logs > Application for any correlating .NET Runtime or Kernel-Power events that might indicate an OS-level thread interruption.
  • Note any associated Process IDs (PIDs) or Query Hashes for targeted query tuning.

Alternative or Verification Steps

  • Re-run the previously failing parallel query using OPTION (MAXDOP 1) as a temporary workaround to confirm the query itself completes successfully in serial mode.
  • If the error persists, enable Trace Flag 8675 temporarily to force serial execution for diagnostic purposes, then re-enable parallelism after validating hardware/memory health via DBCC CHECKDB and Windows Memory Diagnostic.

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

Troubleshooting Guide: SQL Server Error 8723 — “Object Specified in TABLE HINT Clause”

Why This Error Happens

This error occurs when a query uses a table hint (such as WITH (INDEX(...)), FORCESEEK, or NOLOCK) that references a table or view alias incorrectly, or when the specified index name inside the hint does not exist on that object. It commonly arises after a schema change, index rebuild with a renamed index, or when a query was copied from another environment where the underlying table structure differs. SQL Server 2025’s stricter parser validation also flags hints applied to views or synonyms that do not support the specified hint type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Object

  • Capture the exact query text from the application log or SQL Server error log (look for Error 8723 in Event Viewer under Applications and Services Logs > MSSQLSERVER).
  • Locate the table alias referenced in the TABLE HINT or WITH (...) clause.
  • Run sp_helpindex 'YourTableName' in SQL Server Management Studio (SSMS) to confirm valid index names.

Step 2: Correct the Table Hint Syntax

  • Open the query in SSMS and verify the hint matches the actual object name, not an alias.
  • Incorrect: SELECT * FROM Sales AS S WITH (INDEX(S))
  • Correct: SELECT * FROM Sales AS S WITH (INDEX(IX_Sales_CustomerID))
  • If the index was renamed or dropped during maintenance, update the hint to reference the current index name.
  • Remove hints referencing views or synonyms, since Table Hints only work reliably on base tables in SQL Server 2025.

Step 3: Validate Index Existence and Rebuild if Necessary

  • Open SQL Server Management Studio (SSMS 21) and navigate to:
  • Databases > [YourDB] > Tables > [YourTable] > Indexes
  • Confirm the index name referenced in the hint still exists; if missing, recreate it:
  CREATE NONCLUSTERED INDEX IX_Sales_CustomerID 
  ON dbo.Sales (CustomerID);
  • If indexes were recently rebuilt with DROP_EXISTING = ON under a new name, update all stored procedures and application queries referencing the old name.

Step 4: Clear Cached Execution Plans

  • Since SQL Server may cache an old plan referencing the invalid hint, clear it using:
  DBCC FREEPROCCACHE;
  • Alternatively, clear cache for a specific database:
  ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025 if caching issues persist.

Alternative or Verification Steps

  • Re-run the original query in SSMS; if Error 8723 no longer appears and the execution plan shows the intended index being used (check via Include Actual Execution Plan), the fix is confirmed.
  • As an alternative, remove the explicit table hint entirely and allow the Query Optimizer to select the best index automatically—this bypasses the error while SQL Server 2025’s improved cardinality estimator handles index selection.

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

Troubleshooting Guide: Error 8724 in Microsoft SQL Server 2025

Why This Error Happens

Error 8724 occurs when a query attempts to apply a TABLE HINT (such as INDEX, FORCESEEK, or NOLOCK) directly to a table-valued function or an OPENROWSET result set. SQL Server’s query engine does not support hinting against these dynamic row-generating constructs because they do not have the static physical structure (indexes, partitions) that table hints require. This is a syntax/logic limitation in the T-SQL parser rather than a permissions or connectivity issue, meaning it will occur regardless of the underlying Windows Server 2025 or Windows 11 configuration.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Syntax

  • Open SQL Server Management Studio (SSMS) and locate the exact line referenced in the error output.
  • Look specifically for WITH (INDEX(...)), WITH (NOLOCK), or WITH (FORCESEEK) attached immediately after a function call like OPENROWSET(...) or a user-defined Table-Valued Function (TVF).
  • Confirm the object type by running sp_helptext on the function name if it is a TVF (e.g., SELECT * FROM dbo.GetUserData() WITH (NOLOCK)).

Step 2: Remove or Relocate the Table Hint

  • Edit the T-SQL script to strip the hint directly from the function call. For example, change SELECT * FROM dbo.MyFunction() WITH (NOLOCK) to SELECT * FROM dbo.MyFunction().
  • If the isolation level behavior (like dirty reads) is required, move the hint to the session level using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; before the query runs instead of inline hinting.
  • Save the script and re-run it via sqlcmd or SSMS to check for immediate parser acceptance.

Step 3: Refactor Using a Temporary Table or CTE

  • If filtering or indexing logic is strictly required, insert the results of the TVF/OPENROWSET into a temporary table first.
  • Use the syntax: SELECT * INTO #TempResults FROM dbo.MyFunction(); followed by SELECT * FROM #TempResults WITH (INDEX(ix_name));.
  • Apply the required table hints to the #TempResults temporary table instead of the original function.

Step 4: Update Linked Server Configurations (For OPENROWSET Specific Errors)

  • Navigate to Object Explorer > Server Objects > Linked Servers in SSMS if the error originates from a distributed query.
  • Right-click the specific linked server and select Properties to verify that “Collation Compatible” and “Data Access” settings are correctly configured, as misconfigured external sources sometimes force manual (and invalid) hinting attempts to manage locking.
  • Ensure the application connection string does not programmatically inject hints into dynamic SQL involving OPENROWSET.

Alternative or Verification Steps

  • Verification: Execute the modified query using SET STATISTICS IO ON; to confirm the query processes successfully and returns the expected row count without the 8724 error.
  • Alternative Fix: If refactoring is not immediately possible, wrap the function call inside a standard View (CREATE VIEW) and apply the necessary hints to the view reference in the outer query instead of the raw function.

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

Troubleshooting Guide: Error 8722 — Semantic Affecting Hint Mismatch in SQL Server 2025

Why This Error Happens

This error occurs when a query uses the OPTION (TABLE HINTS...) clause to apply plan-affecting hints, but the hints specified there do not exactly match the semantic hints declared in the table’s WITH clause. SQL Server 2025 enforces strict validation between these two clauses because mismatched semantic hints (such as NOLOCK, READPAST, SERIALIZABLE, or FORCESEEK) can silently alter query results or locking behavior in unintended ways. This is typically caused by manually edited query hints, auto-generated query plans from third-party tools, or copy-pasted T-SQL where the WITH clause and the OPTION clause were updated independently of one another.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Hint

  • Open the failed query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact object name referenced in the error message (Error 8722 includes the table/view name and the mismatched hint).
  • Run the query with SET SHOWPLAN_TEXT ON or review the error details pane to capture the full text of the %.*ls placeholders, which reveal the specific hint and clause causing the conflict.

Step 2: Compare the WITH Clause and OPTION (TABLE HINTS) Clause

  • Locate the WITH (HINT1, HINT2, ...) clause directly after the table alias in the FROM section of the query.
  • Locate the corresponding OPTION (TABLE HINT(TableAlias, HINT1, HINT2, ...)) clause at the end of the query.
  • Manually line up both hint lists side-by-side to confirm they contain identical semantic hints (order does not matter, but presence/absence does).

Step 3: Synchronize the Hints

  • Add any missing semantic hint to whichever clause is incomplete — if WITH (NOLOCK) exists but OPTION (TABLE HINT(t, NOLOCK)) does not include NOLOCK, add it there.
  • Alternatively, remove the hint entirely from both clauses if it was unintentionally introduced by a query generator or ORM (e.g., Entity Framework, Hibernate).
  • Save the corrected query script to a local .sql file before re-running it, in case further edits are needed.

Step 4: Re-Execute and Validate the Query

  • Run the corrected query in SSMS against a non-production database first.
  • Confirm Error 8722 no longer appears in the Messages tab.
  • Check the Execution Plan tab to ensure the intended locking/isolation behavior (e.g., NOLOCK scan) is actually being applied as expected.

Step 5: Audit Related Stored Procedures and Views

  • Use sp_helptext or query sys.sql_modules to search for other stored procedures, views, or functions that may contain the same hint mismatch pattern.
  • Run a search across your codebase (SSDT project, Git repo, or deployment scripts) for OPTION (TABLE HINT to catch any other instances before they fail in production.

Alternative or Verification Steps

  • Verification: Re-run the query with SET STATISTICS PROFILE ON and confirm the actual execution plan reflects the intended hint (e.g., check for a Lock Hints property matching NOLOCK or READPAST in the plan XML).
  • Alternative: If the hints are not strictly required for correctness, remove both the WITH clause and the OPTION (TABLE HINTS...) clause entirely and allow SQL Server’s query optimizer to choose default locking and access behavior, then re-test for performance regressions.

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

Troubleshooting Guide: SQL Server Error 8720 — Multiple TABLE HINT Clauses

Why This Error Happens

This error occurs because a T-SQL query contains more than one TABLE HINT clause (specified via WITH (...)) applied to the same table reference, which SQL Server’s parser does not permit. This is typically introduced by developers manually combining hints (e.g., NOLOCK, INDEX, FORCESEEK) into separate bracketed groups instead of a single comma-separated list within one set of parentheses. It can also surface after migrating legacy scripts or ORM-generated queries to SQL Server 2025, where stricter parser validation now flags syntax that may have been silently tolerated in older engine versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing query text from the application log, SSMS error pane, or Extended Events session.
  • Look for the table name referenced in the error message (replacing %.*ls) to locate the exact object involved.
  • Search the query body for repeated WITH ( blocks attached to the same table alias.

Step 2: Consolidate the TABLE HINT Syntax

  • Locate syntax resembling:
  SELECT * FROM Orders WITH (NOLOCK) WITH (INDEX(IX_Orders_Date))
  • Merge all hints into a single WITH (...) clause separated by commas:
  SELECT * FROM Orders WITH (NOLOCK, INDEX(IX_Orders_Date))
  • Ensure only one WITH (...) block exists per table reference, even if multiple hints are required.

Step 3: Check Stored Procedures, Views, and ORM-Generated Code

  • Use sp_helptext or query sys.sql_modules to scan stored procedures and views for duplicate hint blocks:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%WITH (%WITH (%'
  • If the query originates from an ORM (Entity Framework, Hibernate, etc.) or a query-building library, inspect the hint-injection logic, as duplicate hint blocks are often generated programmatically.
  • Patch or update the ORM/query generator layer to emit a single consolidated hint clause.

Step 4: Redeploy and Re-test the Corrected Script

  • Save the corrected procedure/script and redeploy it to the target database using SSMS or your deployment pipeline.
  • Run the corrected query directly in SSMS against Windows Server 2025 / Windows 11 client tools to confirm Error 8720 no longer appears.

Alternative or Verification Steps

  • Re-execute the corrected query in SQL Server Management Studio (SSMS) or Azure Data Studio and confirm it returns results without throwing Error 8720.
  • If the error persists, enable SQL Server’s Query Store or run a trace via Extended Events to capture the exact batch text actually sent to the engine, as application-side query builders sometimes inject hidden duplicate hints not visible in the source code.

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

Troubleshooting Guide: SQL Server Error 8721 — Ambiguous Table Hint Reference

Why This Error Happens

Error 8721 occurs when a query’s OPTION clause contains a TABLE HINT that references a table or view name which cannot be uniquely resolved within the context of the query plan, typically because the object name is duplicated across different schemas, aliased inconsistently, or referenced multiple times within joins or subqueries. SQL Server 2025’s query optimizer requires an unambiguous binding between the hint and a single object instance, and when the parser encounters multiple candidate objects matching the hint’s identifier, it cannot determine which instance the hint should apply to. This commonly surfaces in complex queries involving self-joins, multiple schemas with identically named tables, or legacy query hints that were valid in older compatibility levels but are now stricter under the updated optimizer in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Ambiguous Object Reference

  • Review the full error message text, which includes the specific object name causing the conflict (replace %.*ls with the actual name shown in your error output).
  • Open SQL Server Management Studio (SSMS) and locate the exact query from the application log or SQL Profiler trace.
  • Check if the table name referenced in the TABLE HINT appears more than once in the FROM or JOIN clauses, including cases involving self-joins or multiple schemas (e.g., dbo.Orders vs sales.Orders).

Step 2: Qualify Table Aliases Explicitly

  • Rewrite the query so every table reference in the FROM/JOIN clause uses a unique alias.
  • Update the TABLE HINT clause to reference the alias instead of the base table name, for example:
  SELECT * FROM dbo.Orders AS O1 WITH (TABLE HINT(O1, FORCESEEK))
  • Ensure the alias used in OPTION (TABLE HINT(...)) exactly matches the alias declared in the main query body, as mismatched casing or whitespace can still trigger ambiguity in strict parsing mode.

Step 3: Replace TABLE HINT with USE PLAN (Recommended by Error Message)

  • Capture the existing actual execution plan in XML format using SET STATISTICS XML ON or by exporting the plan from SSMS (.sqlplan file).
  • Convert the query to use the OPTION (USE PLAN N'<xml_plan>') hint instead of TABLE HINT, embedding the captured XML plan directly into the query text.
  • Test the query in a non-production environment first, since USE PLAN locks the execution plan shape and may need regeneration after schema or index changes.

Step 4: Check Database Compatibility Level

  • Run SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the current compatibility level.
  • If the database was recently upgraded to SQL Server 2025, verify compatibility level 170 (or higher) is intentional, as stricter hint validation rules were introduced starting with this level.
  • If older query hint syntax is required for legacy application compatibility, consider temporarily lowering compatibility level via ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; as a short-term workaround while refactoring queries.

Step 5: Validate Query Plan Cache for Stale Hints

  • Clear any cached, invalid plans associated with the query using DBCC FREEPROCCACHE (scoped to a specific plan handle if in production, to avoid broader performance impact).
  • Re-run the corrected query to confirm a new, valid execution plan is generated without the ambiguous hint conflict.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS with SET STATISTICS PROFILE ON to confirm it completes successfully and returns the expected execution plan without Error 8721.
  • If the error persists after aliasing and USE PLAN conversion, use sp_helptext on any views involved in the query to check for embedded hints or nested ambiguous references inherited from underlying view definitions.

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

Troubleshooting Guide: Error 8717 – DML Operations Not Supported with External Tables

Why This Error Happens

Error 8717 occurs when an application or user attempts to execute INSERT, UPDATE, or DELETE statements directly against an external table in SQL Server 2025. External tables (such as those created via PolyBase, Data Virtualization, or linked to external data sources like Azure Blob Storage, Hadoop, or other relational systems) are read-only by design in most configurations, since SQL Server does not own the underlying storage engine. This typically happens because a developer or migration script mistakenly treats an external table like a standard local table, or because the external data source connector in use does not support write-back operations.

Step-by-Step Resolution Guide

Step 1: Identify the Target Object Type

  • Run sp_help 'YourTableName' or query sys.external_tables to confirm the object is indeed external rather than a standard heap/clustered table.
  • Check the EXTERNAL keyword in the CREATE TABLE definition using sys.tables joined with sys.external_tables on object_id.
  • Command: SELECT name, object_id FROM sys.external_tables WHERE name = 'YourTableName';

Step 2: Redirect DML Operations to a Staging Table

  • Create a local staging table with an identical schema using CREATE TABLE dbo.Staging_YourTableName (...).
  • Use INSERT INTO dbo.Staging_YourTableName SELECT * FROM ExternalTableName to pull data locally first.
  • Perform all required INSERT, UPDATE, or DELETE operations against the local staging table instead of the external source.

Step 3: Push Changes Back Using ETL or CETAS (If Write-Back Is Required)

  • If writing back to the external source is mandatory, use CREATE EXTERNAL TABLE AS SELECT (CETAS) to export modified data from the staging table to the external location.
  • On Windows Server 2025, verify the PolyBase service account has write permissions on the target external folder (check NTFS permissions at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\Polybase\).
  • Confirm the external data source credential (CREDENTIAL) used in CREATE EXTERNAL DATA SOURCE has write-level scope rather than read-only scope.

Step 4: Validate PolyBase/Data Virtualization Service Configuration

  • Open SQL Server Configuration Manager and confirm the “SQL Server PolyBase Engine” and “SQL Server PolyBase Data Movement” services are running under a service account with appropriate write access.
  • Restart both services via PowerShell if settings were changed: Restart-Service "MSSQLSERVER$PolyBase*".
  • Re-run the original DML statement against the staging table (not the external table) to confirm Error 8717 no longer appears.

Alternative or Verification Steps

  • Verify the fix by executing a test INSERT against the staging table and then running the CETAS export; confirm no Error 8717 is thrown and data lands correctly in the external location.
  • If write-back is not supported by your external data source type (e.g., read-only REST connectors), consider using SSIS or Azure Data Factory as an alternative ETL pipeline to synchronize changes instead of relying on native T-SQL DML.

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

Troubleshooting Guide: PolyBase Error 8715 – Failed to Set Physical Layout for Table

Why This Error Happens

Error 8715 typically occurs when the column definitions in your external table do not align with the physical structure of the underlying data file (such as mismatched data types, column order, or column count). This often happens after schema drift on the source file (CSV, Parquet, or ORC) or when the external file format object references incompatible serialization settings. Corrupted or incomplete metadata in the external data source can also trigger this mismatch between the declared “external buffer layout” and the actual file schema.

Step-by-Step Resolution Guide

Step 1: Validate the External Table Schema

  • Run sp_help 'YourExternalTableName' to inspect the current column definitions.
  • Compare the data types and column order against the actual source file (open a sample row in Parquet/CSV viewer).
  • Pay close attention to VARCHAR length mismatches and NULL/NOT NULL constraints, as these are the most common causes of buffer layout failures.

Step 2: Recreate the External File Format Object

  • Drop the existing file format using DROP EXTERNAL FILE FORMAT YourFileFormatName.
  • Re-create it ensuring the DATA_COMPRESSION and FIELD_TERMINATOR settings match the source file exactly.
  • If using Parquet, verify the FORMAT_TYPE = PARQUET option is correctly set without legacy CSV parameters lingering in the definition.

Step 3: Drop and Rebuild the External Table

  • Execute DROP EXTERNAL TABLE YourExternalTableName to clear any corrupted metadata cache.
  • Re-run the CREATE EXTERNAL TABLE statement, explicitly casting ambiguous columns (e.g., force BIGINT instead of relying on auto-detection for integer columns).
  • Ensure the column order in the CREATE EXTERNAL TABLE script matches the physical column order in the source file 1:1.

Step 4: Clear the PolyBase Cache and Restart Services

  • Open Services.msc on Windows Server 2025 and restart the SQL Server PolyBase Engine and SQL Server PolyBase Data Movement services.
  • Navigate to the PolyBase data movement directory (typically C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Binn\Polybase\) and clear any temporary cache logs if the issue persists after a schema fix.

Alternative or Verification Steps

  • Verify the Fix: Run a test query using SELECT TOP 10 * FROM YourExternalTableName; to confirm SQL Server can successfully read the buffer without throwing Error 8715.
  • Alternative Solution: If the error persists despite a correct schema, bypass the external file format issue by exporting the source data to a standardized, simple CSV format using default encoding (UTF-8) before re-attempting the CREATE EXTERNAL TABLE command.

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

Troubleshooting Guide: SQL Server Error 8716 – Invalid Shared Memory Table Data

Why This Error Happens

Error 8716 occurs when an external process writes a value into a SQL Server shared memory table using a data format or type that SQL Server does not recognize or support. This is typically caused by a mismatched or outdated SQL Server Native Client/driver version communicating over the shared memory protocol, a corrupted shared memory segment left behind by an improperly terminated connection, or a third-party monitoring/IPC tool injecting malformed data into the communication channel. In most cases, this points to a protocol-layer incompatibility rather than a problem with the actual database engine or stored data.

Step-by-Step Resolution Guide

Step 1: Verify and Update Client Connectivity Components

  • Open SQL Server Configuration Manager and confirm which protocols are enabled under SQL Server Network Configuration > Protocols for [Instance Name].
  • Check that the Shared Memory protocol is enabled only for local connections (right-click → Properties → Enabled = Yes).
  • Update the ODBC Driver or OLE DB Provider on client machines to the latest version compatible with SQL Server 2025 (download from Microsoft Download Center).
  • Restart the SQL Server service after updates: net stop MSSQLSERVER then net start MSSQLSERVER.

Step 2: Clear Corrupted Shared Memory Segments

  • Fully stop all SQL Server-related services, including SQL Server Agent and SQL Server Browser, via services.msc.
  • Restart the Windows Server 2025 / Windows 11 machine to force release of any orphaned shared memory handles (a simple service restart is often insufficient since the OS may retain stale memory-mapped segments).
  • After reboot, start services in order: SQL Server Browser > SQL Server (MSSQLSERVER) > SQL Server Agent.

Step 3: Identify the External Producer Process

  • Use SQL Server Profiler or Extended Events to capture the session ID and application name associated with the failing write at the time Error 8716 is raised.
  • Cross-reference the offending application in Task Manager or Resource Monitor to confirm if it is a legacy monitoring agent, backup tool, or custom IPC script.
  • If identified, update or disable the third-party tool temporarily to confirm it is the root cause.

Step 4: Rebuild the Shared Memory Endpoint

  • Navigate to SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for [Instance Name].
  • Disable the Shared Memory protocol, click Apply, then re-enable it and Apply again — this forces SQL Server to regenerate the memory-mapped file structure on next startup.
  • Restart the SQL Server service to apply the protocol reset.

Alternative or Verification Steps

  • Run a test connection using sqlcmd -S localhost -E immediately after remediation; if no 8716 error appears in the SQL Server Error Log (ERRORLOG file under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\), the shared memory channel is stable.
  • If the error persists, bypass Shared Memory entirely by forcing client connections to use TCP/IP instead (enable TCP/IP in Configuration Manager and specify tcp:ServerName in the connection string) as a reliable workaround while the root cause is investigated further.

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

Troubleshooting Guide: PolyBase Error 8714 — Failed to Convert External Data Format

Why This Error Happens

Error 8714 typically occurs when PolyBase encounters a data type or schema mismatch between the external data source file (CSV, Parquet, ORC) and the external table definition created in SQL Server. This often stems from incorrect column data types, unexpected NULL values in non-nullable columns, or malformed rows (such as inconsistent delimiters or encoding issues) within the source file. Additionally, outdated PolyBase connectors or corrupted ODBC/JDBC drivers on Windows Server 2025 can misinterpret the external file format, triggering this conversion failure.

Step-by-Step Resolution Guide

Step 1: Validate the External Table Schema Against Source Data

  • Open SQL Server Management Studio (SSMS) and run sp_help 'YourExternalTableName' to review the defined column data types.
  • Compare these types against the actual source file schema (e.g., open the CSV in a text editor or use Get-Content -Path "C:\Data\source.csv" -TotalCount 5 in PowerShell to inspect the first few rows).
  • Pay close attention to precision/scale mismatches on DECIMAL or NUMERIC columns, as these are the most common cause of Error 8714.

Step 2: Check for Malformed Rows or Null Handling Issues

  • Enable PolyBase rejection logging by setting REJECT_TYPE = VALUE and REJECT_VALUE = 10 (or a higher threshold) in your CREATE EXTERNAL TABLE statement to allow logging instead of a hard failure.
  • Locate the rejected rows log, typically found in the PolyBase data movement directory:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\PolybaseErrorLogs\
  • Open the .rejectedrows file in this directory to identify the exact row and column causing the conversion failure.

Step 3: Repair or Reinstall the PolyBase Connectivity Components

  • Open Services.msc and restart both SQL Server PolyBase Engine and SQL Server PolyBase Data Movement Service.
  • If the error persists, navigate to Control Panel > Programs > SQL Server 2025 Setup and select Repair on the PolyBase Query Service for External Data feature.
  • Verify the external data source connection string does not have a trailing slash or incorrect port number, as this can cause the engine to misread file headers during format conversion.

Step 4: Update Statistics and External File Format Object

  • Drop and recreate the EXTERNAL FILE FORMAT object to ensure the FIELD_TERMINATOR, STRING_DELIMITER, and DATE_FORMAT settings exactly match the source file’s current configuration.
  • Run UPDATE STATISTICS on the external table to refresh metadata cached by the SQL Server engine regarding the file format.

Alternative or Verification Steps

  • Verify the Fix: Run a simple SELECT TOP 10 * FROM YourExternalTableName; query. If the data returns without triggering Error 8714, the schema/format mismatch has been resolved.
  • Alternative Solution: If the error continues specifically with Parquet or ORC files, bypass the native PolyBase connector by using Azure Data Studio to export the data to a standard flat-file CSV format first, then re-import it to isolate whether the issue is file-format specific.

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

Troubleshooting Guide: SQL Server Error 8712 – Index Structure Corruption

Why This Error Happens

Error 8712 occurs when SQL Server’s storage engine detects a structural inconsistency within an index page, typically caused by physical corruption on the disk subsystem, improper shutdowns, or faulty storage hardware/drivers. This can also result from bit-level corruption introduced by memory errors (bad RAM) or a failing storage controller that silently alters data during I/O operations. In rarer cases, antivirus software or backup agents on Windows Server 2025 may lock or partially write to the underlying MDF/NDF files during an active transaction, leading to an inconsistent index structure.

Step-by-Step Resolution Guide

Step 1: Run DBCC CHECKDB to Confirm the Scope of Corruption

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Execute the following command to get a full diagnostic report: DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Note the specific Object ID and Index ID mentioned in the error output for targeted repair.

Step 2: Isolate and Repair the Specific Index

  • If the corruption is isolated to a single non-clustered index, the fastest fix is often to drop and rebuild it rather than running a full database repair.
  • Use the following syntax to rebuild the specific index identified in Step 1: ALTER INDEX [IndexName] ON [SchemaName].[TableName] REBUILD;
  • If the index is clustered or the rebuild fails, proceed to a targeted repair using: DBCC CHECKDB ('YourDatabaseName', REPAIR_REBUILD);

Step 3: Check Hardware and Windows Event Logs

  • Navigate to the Windows Server 2025 Event Viewer under Windows Logs > System to check for underlying Disk or NTFS warnings (Event ID 7 or 51).
  • Verify the storage controller drivers are up to date via Device Manager, as outdated drivers on Windows Server 2025 can cause I/O path corruption.
  • If using a SAN or virtualized storage, confirm the disk alignment and caching policies are correctly configured for SQL Server workloads.

Step 4: Restore from a Clean Backup (If Repair Fails)

  • If the index rebuild fails due to severe corruption, the safest route is restoring the database from the last known good backup.
  • Use RESTORE DATABASE [YourDatabaseName] FROM DISK = 'PathToBackupFile.bak' WITH REPLACE; to restore the full database.
  • Apply any available transaction log backups to minimize data loss up to the point of failure.

Alternative or Verification Steps

  • After applying the fix, re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS; to ensure the error code 8712 no longer appears and the allocation/index structures report “0 allocation errors and 0 consistency errors.”
  • If corruption recurs frequently, run Windows Memory Diagnostic (mdsched.exe) and a vendor-specific disk health check (such as chkdsk /f or a manufacturer’s SMART tool) to rule out failing physical hardware.

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

Troubleshooting Guide: Error 8713 – Could Not Force Query Plan Because of a Problem in an Indexed View

Why This Error Happens

This error occurs when SQL Server attempts to force a query plan (via Query Store or USE PLAN hint) that relies on an indexed view, but the indexed view’s schema has become inconsistent with the metadata stored in the plan. This typically happens after the underlying base tables referenced by the indexed view are altered (e.g., column changes, dropped constraints) without the indexed view being rebuilt. It can also occur if the indexed view itself is corrupted, disabled, or if SET options used at the time of the view’s creation differ from the current session’s SET options.

Step-by-Step Resolution Guide

Step 1: Verify the Indexed View’s Integrity

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run DBCC CHECKTABLE('YourIndexedViewName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to check for corruption.
  • Check sys.indexes and sys.views to confirm the clustered index on the view is still marked as valid and not disabled.

Step 2: Rebuild the Indexed View

  • Drop the existing unique clustered index on the view using DROP INDEX YourIndexName ON YourSchema.YourIndexedView;
  • Recreate the clustered index with CREATE UNIQUE CLUSTERED INDEX YourIndexName ON YourSchema.YourIndexedView (YourColumns);
  • This forces SQL Server to re-materialize the view data and refresh internal metadata used by the query optimizer.

Step 3: Validate SET Options Consistency

  • Confirm that ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER, and NUMERIC_ROUNDABORT are set to ON (except NUMERIC_ROUNDABORT, which must be OFF) at the session level.
  • Verify these same options were active when the indexed view was originally created by checking the object definition in sys.sql_modules.
  • Re-create the view with correct SET options explicitly declared at the top of the script if a mismatch is found.

Step 4: Clear and Reset the Query Store Plan

  • Navigate to Database Properties > Query Store in SSMS, or run ALTER DATABASE [YourDatabase] SET QUERY_STORE CLEAR; to purge stale forced plans.
  • Re-run the problematic query to allow SQL Server to generate and force a new, valid execution plan.
  • Optionally, use sp_query_store_unforce_plan to remove the specific broken forced plan before clearing the entire store.

Step 5: Update Statistics and Recompile

  • Execute UPDATE STATISTICS YourSchema.YourIndexedView WITH FULLSCAN; to ensure the optimizer has accurate data distribution information.
  • Run EXEC sp_recompile 'YourSchema.YourIndexedView'; to force recompilation of all dependent query plans.

Alternative or Verification Steps

  • To verify the fix, re-run the originally failing query and check sys.query_store_plan to confirm the plan is now marked as is_forced_plan = 1 with no associated error state.
  • If the issue persists, as a temporary workaround, use OPTION (IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX) or disable plan forcing for that specific query via sp_query_store_unforce_plan while the indexed view is rebuilt offline.

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

Troubleshooting Guide: SQL Server Error 8711 – Incompatible Orderings in Aggregate Functions

Why This Error Happens

Error 8711 occurs when a single query contains multiple ordered aggregate functions (such as those using WITHIN GROUP (ORDER BY ...)) that specify conflicting sort directions or sort columns within the same scope. SQL Server’s query optimizer cannot generate a single execution plan that simultaneously satisfies multiple incompatible sort requirements for aggregates evaluated in the same context. This is typically a query design issue rather than a server configuration problem, often introduced after application updates, ORM-generated queries, or manually written T-SQL that combines functions like STRING_AGG, PERCENTILE_CONT, or custom CLR aggregates with differing ORDER BY clauses.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Aggregate Functions

  • Review the query that triggered Error 8711 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Look specifically for multiple instances of WITHIN GROUP (ORDER BY ...) in the same SELECT statement or subquery scope.
  • Check for mismatched sort directions (e.g., one aggregate using ASC and another using DESC on related columns).
  • Example of a problematic pattern:
  SELECT 
      STRING_AGG(Name, ',') WITHIN GROUP (ORDER BY Name ASC),
      PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Salary DESC) OVER ()
  FROM Employees

Step 2: Isolate Each Aggregate Into Separate Query Scopes

  • Break the single query into separate Common Table Expressions (CTEs) or subqueries so each ordered aggregate operates independently.
  • Use a CTE per aggregate function to avoid scope collisions:
  WITH SortedByName AS (
      SELECT STRING_AGG(Name, ',') WITHIN GROUP (ORDER BY Name ASC) AS NameList
      FROM Employees
  ),
  SortedBySalary AS (
      SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Salary DESC) AS MedianSalary
      FROM Employees
  )
  SELECT * FROM SortedByName CROSS JOIN SortedBySalary;
  • Save the corrected script to a working file, e.g., C:\SQLScripts\Fix_8711_Query.sql.

Step 3: Align Sort Directions Where Aggregates Must Coexist

  • If the aggregates must remain in the same scope (e.g., inside a single OVER() window), standardize the ORDER BY direction across all ordered aggregates.
  • Update all conflicting clauses to use the same direction (either all ASC or all DESC) on the shared partition.
  • Re-run the query in SSMS to confirm the parser no longer throws Error 8711.

Step 4: Update Statistics and Rebuild the Execution Plan Cache

  • Clear any stale cached execution plans that may reference the old, broken query structure.
  • Run the following in a query window connected to the affected database:
  DBCC FREEPROCCACHE;
  GO
  UPDATE STATISTICS dbo.Employees WITH FULLSCAN;
  GO
  • Restart the SQL Server service via services.msc on Windows Server 2025 (locate “SQL Server (MSSQLSERVER)”) to ensure a clean plan cache state.

Step 5: Validate Application-Layer Query Generation (If Using an ORM)

  • If the query originates from Entity Framework, Dapper, or another ORM, inspect the generated SQL in the application logs.
  • Check configuration files (e.g., appsettings.json or web.config) for any custom aggregate mapping logic that might auto-generate conflicting ORDER BY clauses.
  • Patch the ORM query builder or override it with a raw SQL call using the corrected syntax from Step 2 or Step 3.

Alternative or Verification Steps

  • Verify the fix by re-executing the original failing query in SSMS and confirming it returns results without raising Error 8711; also check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for recurrence.
  • As an alternative, if restructuring the query isn’t immediately feasible, compute each ordered aggregate in separate round-trip queries from the application layer and merge the results in application code rather than in T-SQL.

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

Why This Error Happens

Error 8709 occurs when a T-SQL query uses a window function (such as SUM(), AVG(), or ROW_NUMBER()) with an OVER() clause containing a ROWS or RANGE frame specification where the boundary value is either NULL or a negative integer. SQL Server 2025’s query optimizer strictly validates frame delimiters—such as ROWS BETWEEN n PRECEDING AND m FOLLOWING—and rejects any execution plan where n or m evaluates to a negative number or resolves to NULL at runtime. This commonly happens when the delimiter value is derived from a variable, parameter, or subquery that wasn’t properly validated or defaulted before being passed into the window frame logic.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Isolate the Window Function

  • Check the SQL Server error log or Extended Events session for the exact statement that triggered Error 8709.
  • Open SQL Server Management Studio (SSMS) and run the query in isolation to reproduce the error.
  • Locate the OVER (... ROWS BETWEEN ... AND ...) or RANGE BETWEEN ... clause in the query text.

Step 2: Validate and Correct the Frame Delimiter Values

  • Ensure the PRECEDING/FOLLOWING values are static non-negative integers (e.g., ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING).
  • If the delimiter is sourced from a variable, add a guard clause:
  DECLARE @FrameSize INT = ISNULL(@InputFrameSize, 0);
  IF @FrameSize < 0 SET @FrameSize = 0;
  • Replace any dynamic SQL that concatenates user input directly into the ROWS BETWEEN clause with sanitized, validated integer values.

Step 3: Update Statistics and Rebuild Execution Plans

  • Run EXEC sp_recompile 'YourTableName'; to force SQL Server to regenerate the cached execution plan.
  • Clear the plan cache for the specific database if the issue persists:
  DBCC FREEPROCCACHE;
  • Confirm the SQL Server 2025 Cumulative Update level is current via SELECT @@VERSION;, as early builds had a known regression in frame-bound validation (fixed in CU2).

Step 4: Apply Windows Server 2025 / Windows 11 Patch Level Check

  • Open Settings > Windows Update and confirm all optional “Quality Updates” for SQL Server integration components are installed.
  • Verify no pending reboot is blocking the SQL Server service from loading updated query-processing DLLs located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.

Alternative or Verification Steps

  • Re-run the corrected query with SET SHOWPLAN_ALL ON; to confirm the execution plan no longer references an invalid frame boundary.
  • If the error persists after code correction, restore the affected stored procedure from a pre-migration backup and re-apply the window function logic manually, testing each delimiter value incrementally in a non-production environment.

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

Why This Error Happens

Error 8710 occurs when a query attempts to use a DISTINCT aggregate function (such as COUNT(DISTINCT column)) in combination with the CUBE or ROLLUP operators in a GROUP BY clause. SQL Server 2025’s query optimizer cannot generate the super-aggregate rows required by CUBE/ROLLUP when a DISTINCT aggregate is present, because the internal grouping sets engine does not support distinct-value deduplication across multiple aggregation levels simultaneously. This is a T-SQL syntax/logic limitation rather than a server configuration or permissions issue, so it will occur consistently regardless of the Windows Server 2025 or Windows 11 environment hosting the instance.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the query referenced in the error stack from the Application log or SSMS error output.
  • Look specifically for GROUP BY ... WITH CUBE, WITH ROLLUP, or GROUPING SETS clauses combined with COUNT(DISTINCT ...), SUM(DISTINCT ...), or AVG(DISTINCT ...).
  • Confirm the exact line number using the query execution plan or by isolating the SELECT statement in a new query window.

Step 2: Refactor the Query Using a Subquery or CTE

  • Rewrite the query to pre-aggregate the DISTINCT values in a Common Table Expression (CTE) or derived table before applying CUBE/ROLLUP.
  • Example pattern:
  WITH DistinctData AS (
      SELECT DISTINCT CustomerID, Region, OrderID
      FROM Sales.Orders
  )
  SELECT Region, COUNT(OrderID) AS OrderCount
  FROM DistinctData
  GROUP BY Region WITH CUBE;
  • This removes the DISTINCT keyword from inside the aggregate function while preserving the deduplication logic.

Step 3: Replace CUBE/ROLLUP with GROUPING SETS (If Applicable)

  • If only specific aggregation levels are needed (not the full cube), use explicit GROUPING SETS instead of CUBE, which can sometimes allow more flexible pre-processing of distinct values.
  • Test performance impact, as GROUPING SETS with large DistinctData CTEs can increase tempdb usage on Windows Server 2025 instances with default memory settings.

Step 4: Update Application/Reporting Layer Queries

  • Search any SSRS reports, Power BI datasets, or application-layer SQL (e.g., Entity Framework raw queries) for the same anti-pattern.
  • Deploy the corrected query to all environments (Dev, QA, Production) to prevent recurrence from cached or templated report queries.

Alternative or Verification Steps

  • Run the corrected query directly in SSMS against SQL Server 2025 and confirm it returns grouped results without raising Error 8710 in the Messages tab.
  • If rewriting is not immediately feasible, use SUM(CASE WHEN ... THEN 1 ELSE 0 END) as a manual distinct-count alternative within the CUBE aggregation to bypass the native DISTINCT restriction entirely.

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

Troubleshooting Guide: SQL Server Error 8705

Why This Error Happens

Error 8705 occurs when SQL Server’s Database Engine detects index corruption, specifically when a Data Manipulation Language (DML) operation (INSERT, UPDATE, DELETE) attempts to locate a row in a non-clustered index but finds no corresponding entry. This typically stems from underlying storage subsystem failures, improper shutdowns, faulty memory (RAM) on the host machine, or bugs in prior SQL Server builds that caused index desynchronization. Because the index no longer accurately maps to the underlying table data, the Storage Engine halts the transaction to prevent further data integrity violations.

Step-by-Step Resolution Guide

Step 1: Isolate the Scope of Corruption

  • Immediately run DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS; to get a full report.
  • Identify the specific Table ID and Index ID mentioned in the original error message using SELECT OBJECT_NAME(object_id) FROM sys.indexes WHERE index_id = [YourIndexID];.
  • Check the SQL Server Error Log (via SSMS Object Explorer > Management > SQL Server Logs) for concurrent I/O or disk-related warnings.

Step 2: Rebuild the Corrupted Non-Clustered Index

  • Since this error usually affects non-clustered indexes (which can be safely regenerated from the base table data), perform a rebuild rather than a restore.
  • Execute the following T-SQL command, replacing the placeholders:
    ALTER INDEX [YourIndexName] ON [YourSchema].[YourTableName] REBUILD WITH (ONLINE = ON, SORT_IN_TEMPDB = ON);
  • If the index name is unknown, rebuild all indexes on the table using ALTER INDEX ALL ON [YourTableName] REBUILD;

Step 3: Verify Hardware and Windows Server Stability

  • Open Event Viewer on Windows Server 2025 and navigate to Windows Logs > System to check for Disk, NTFS, or Volsnap errors occurring at the same timestamp as the SQL error.
  • Run chkdsk C: /f /r (adjusting the drive letter to your SQL data volume) during a scheduled maintenance window to scan for physical sector errors.
  • Verify your SAN/Storage drivers and firmware are up to date, as outdated drivers are a common cause of “torn pages” leading to Error 8705.

Step 4: Restore from Backup (If Rebuild Fails)

  • If the ALTER INDEX REBUILD command fails or DBCC CHECKDB reports errors on the Clustered Index (the actual data pages) rather than just a Non-Clustered Index, a rebuild will not fix the root data issue.
  • In this scenario, restore the specific database from the last known good, clean backup: RESTORE DATABASE [YourDatabaseName] FROM DISK = 'PathToBackup.bak' WITH NORECOVERY;
  • Apply subsequent transaction log backups to minimize data loss up to the point of failure.

Alternative or Verification Steps

  • Verify the Fix: Re-run DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS; immediately after the rebuild; a clean result with “0 allocation errors and 0 consistency errors” confirms the fix.
  • Alternative Fix: If corruption persists after a rebuild, drop the specific non-clustered index entirely using DROP INDEX and recreate it from scratch using CREATE INDEX, as this forces a full page allocation rather than a simple defragmentation.

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

Troubleshooting Guide: Error 8699 – Multiple USE PLAN Hints in SQL Server 2025

Why This Error Happens

This error occurs because the T-SQL query optimizer only supports a single USE PLAN query hint per statement, and the submitted query contains two or more instances of this hint—often due to nested subqueries, UNION statements, or stored procedures each carrying their own USE PLAN directive. This typically happens when query hints are programmatically injected by an ORM, middleware layer, or a query plan-forcing tool (like Plan Guides or Query Store) without checking for pre-existing hints in the batch. It can also surface after merging T-SQL scripts from different sources where each script independently applies a forced execution plan via XML plan hints.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Duplicate Hints

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio and review the raw query text being executed against the SQL Server 2025 instance.
  • Search explicitly for the string OPTION (USE PLAN within the batch; count the total occurrences.
  • Check if the query is being generated dynamically via application code (e.g., Entity Framework, Dapper) or constructed through string concatenation in a stored procedure.

Step 2: Isolate and Consolidate the Query Hints

  • If the query contains sub-selects or UNION ALL blocks, move the OPTION (USE PLAN N'<xml_plan>') clause so it only appears once at the outermost level of the batch.
  • Remove any redundant USE PLAN hints from inner derived tables or CTEs (Common Table Expressions); SQL Server 2025 requires the hint to apply to the statement as a whole, not to individual sub-components.
  • Validate the XML syntax of the remaining single hint using SELECT TRY_CONVERT(xml, '<ShowPlanXML>...</ShowPlanXML>') to ensure it wasn’t corrupted during the consolidation.

Step 3: Check Plan Guides and Query Store Interference

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Plan Guides in SSMS to see if an active Plan Guide is injecting a second USE PLAN hint automatically.
  • Run EXEC sp_control_plan_guide 'DROP', '<PlanGuideName>'; to remove conflicting guides if they duplicate a hint already present in the application code.
  • If using Query Store forced plans (sys.query_store_plan), verify via SELECT * FROM sys.query_store_plan WHERE is_forced_plan = 1; that forcing isn’t stacking with a manual hint in the same query.

Step 4: Update Application or Middleware Logic

  • If the duplication originates from application-layer code (common in batch-generated reports), update the data access layer to strip existing USE PLAN hints before appending a new one.
  • For C#/.NET applications, add a regex filter (e.g., Regex.Replace(query, @"OPTION\s*\(\s*USE PLAN.*?\)", "")) prior to injecting the updated plan hint.

Alternative or Verification Steps

  • Re-execute the cleaned query in SSMS and confirm the Messages tab shows no Error 8699, then check the Actual Execution Plan to verify the forced plan was applied as expected.
  • If removing duplicates isn’t feasible, bypass the hint entirely and use sp_create_plan_guide to externally force the execution plan, which decouples the plan-forcing logic from the query text itself.

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

Troubleshooting Guide: Error 8700 – Column Store Indexes on Memory Optimized Tables Disabled

Why This Error Happens

This error occurs because the SQL Server instance has the column store index for memory optimized tables feature disabled at either the database scoped configuration or server configuration level, typically following a migration, restore, or default installation setting in SQL Server 2025. It can also surface if the database compatibility level is set below the threshold required to support memory-optimized columnstore operations. Additionally, this may happen if the Hekaton (In-Memory OLTP) engine was not properly initialized during the filegroup creation process.

Step-by-Step Resolution Guide

Step 1: Verify Current Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) 21 and connect to your SQL Server 2025 instance.
  • Run the following query to check the compatibility level: SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDBName';
  • Ensure the compatibility level is set to 160 or higher to support the required memory-optimized indexing features.

Step 2: Enable the Columnstore Index Configuration

  • Execute the following T-SQL command to enable the feature at the database scope: ALTER DATABASE SCOPED CONFIGURATION SET MEMORY_OPTIMIZED_COLUMNSTORE_INDEX = ON;
  • If the command fails, verify you are a member of the sysadmin or db_owner role for the target database.
  • Restart the specific database context (not the full instance) to apply the scoped configuration changes.

Step 3: Check Server-Level Trace Flags and Configuration

  • Open the SQL Server Configuration Manager on your Windows Server 2025 machine.
  • Navigate to the SQL Server Services properties and check the Startup Parameters tab for any lingering trace flags (e.g., -T9976) that might be force-disabling memory-optimized columnstore functionality.
  • Remove any conflicting deprecated trace flags and restart the SQL Server (MSSQLSERVER) service.

Step 4: Rebuild the Index with Explicit Hints

  • If the configuration is correct but the query still fails, modify the query to force the engine to recognize the index: SELECT * FROM YourTable WITH (INDEX(YourColumnstoreIndexName));
  • Ensure the index name matches exactly what is defined in sys.indexes for that specific memory-optimized table.

Alternative or Verification Steps

  • To verify the fix, run SELECT DATABASEPROPERTYEX('YourDBName', 'IsMemoryOptimizedElevateToSnapshotEnabled'); and ensure the query executes without throwing Error 8700.
  • If the error persists, consider dropping and recreating the memory-optimized filegroup container, as a corrupted checkpoint file pair (CFP) in the Data directory can sometimes mimic this disabled-feature behavior.

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

Troubleshooting Guide: Error 8698 – USE PLAN Hint Verification Failure

Why This Error Happens

Error 8698 occurs when SQL Server’s query processor attempts to apply a forced execution plan via the USE PLAN hint (often generated by Query Store plan forcing or sp_create_plan_guide), but the plan XML no longer matches the current shape, schema, or semantics of the query. This typically happens after schema changes (added/dropped columns, indexes, or constraints), statistics updates, or when the query text has been altered slightly since the plan was originally captured. It can also occur in SQL Server 2025 when cross-database references, parameterization mismatches, or incompatible compatibility levels prevent the optimizer from validating the frozen plan as logically equivalent to the submitted query.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the USE PLAN Hint

  • Check if the hint originates from Query Store (sys.query_store_plan) or a manually created plan guide.
  • Run the following to locate active plan guides:
  SELECT * FROM sys.plan_guides WHERE is_disabled = 0;
  • Review sys.query_store_plan.is_forced_plan = 1 entries if using Query Store forcing.

Step 2: Remove or Disable the Invalid Plan Guide/Forced Plan

  • If using a manual plan guide, drop it:
  EXEC sp_control_plan_guide N'DROP', N'PlanGuideName';
  • If using Query Store, unforce the plan:
  EXEC sp_query_store_unforce_plan @query_id = <id>, @plan_id = <id>;
  • This immediately allows SQL Server to fall back to the optimizer’s natural plan choice.

Step 3: Validate Schema and Statistics Alignment

  • Ensure no recent ALTER TABLE, index rebuilds, or column changes have invalidated the original plan’s assumptions.
  • Update statistics to ensure the optimizer has current data distribution info:
  UPDATE STATISTICS dbo.YourTableName WITH FULLSCAN;
  • Confirm database compatibility level matches the level used when the plan was captured:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';

Step 4: Regenerate and Re-Force a Valid Plan (Optional)

  • If plan forcing is still desired, capture a fresh plan under current schema conditions using Query Store’s “Force Plan” feature in SSMS (Query Store > Top Resource Consuming Queries).
  • Alternatively, recreate the plan guide using sp_create_plan_guide with updated @hints reflecting the current query structure.

Step 5: Restart the SQL Server Service (If Plan Cache Corruption Suspected)

  • On Windows Server 2025 / Windows 11, open Services.msc, locate SQL Server (MSSQLSERVER) or named instance, and restart it.
  • Alternatively, run from an elevated PowerShell prompt:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This clears any stale cached plan metadata tied to the invalid hint.

Alternative or Verification Steps

  • Re-run the original query without the USE PLAN hint to confirm it executes successfully and check the actual execution plan via Include Actual Execution Plan in SSMS.
  • If forcing is required long-term, enable Automatic Plan Correction in Query Store (ALTER DATABASE SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE)) so SQL Server can automatically detect and revert invalid forced plans going forward.

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

Troubleshooting Guide: SQL Server Error 8696 – Improperly Formed Spool Element in USE PLAN Hint

Why This Error Happens

This error occurs when the XML execution plan supplied in a USE PLAN hint contains a Spool element whose parent RelOp node has a NodeId that is either missing, duplicated, or does not uniquely correspond to a single operator in the plan tree. SQL Server’s query optimizer requires every RelOp associated with a Spool operator to have a distinct NodeId so it can correctly map the forced plan shape back to the logical query tree. This typically results from manually edited XML plans, plans copied between different query contexts, or plans generated by a mismatched SQL Server version/build that structures Spool metadata differently.

Step-by-Step Resolution Guide

Step 1: Validate the XML Plan Structure

  • Open the XML plan file or extracted plan text used in the USE PLAN hint.
  • Search for all instances of <RelOp NodeId= and cross-reference them against every <Spool> parent element.
  • Confirm no two RelOp elements share the same NodeId value anywhere in the document.
  • Use a tool like Notepad++ or VS Code with XML formatting enabled to visually inspect nested Spool structures.

Step 2: Regenerate the Execution Plan from a Clean Source

  • Re-run the original query using SET SHOWPLAN_XML ON or extract the plan via SQL Server Management Studio (SSMS) “Include Actual Execution Plan” rather than reusing an old or hand-edited XML file.
  • Save the newly generated plan as a .sqlplan file to avoid encoding or structural corruption from copy-pasting raw XML.
  • Avoid merging plan fragments from two different queries or SQL Server builds, as NodeId numbering is context-specific per compiled plan.

Step 3: Apply the USE PLAN Hint with the Verified XML

  • Reference the clean, regenerated XML plan in your query hint syntax:
OPTION (USE PLAN N'<ShowPlanXML>...</ShowPlanXML>')
  • Ensure the XML namespace declaration matches the SQL Server 2025 schema version (xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan").
  • Test the query in a non-production environment first to confirm the Spool and RelOp hierarchy compiles without error 8696.

Step 4: Check for Compatibility Level Mismatches

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the database compatibility level matches the SQL Server 2025 engine generating the plan.
  • If the XML plan was captured on a different compatibility level or older SQL Server version, regenerate it after aligning compatibility levels using:
ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • After applying the corrected plan, execute the query with OPTION (RECOMPILE) once to confirm no residual cached plan is causing conflicting NodeId references.
  • If the error persists, bypass the USE PLAN hint temporarily and use OPTION (USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION')) or a plan guide instead, then re-capture a fresh XML plan from that execution for future reuse.

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

Troubleshooting Guide: Error 8697 — “Cannot Run Query Because in XML Plan Provided to USE PLAN”

Why This Error Happens

This error occurs when the XML execution plan supplied to the USE PLAN query hint does not match the structure or requirements of the query it is being applied to, often due to schema changes, index modifications, or statistics drift since the plan was captured. SQL Server 2025’s query optimizer validates the plan against the current query shape, and any mismatch—such as missing operators, invalid join types, or referenced objects (indexes/views) that no longer exist—triggers a hard failure rather than a fallback. Corrupted or manually edited XML plan files are another common root cause, as even minor syntax deviations break the plan guide parser.

Step-by-Step Resolution Guide

Step 1: Validate the XML Plan Structure

  • Open the .sqlplan or inline XML string in SQL Server Management Studio (SSMS) and check for well-formed XML syntax.
  • Confirm the plan was generated from the exact same query text (including whitespace and casing) using SET SHOWPLAN_XML ON.
  • Look for <MissingIndexes> or <Warnings> nodes that indicate the plan is already flagging incompatibilities.

Step 2: Regenerate the Execution Plan

  • Run the target query without USE PLAN and capture a fresh actual execution plan via SSMS (Ctrl+M) or SET STATISTICS XML ON.
  • Export the new plan using Right-click → Save Plan As XML.
  • Replace the outdated plan file referenced in your OPTION (USE PLAN N'...') hint with this newly generated XML.

Step 3: Verify Referenced Objects Still Exist

  • Check that all indexes, statistics, and views referenced in the XML plan (search for Index= and Object= attributes) still exist in the database.
  • Run sp_helpindex 'TableName' and DBCC SHOW_STATISTICS to confirm nothing was dropped or renamed since the plan was captured.
  • Rebuild any missing or fragmented indexes using ALTER INDEX ... REBUILD.

Step 4: Check Compatibility Level and Query Store Settings

  • Verify the database compatibility level via SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'; matches the level the plan was generated under.
  • If using Query Store–forced plans instead, run sp_query_store_unforce_plan and re-force a current plan through sp_query_store_force_plan.
  • Restart the SQL Server 2025 instance service via Services.msc on Windows Server 2025 only if plan cache corruption is suspected.

Alternative or Verification Steps

  • Re-run the query with OPTION (USE PLAN N'<new_xml>') and confirm it executes without Error 8697, then check sys.dm_exec_query_plan to ensure the plan is being used as expected.
  • As a fallback, remove USE PLAN entirely and use OPTION (RECOMPILE) or a plan guide via sp_create_plan_guide instead, letting the optimizer generate a compatible plan automatically.

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

Troubleshooting Guide: SQL Server Error 8695 – Incorrectly Formed XML Plan in USE PLAN Hint

Why This Error Happens

This error occurs when the XML plan supplied to the USE PLAN query hint is malformed, incomplete, or does not conform to the schema that SQL Server’s plan forcing mechanism expects. It commonly results from manually editing an XML plan, copying a plan from a different SQL Server version (such as extracting one from SQL Server 2019 and forcing it on SQL Server 2025), or truncation of the XML string during storage or transmission. Since SQL Server 2025 validates the plan against internal structural rules before execution, any mismatch — missing nodes, invalid operators, or incompatible plan shape — causes the engine to reject the hint outright.

Step-by-Step Resolution Guide

Step 1: Validate the XML Plan Source

  • Confirm the XML plan was generated using SET SHOWPLAN_XML ON or extracted directly from sys.dm_exec_query_plan on the same SQL Server 2025 instance (or a fully compatible version).
  • Avoid manually editing node attributes like NodeId, PhysicalOp, or LogicalOp, as hand-edited plans frequently fail schema validation.
  • Check that the XML was not truncated when copied from SSMS results grid (use “Save Results As” instead of copy-paste for large plans).

Step 2: Re-Capture the Plan Using the Correct Method

  • Run the query with actual execution plan capture enabled:
  SET STATISTICS XML ON;
  GO
  • Alternatively, extract the plan directly via:
  SELECT query_plan 
  FROM sys.dm_exec_query_stats AS qs
  CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle);
  • Save the full, unmodified XML output and reapply it in the OPTION (USE PLAN N'<ShowPlanXML>...') clause.

Step 3: Verify Plan Compatibility Settings

  • Check the database compatibility level, since USE PLAN requires the XML to match the compatibility level of the database:
  SELECT name, compatibility_level 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If the plan was generated under a different compatibility level (e.g., 150 vs. 170 in SQL Server 2025), regenerate it under the current level using:
  ALTER DATABASE YourDatabaseName 
  SET COMPATIBILITY_LEVEL = 170;

Step 4: Test the Plan in Isolation

  • Run the query with the USE PLAN hint in a scratch/test environment on Windows Server 2025 before deploying to production.
  • Use SET PARSEONLY ON combined with plan validation tools to confirm the XML parses without triggering Error 8695.
  • Remove any extraneous whitespace, BOM (byte-order marks), or encoding artifacts introduced when the XML was saved via text editors like Notepad.

Alternative or Verification Steps

  • To verify the fix, re-execute the query with the corrected OPTION (USE PLAN N'...') hint and confirm no Error 8695 is raised; check the actual execution plan in SSMS to ensure it matches the forced plan shape.
  • If re-forcing the plan continues to fail, use Query Store instead (sys.sp_query_store_force_plan) to force a known-good plan by plan_id, which bypasses manual XML handling entirely and is less error-prone on SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 8694

Why This Error Happens

Error 8694 occurs because the USE PLAN query hint forces SQL Server’s optimizer to use a specific, cached execution plan, but this is fundamentally incompatible with queries involving distributed queries (linked servers) or full-text search operations. The query optimizer cannot guarantee or force a fixed plan shape when the execution involves external data sources (via OLE DB providers) or specialized full-text indexes, because these operations rely on dynamic resource allocation that cannot be dictated by a static XML plan. Essentially, the engine is rejecting the hint because it conflicts with the underlying architecture required to process remote or full-text data.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the specific T-SQL statement causing the error in your application code, stored procedure, or ETL job (e.g., SSIS package running on Windows Server 2025).
  • Check if the query contains references to a linked server (e.g., SELECT * FROM LinkedServerName.DB.Schema.Table) or a CONTAINS/FREETEXT predicate alongside an OPTION (USE PLAN N'...') clause.

Step 2: Remove the USE PLAN Hint

  • Open the query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Manually delete the OPTION (USE PLAN N'<XML_Plan>') clause from the end of the query batch.
  • If the hint was auto-generated via a Plan Guide, you will need to drop it using sp_control_plan_guide 'DROP', 'PlanGuideName';.

Step 3: Isolate Distributed/Full-Text Logic

  • If forcing a plan is strictly necessary for performance tuning, refactor the query to separate the logic.
  • Use a temporary table or table variable to pull data from the linked server or full-text index first (without the hint).
  • Apply the USE PLAN hint only to the second, local query that processes the data already stored in the temp table.

Step 4: Update Statistics and Recompile

  • Since removing the hint reverts control to the Query Optimizer, ensure your statistics are current to avoid performance regressions.
  • Run UPDATE STATISTICS TableName; on the relevant tables.
  • Execute EXEC sp_recompile 'ObjectName'; to clear any stale cached plans associated with the previous hint.

Alternative or Verification Steps

  • Verification: Re-run the query in SSMS with “Include Actual Execution Plan” enabled (Ctrl+M). If the query executes successfully and returns the full-text/distributed results without a red X error icon, the conflict is resolved.
  • Alternative: If specific plan stability is required, replace USE PLAN with more generalized hints like OPTION (RECOMPILE) or specific join hints (e.g., OPTION (LOOP JOIN)) which are compatible with distributed and full-text operations.

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

Troubleshooting Guide: Error 8692 – USE PLAN Hint Not Supported

Why This Error Happens

This error occurs because the USE PLAN query hint is restricted exclusively to SELECT statements in SQL Server 2025, and the engine has detected it attached to an unsupported statement type such as INSERT, UPDATE, DELETE, or MERGE. The root cause is almost always a T-SQL authoring issue where a query hint was copied from a SELECT statement (often during performance tuning or Query Store plan forcing) and pasted into a DML statement without adjusting the hint syntax. This is a parser-level validation error, not a permissions, port, or file corruption issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement

  • Check the application log or SSMS error output for the exact statement text referenced by %ls in the error message.
  • Search your stored procedures, dynamic SQL blocks, or ORM-generated queries for OPTION (USE PLAN '...') clauses.
  • Pay special attention to MERGE statements, which often embed an internal SELECT but apply the hint to the outer statement by mistake.

Step 2: Remove or Relocate the USE PLAN Hint

  • If the hint was mistakenly applied to an INSERT...SELECT, UPDATE, or DELETE statement, delete the OPTION (USE PLAN N'<xml_plan>') clause from the outer statement.
  • If plan forcing is genuinely required, isolate the SELECT portion of your logic into a separate statement or subquery and apply USE PLAN only there.
  • For MERGE statements, confirm that no hint syntax was incorrectly inherited from a source SELECT used to build the merge source.

Step 3: Use Query Store or Plan Guides as an Alternative

  • Instead of manually embedding USE PLAN in DML statements, use sp_query_store_force_plan to force a specific plan at the Query Store level without modifying T-SQL syntax.
  • Navigate to SSMS > Databases > [Your DB] > Query Store > Top Resource Consuming Queries, locate the query, and force the desired plan directly from the GUI.
  • This avoids hardcoding plan XML into application code and sidesteps the SELECT-only restriction entirely.

Step 4: Validate the T-SQL Syntax

  • Re-run the corrected statement in SSMS or Azure Data Studio connected to your Windows Server 2025 instance.
  • Confirm no OPTION (USE PLAN ...) clause exists outside of SELECT statements, including inside CTEs feeding into DML operations.
  • Check execution plans (Ctrl+M) to ensure the intended plan is still being used after removing the hint.

Alternative or Verification Steps

  • Run the corrected query and confirm Error 8692 no longer appears in SSMS or the SQL Server error log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If plan stability is still required for DML statements, use Plan Guides (sp_create_plan_guide) with the OBJECT or SQL type, which support a broader range of statement types than inline USE PLAN hints.

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

Troubleshooting Guide: SQL Server Error 8693

Why This Error Happens

Error 8693 occurs when the SQL Server Query Optimizer encounters an unsupported or invalid combination of a logical operator (LogicalOp) with specific data types, indexes, or physical operators during query compilation. This is typically triggered by querying columns with incompatible data types (such as certain spatial, CLR, or FILESTREAM types) using operations the optimizer cannot translate into a valid execution plan. It can also surface due to corrupted statistics, outdated query plans in cache, or bugs related to specific Cumulative Updates (CUs) on SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Object

  • Capture the exact query text from the application logs or SQL Server error logs to isolate the specific SELECT, UPDATE, or JOIN statement causing the compile failure.
  • Check if the query involves spatial data types (GEOGRAPHY/GEOMETRY), computed columns, or full-text indexes, as these are common triggers.
  • Run DBCC TRACEON(3604, -1) temporarily in a test environment to get verbose optimizer output if the error persists.

Step 2: Update Statistics and Rebuild Indexes

  • Outdated or corrupted statistics often cause the optimizer to select an invalid logical operation path.
  • Navigate to SQL Server Management Studio (SSMS) and run the following against the affected database:
  EXEC sp_updatestats;
  • Rebuild indexes on the specific table referenced in the query to eliminate fragmentation-related compilation errors:
  ALTER INDEX ALL ON [YourTableName] REBUILD;

Step 3: Clear the Procedure Cache

  • A stale or corrupted execution plan stored in memory can cause the optimizer to repeatedly fail on the same logical combination.
  • Execute the following command to force SQL Server to recompile the plan from scratch:
  DBCC FREEPROCCACHE;
  • Alternatively, use sp_recompile 'YourTableName' to mark a specific object’s plan for recompilation without flushing the entire server cache.

Step 4: Apply the Latest Cumulative Update (CU)

  • Since this is a newly released issue specific to SQL Server 2025, verify that you are not running a known buggy build.
  • Navigate to the Microsoft Update Catalog or use SQL Server Setup to check for the latest CU.
  • Install the update on your Windows Server 2025 instance and restart the MSSQLSERVER service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER.

Alternative or Verification Steps

  • Verify the Fix: Re-run the exact query that previously failed in SSMS. If the execution plan generates successfully (visible via Display Estimated Execution Plan), the issue is resolved.
  • Alternative Workaround: If updating isn’t immediately possible, rewrite the query to avoid the specific logical operator combination (e.g., replace an OR condition with a UNION ALL of two separate SELECT statements) to bypass the specific optimizer bug.

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

Troubleshooting Guide: Error 8691 – USE PLAN Hint Conflicts with SET Option

Why This Error Happens

This error occurs because the query uses a USE PLAN hint to force a specific execution plan, but that cached plan was generated under different SET options (such as ARITHABORT, ANSI_WARNINGS, QUOTED_IDENTIFIER, or CONCAT_NULL_YIELDS_NULL) than the ones currently active in the session. SQL Server 2025 enforces strict plan-to-session consistency to guarantee deterministic query results, so if the session-level SET option doesn’t match what the plan guide or cached plan expects, the Query Optimizer rejects compilation. This commonly happens when applications, ORMs, or connection drivers (like ODBC or JDBC) set different default session options than what was used when the plan was originally captured.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting SET Option

  • Read the full error message text carefully — it explicitly names the conflicting option (e.g., SET ARITHABORT ON conflicts, so you need ARITHABORT OFF).
  • Run the query manually in SQL Server Management Studio (SSMS) with SET SHOWPLAN_TEXT ON to see which session settings are embedded in the plan.
  • Check sys.dm_exec_plan_attributes for the cached plan to view the set_options bitmask value tied to the plan.

Step 2: Adjust Session-Level SET Options in the Client Application

  • Locate the connection string or driver configuration (ODBC Data Source, JDBC URL, or .NET SqlConnection settings) on the Windows Server 2025 or Windows 11 client machine.
  • For ODBC connections, open ODBC Data Source Administrator (odbcad32.exe), select the SQL Server DSN, and verify the “Use ANSI Quoted Identifiers” and “Use ANSI Null, Paddings and Warnings” checkboxes match the plan’s expected values.
  • For application code, explicitly issue the correct option before the query executes, for example:
  SET ARITHABORT OFF;
  GO
  • Restart the application pool or service (IIS, Windows Service, or custom app host) to apply the updated connection settings.

Step 3: Recreate or Drop the Conflicting Plan Guide

  • Open SSMS and run sp_help_plan_guide to list all active plan guides on the database.
  • If the plan guide was created with outdated or mismatched SET assumptions, drop it:
  EXEC sp_control_plan_guide N'DROP', N'PlanGuideName';
  • Recreate the plan guide using sp_create_plan_guide with the @hints parameter reflecting the current session SET options used by your application.

Step 4: Align Database-Level Defaults

  • In SSMS, right-click the database → Properties → Options, and confirm ANSI NULLS, ANSI Warnings, and Arithabort defaults align with your application’s connection settings.
  • For Windows Server 2025 environments using Always On Availability Groups, ensure these database-scoped settings are consistent across all replicas to avoid plan conflicts during failover.

Alternative or Verification Steps

  • Re-run the original failing query after applying the SET change — if Error 8691 no longer appears and an execution plan returns successfully, the fix is confirmed.
  • As a quick alternative, remove the USE PLAN hint entirely from the query and let SQL Server’s optimizer generate a fresh plan; this bypasses the conflict entirely if plan-forcing isn’t strictly required.

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

Why This Error Happens

Error 8689 occurs when SQL Server attempts to bring a database containing memory-optimized (In-Memory OLTP) filegroups online, but the server does not have enough available physical memory to load the Hekaton data into RAM. This typically happens after a server reboot, a failover, or when the “Max Server Memory” setting is configured too restrictively relative to the size of the memory-optimized tables. Since memory-optimized data must reside entirely in memory for the database to function, SQL Server refuses to open the database rather than risk instability.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Allocation

  • Open SQL Server Management Studio (SSMS) and run EXEC sp_configure 'max server memory'; to check the current ceiling.
  • Compare this value against the physical RAM installed on the Windows Server 2025 host (visible via Task Manager > Performance > Memory).

Step 2: Increase Max Server Memory Configuration

  • Run the following T-SQL to raise the limit (adjust value in MB based on available RAM):
  • EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
  • EXEC sp_configure 'max server memory', 16384; RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER for the setting to take full effect on the instance.

Step 3: Check for Competing Memory Consumers

  • Open Task Manager (Ctrl+Shift+Esc) on Windows Server 2025 and identify other processes (IIS, backup agents, antivirus scanners) consuming significant RAM.
  • Temporarily stop non-essential services to free up memory for the memory-optimized filegroup to load.

Step 4: Add Physical Memory or Resize VM Allocation

  • If running on a Hyper-V or Azure VM, increase the assigned vRAM through the Hyper-V Manager or VM settings blade.
  • Ensure the host itself has sufficient free memory to support the increased allocation before applying changes.

Step 5: Attempt Database Recovery

  • Once memory is adjusted, try bringing the database back online using:
  • ALTER DATABASE [YourDatabaseName] SET ONLINE;
  • Monitor the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for confirmation that the memory-optimized filegroup loaded successfully.

Alternative or Verification Steps

  • Verify the fix by querying sys.dm_os_memory_clerks for the MEMORYCLERK_XTP type to confirm the memory-optimized data has been allocated correctly.
  • If increasing memory is not feasible, consider reducing the size of memory-optimized tables (e.g., archiving old data) or migrating some tables back to disk-based storage to lower the memory footprint.

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

Troubleshooting Guide: SQL Server Error 8690 – USE PLAN Hint Conflict

Why This Error Happens

Error 8690 occurs when a query contains a USE PLAN hint alongside another query hint that is logically incompatible with forcing a specific execution plan, such as FORCE ORDER, OPTIMIZE FOR, or another plan-shaping directive. SQL Server 2025’s query optimizer cannot reconcile a fixed XML execution plan with additional hints that attempt to alter join order, parameterization behavior, or other compilation-time decisions. This typically results from hints being copied or merged from Query Store forced plans, plan guides, or legacy T-SQL scripts without validating hint compatibility.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Hint in the Query Text

  • Open the failing query in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate the OPTION clause and review all hints listed alongside USE PLAN.
  • Check the error message detail — SQL Server substitutes the actual conflicting hint name in place of %ls (e.g., FORCE ORDER or OPTIMIZE FOR UNKNOWN).

Step 2: Remove or Isolate the Conflicting Hint

  • Edit the query and delete the hint named in the error output (e.g., remove FORCE ORDER if it conflicts).
  • If the hint was auto-generated via a Plan Guide, run sp_help_plan_guide to inspect its definition.
  • Update the plan guide using sp_control_plan_guide 'DROP', '<plan_guide_name>' followed by sp_create_plan_guide with corrected hint syntax.

Step 3: Validate Query Store Forced Plans

  • Open SSMS > Databases > [Your DB] > Query Store > Top Resource Consuming Queries.
  • Check if the query has a forced plan applied; if so, click Unforce Plan before retesting.
  • Re-run the query manually with only the USE PLAN hint to confirm it compiles independently.

Step 4: Rebuild and Reapply the Plan Guide (If Applicable)

  • Use the following T-SQL template to regenerate the plan guide without the conflicting hint:
EXEC sp_create_plan_guide
    @name = N'PG_FixedPlan',
    @stmt = N'<original query text>',
    @type = N'SQL',
    @hints = N'OPTION (USE PLAN N''<xml_plan>'')';
  • Deploy the corrected plan guide to the target database on Windows Server 2025.

Alternative or Verification Steps

  • Run SELECT * FROM sys.plan_guides WHERE is_disabled = 0; to confirm no duplicate or conflicting guides remain active.
  • As an alternative, replace USE PLAN with a simpler, compatible hint set (e.g., just OPTIMIZE FOR) if plan-forcing isn’t strictly required, then monitor execution plan stability via Query Store for 24–48 hours.

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

Troubleshooting Guide: SQL Server Error 8688 — Cursor Plan Forcing Failed via USE PLAN

Why This Error Happens

This error occurs when the XML execution plan supplied to the USE PLAN query hint is structurally invalid, malformed, or incompatible with the current query shape for a cursor operation. SQL Server’s Query Optimizer validates the XML plan against internal plan-matching rules, and if the cursor’s underlying query doesn’t align with the operators, indexes, or join structures defined in the forced plan, the forcing operation is rejected. This commonly happens after schema changes (dropped/renamed indexes or columns), SQL Server version upgrades that alter plan XML schemas, or when a plan XML is manually edited or copied from a mismatched query context.

Step-by-Step Resolution Guide

Step 1: Validate the XML Plan Structure

  • Extract the exact XML plan being passed to USE PLAN and validate it against the showplanxml.xsd schema located under C:\Program Files\Microsoft SQL Server\160\Tools\Binn\schemas\sqlserver\2004\07\showplan\.
  • Check for schema version mismatches — SQL Server 2025 may use an updated showplan schema version than the one that generated the original XML.
  • Run the query standalone with SET SHOWPLAN_XML ON to confirm SQL Server can generate a valid baseline plan for comparison.

Step 2: Verify Referenced Objects Still Exist

  • Confirm all indexes, statistics, and tables referenced in the XML plan (e.g., <Object Index="..." Table="..."/> nodes) still exist and haven’t been renamed or dropped.
  • Query sys.indexes and sys.stats to cross-reference object names in the plan.
  • Rebuild or recreate any missing indexes that the forced plan depends on.

Step 3: Regenerate the Plan Using Plan Guides or Query Store

  • Instead of manually crafting XML, use Query Store (Object Explorer > Databases > [YourDB] > Query Store > Top Resource Consuming Queries) to capture a known-good plan and force it via sp_query_store_force_plan.
  • Alternatively, use sp_create_plan_guide with @type = N'SQL' and reference a tested, current execution plan rather than a hand-edited XML blob.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after applying plan guide changes to clear cached invalid plans.

Step 4: Check Compatibility Level Settings

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabase'; to confirm the database compatibility level matches the level the XML plan was generated under.
  • If mismatched, update it using ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170; (adjust to your SQL Server 2025 target level).
  • Re-test the cursor operation after aligning compatibility levels.

Alternative or Verification Steps

  • Re-run the cursor query with OPTION (USE PLAN N'<xml_plan>') removed temporarily to confirm the query executes correctly without forcing, isolating whether the issue is the plan itself or the underlying query.
  • If plan forcing continues to fail, use sp_query_store_force_plan through Query Store instead of manual USE PLAN hints, as it automatically validates plan compatibility before applying it.

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

Troubleshooting Guide: Error 8687 – Cursor Plan Failed with USE PLAN Hint

Why This Error Happens

This error occurs because the USE PLAN query hint can only be applied to cursors declared as FAST_FORWARD or STATIC. When SQL Server 2025 encounters a cursor of a different type (such as DYNAMIC, KEYSET, or default FORWARD_ONLY) combined with a forced execution plan, it cannot reconcile the cursor’s mechanics with the specified plan shape, causing the optimizer to reject the request. This typically surfaces after a plan guide, query hint, or plan forcing operation (via Query Store or sp_create_plan_guide) is applied to a stored procedure or ad-hoc query that declares a non-compliant cursor type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Cursor Declaration

  • Capture the exact query text using Extended Events or the SQL Server error log (filter for Error 8687).
  • Locate the DECLARE CURSOR statement in the associated stored procedure, function, or ad-hoc batch.
  • Check the cursor type keyword used (e.g., DYNAMIC, KEYSET, or no explicit type, which defaults to FORWARD_ONLY/dynamic behavior in some contexts).

Step 2: Modify the Cursor Type to a Supported Format

  • Edit the T-SQL code to explicitly declare the cursor as FAST_FORWARD or STATIC, for example:
  DECLARE cur CURSOR FAST_FORWARD FOR
  SELECT column1, column2 FROM YourTable;
  • If STATIC is more appropriate (e.g., the application needs a snapshot that doesn’t reflect concurrent changes), use:
  DECLARE cur CURSOR STATIC FOR
  SELECT column1, column2 FROM YourTable;
  • Save and redeploy the modified stored procedure or script to the database.

Step 3: Remove or Replace the USE PLAN Hint

  • If changing the cursor type is not feasible, remove the OPTION (USE PLAN N'...') hint from the query.
  • In SQL Server Management Studio (SSMS) 21, open the query/procedure definition and strip out the USE PLAN XML hint block.
  • Replace it with alternative hints like OPTION (RECOMPILE), OPTION (OPTIMIZE FOR (@param = value)), or a PLAN GUIDE targeting a compatible query form.

Step 4: Update Statistics to Allow Natural Plan Selection

  • Run UPDATE STATISTICS on the tables referenced by the cursor query:
  UPDATE STATISTICS dbo.YourTable WITH FULLSCAN;
  • Alternatively, update all statistics in the database:
  EXEC sp_updatestats;
  • This allows the SQL Server 2025 Cardinality Estimator to choose an appropriate plan without forcing, reducing dependency on USE PLAN.

Step 5: Validate Plan Guides and Query Store Settings

  • Open SQL Server Management Studio → Databases → [YourDB] → Query Store → Top Resource Consuming Queries.
  • Check if a forced plan (via Query Store “Force Plan” feature) is causing the conflict; if so, select Unforce Plan.
  • If using sp_create_plan_guide manually, run sp_control_plan_guide 'DROP', 'GuideName' to remove conflicting guides tied to non-compliant cursors.

Alternative or Verification Steps

  • After applying changes, execute the stored procedure or query directly in SSMS and confirm Error 8687 no longer appears in the Messages tab or the SQL Server Error Log (EXEC sp_readerrorlog).
  • As an alternative, if forcing a specific plan is mandatory, refactor the cursor logic into a set-based operation (replacing the cursor entirely) so that USE PLAN can be applied without cursor-type restrictions.

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

Troubleshooting Guide: Error 8685 – USE PLAN Hint Applied to Non-Cursor Statement

Why This Error Happens

Error 8685 occurs when a query hint USE PLAN is supplied with an XML plan that contains elements valid only for cursor-based execution (such as <CursorPlan> nodes), but the statement it is being applied to is a standard, non-cursor DML statement. This typically results from manually editing an XML plan, copying a plan from a different query context (e.g., from a stored procedure using cursors), or from an application/ORM layer generating forced-plan hints programmatically without validating the statement type. SQL Server 2025’s query optimizer strictly validates the plan shape against the statement type before compilation, and any mismatch immediately throws this error rather than attempting a partial match.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Plan Source

  • Locate the exact query text raising Error 8685 by checking the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG (path may vary based on instance name).
  • Run the following to capture the failing statement in real time:
SELECT text, query_plan 
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t;
  • Confirm whether the query was manually hinted with OPTION (USE PLAN N'<ShowPlanXML>...').

Step 2: Regenerate a Clean XML Plan from SQL Server

  • Remove the existing hand-modified or mismatched plan from the query.
  • Execute the query without any hint and capture the actual execution plan using:
SET STATISTICS XML ON;
GO
-- Run your query here
GO
SET STATISTICS XML OFF;
  • Save the resulting XML plan directly from SQL Server Management Studio (right-click plan → “Save Plan As”) rather than copying plan XML from another cursor-based query or external tool.

Step 3: Reapply the USE PLAN Hint Correctly

  • Ensure the XML plan you reapply via OPTION (USE PLAN N'...') originates from the exact same statement type (non-cursor to non-cursor).
  • Avoid injecting <CursorPlan> or cursor-specific XML nodes into plans used for standard SELECT/INSERT/UPDATE/DELETE statements.
  • If using Plan Guides via sp_create_plan_guide, validate the plan type parameter matches OBJECT, SQL, or TEMPLATE correctly based on the statement, not a cursor execution context.

Step 4: Validate Compatibility Level and Query Store Settings

  • Check the database compatibility level, since SQL Server 2025 enforces stricter plan validation on higher compatibility levels:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If using Query Store forced plans (sys.sp_query_store_force_plan), unforce the plan first, then re-force using a freshly captured plan:
EXEC sys.sp_query_store_unforce_plan @query_id, @plan_id;

Alternative or Verification Steps

  • Re-run the query after reapplying the corrected plan and confirm no Error 8685 appears in the Error Log or SSMS Messages pane; also verify via sys.dm_exec_query_stats that the plan compiled successfully.
  • If the error persists, bypass USE PLAN entirely and instead use simpler hints like OPTION (RECOMPILE) or OPTION (OPTIMIZE FOR) to achieve similar plan stability without the risk of XML plan mismatches.

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

Troubleshooting Guide: SQL Server Error 8686 – Cursor Plan Forcing Failure

Why This Error Happens

Error 8686 occurs when SQL Server’s Plan Forcing engine attempts to apply a USE PLAN hint or a forced plan via Query Store to a cursor-based query, but the supplied XML plan contains a duplicate OperationType node where the optimizer expects exactly one. This typically happens because the XML plan was manually edited, hand-crafted, or copied/merged from multiple execution plans rather than being captured directly and unmodified from SQL Server’s actual output. Since cursor plans have strict structural requirements (the optimizer needs a single, unambiguous operation node for operations like FETCH, OPEN, or CLOSE), any duplication—even if syntactically valid XML—breaks the plan-forcing validation logic in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Plan and Query

  • Run the following to find the query and plan handle associated with the failure:
  • SELECT * FROM sys.dm_exec_query_store_plan WHERE plan_id = <failing_plan_id>;
  • Check SQL Server Error Log (via xp_readerrorlog) or Event Viewer under Applications and Services Logs > Microsoft > SQL Server for the full XML snippet referenced in the error text (%ls will show the specific OperationType, e.g., “Fetch Cursor”).
  • Confirm whether the plan was applied via sp_create_plan_guide with @type = N'XML_SHOWPLAN' or via Query Store forcing (sys.sp_query_store_force_plan).

Step 2: Re-Capture a Clean, Unmodified XML Plan

  • Do not hand-edit the XML plan file. Instead, re-generate it directly from SQL Server:
  • Enable SET SHOWPLAN_XML ON; and re-run the original cursor query to capture a fresh, native XML plan.
  • Save the output directly from SSMS (right-click plan > “Save Plan As”) rather than copying/pasting XML text, which often introduces duplicate or malformed nodes.
  • Store the captured .sqlplan file in a controlled path, e.g., C:\SQLPlans\CursorPlan_Clean.sqlplan, for reuse.

Step 3: Drop and Recreate the Plan Guide or Forced Plan

  • If using a plan guide, drop the broken one first:
  • EXEC sp_control_plan_guide N'DROP', N'<PlanGuideName>';
  • Recreate it using the clean XML captured in Step 2:
  • EXEC sp_create_plan_guide @name = N'PG_CursorFix', @stmt = N'<original_query_text>', @type = N'XML_SHOWPLAN', @module_or_batch = NULL, @params = NULL, @hints = N'<clean_xml_plan_here>';
  • If using Query Store forced plans instead, unforce and reforce:
  • EXEC sys.sp_query_store_unforce_plan @query_id, @plan_id;
  • EXEC sys.sp_query_store_force_plan @query_id, @new_clean_plan_id;

Step 4: Validate Cursor Options in the Query

  • Ensure the cursor declaration itself (FAST_FORWARD, STATIC, DYNAMIC, etc.) matches the plan shape expected by the optimizer.
  • Avoid mixing cursor types that generate multiple possible operation paths (e.g., switching between forward-only and scrollable cursors), as this can cause the optimizer to generate ambiguous nodes during recompilation.

Step 5: Test in a Non-Production Environment First

  • Apply the corrected plan guide or Query Store forced plan in a staging instance of SQL Server 2025 running on Windows Server 2025 or Windows 11 (developer edition) before deploying to production.
  • Run DBCC FREEPROCCACHE (scoped to the specific plan handle if possible) to clear any cached invalid plan artifacts.

Alternative or Verification Steps

  • Verify the fix by re-running the original cursor query and checking sys.dm_exec_query_store_plan or sys.plan_guides to confirm is_disabled = 0 and no corresponding error appears in sys.dm_exec_query_store_query plan forcing failure reason reports.
  • If plan forcing continues to fail, consider abandoning manual plan guide creation entirely and instead let Query Store automatically capture and force a known-good plan using sys.sp_query_store_force_plan based on a historical plan_id that executed successfully in production telemetry.

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

Troubleshooting Guide: SQL Server Error 8684 – USE PLAN Hint Optimizer Failure

Why This Error Happens

Error 8684 occurs when the SQL Server Query Optimizer attempts to validate a forced execution plan supplied via a USE PLAN hint, but the plan requires more internal transformation operations than the optimizer’s internal threshold allows. This typically happens when the underlying table statistics have changed significantly since the plan was generated (via XML plan guide or forced plan), making the old plan structurally incompatible with the current data distribution. It can also occur when the query itself is highly complex (many joins/subqueries), causing the optimizer’s search space to exceed internal limits while trying to reconcile the hinted plan shape.

Step-by-Step Resolution Guide

Step 1: Remove or Isolate the USE PLAN Hint

  • Temporarily strip the OPTION (USE PLAN N'...') clause from the query text and re-run it to confirm the query executes successfully without the forced plan.
  • If the query runs fine without the hint, this confirms the forced plan is stale or incompatible with current statistics rather than a syntax error.
  • Check if the hint originated from a Plan Guide using sp_control_plan_guide or sys.plan_guides catalog view.

Step 2: Update Statistics and Rebuild Indexes

  • Run UPDATE STATISTICS <table_name> WITH FULLSCAN; on all tables referenced in the query to ensure the optimizer has accurate cardinality estimates.
  • For databases with heavy write activity, execute EXEC sp_updatestats; at the database level to refresh all outdated statistics in bulk.
  • Rebuild fragmented indexes using ALTER INDEX ALL ON <table_name> REBUILD; since fragmented indexes can cause the optimizer to generate drastically different plan shapes than the one specified in the hint.

Step 3: Drop and Regenerate the Plan Guide (If Applicable)

  • Locate the specific guide using SELECT * FROM sys.plan_guides WHERE name = '<guide_name>';
  • Drop the outdated guide with EXEC sp_control_plan_guide N'DROP', N'<guide_name>';
  • Recreate the plan guide using sp_create_plan_guide with a freshly captured XML showplan from the current query execution, ensuring the new plan aligns with updated table statistics.

Step 4: Increase Optimizer Search Depth (Advanced Workaround)

  • If removing the hint is not feasible, add trace flag 2301 cautiously in a test environment to allow more aggressive optimization search depth, though this may increase compile time.
  • Alternatively, simplify the query logic (e.g., breaking a large multi-join query into temp tables or CTEs) to reduce the complexity of the search space the optimizer must traverse to match the plan.

Alternative or Verification Steps

  • Verify the fix by running the original query with SET STATISTICS XML ON; to confirm an actual execution plan is generated without error 8684 appearing in the Messages tab.
  • If the error persists after updating statistics, use Query Store (Query Store > Top Resource Consuming Queries) to force a new, valid plan directly through the GUI rather than relying on the legacy USE PLAN XML hint.

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

Troubleshooting Guide: SQL Server Error 8683 – Invalid Star Join Specification in USE PLAN Hint

Why This Error Happens

This error occurs when the XML showplan supplied in a USE PLAN query hint has been manually edited or reconstructed in a way that produces an invalid or unsupported Star Join operator specification. SQL Server’s query optimizer validates the structural integrity of the plan against the actual query tree, and Star Join operators have strict requirements regarding the number and arrangement of fact/dimension table inputs. When the XML is altered outside of SQL Server’s native plan export process (or copied from a different query/schema context), the optimizer cannot reconcile the Star Join topology with the current query, triggering Error 8683.

Step-by-Step Resolution Guide

Step 1: Capture a Fresh, Unmodified Showplan

  • Re-run the original query without any USE PLAN hint and enable SET SHOWPLAN_XML ON or use “Include Actual Execution Plan” in SSMS.
  • Export the resulting XML directly via Right-click → Save Execution Plan As rather than copying/pasting text, which can introduce formatting or encoding errors.
  • Avoid manually editing any node attributes, especially StarJoinInfo, IndexedViewInfo, or join ordering elements.

Step 2: Validate the XML Structure Before Reapplying

  • Open the saved .sqlplan file and confirm the StmtSimple and QueryPlan nodes match the current query text exactly (same table order, same join predicates).
  • Check that the Star Join section (<StarJoinInfo>) references valid fact and dimension table aliases that still exist in the current schema.
  • If the schema has changed since the plan was captured (e.g., index rebuilt, partition changed, or dimension table altered), regenerate the plan from scratch instead of reusing the old XML.

Step 3: Reapply the USE PLAN Hint Using the Verified XML

  • Use the unmodified XML directly in the hint:
  OPTION (USE PLAN N'<ShowPlanXML>...</ShowPlanXML>')
  • Ensure no whitespace, encoding (UTF-8 vs UTF-16), or line-break corruption occurred when copying the XML into the query string.
  • If pulling from Query Store, use sp_query_store_force_plan instead of manually pasting XML, since it guarantees a validated, SQL Server-generated plan.

Step 4: Disable Star Join Optimization If Issue Persists

  • If the application does not strictly require Star Join processing, add trace flag 2301 only after testing, or disable the behavior at the query level with:
  OPTION (USE PLAN N'...', QUERYTRACEON 9481)
  • Test whether forcing a standard nested loop/hash join plan resolves the forcing issue, as a temporary workaround while investigating the root schema change.

Alternative or Verification Steps

  • Run the query with the forced plan and check sys.dm_exec_query_plan or sys.query_store_plan to confirm the plan was accepted without falling back to Error 8683.
  • If forcing still fails, use Query Store’s “Force Plan” UI feature in SSMS instead of manual USE PLAN XML — it automatically validates plan compatibility before applying it, bypassing manual XML corruption issues entirely.

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

Troubleshooting Guide: SQL Server Error 8681 – Internal Query Processor Error

Why This Error Happens

Error 8681 is a generic internal query processor error that typically occurs when SQL Server’s optimizer encounters an invalid or unexpected query execution plan state, often triggered by outdated statistics, corrupted query plan cache entries, or bugs exposed by complex queries (such as those with heavy nested views, CTEs, or parallelism). It can also surface due to memory pressure causing the optimizer to fail mid-computation, or because of a missing cumulative update that contains a fix for a known optimizer defect. In some cases, corrupted metadata in system catalog views following an incomplete upgrade to SQL Server 2025 can also trigger this error.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure Cache and Update Statistics

  • Run DBCC FREEPROCCACHE to remove potentially corrupted cached execution plans.
  • Execute EXEC sp_updatestats; on the affected database to refresh outdated statistics.
  • Re-run the failing query to see if the error persists.

Step 2: Check and Apply the Latest Cumulative Update

  • Open SQL Server Configuration Manager and verify the current build number via SELECT @@VERSION;.
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the CU package and restart the SQL Server service from services.msc.

Step 3: Disable Parallelism for the Problematic Query

  • Add query hint OPTION (MAXDOP 1) to the failing query to force a serial execution plan.
  • If the error disappears, lower the server-wide max degree of parallelism setting under Server Properties > Advanced in SQL Server Management Studio (SSMS).
  • Document the query pattern for future optimizer regression tracking.

Step 4: Run Database Consistency Checks

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption.
  • Review the output for any allocation or consistency errors tied to system tables.
  • If corruption is found, restore from the most recent verified backup.

Step 5: Enable Trace Flags for Diagnostic Logging

  • Add trace flag -T3604 and -T8675 temporarily via SQL Server Configuration Manager startup parameters.
  • Restart the SQL Server instance and reproduce the error to capture detailed optimizer output in the SQL Server error log.
  • Remove the trace flags once diagnostics are complete to avoid performance overhead.

Alternative or Verification Steps

  • Verify the fix by running the originally failing query 3–5 times under normal load to confirm Error 8681 no longer appears in the SQL Server error log (%ProgramFiles%\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • If the error persists after all steps, open a Microsoft Support ticket and attach the DBCC CHECKDB output along with the captured trace flag logs for deeper optimizer-level analysis.