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

Troubleshooting Guide: Error 4220 – Cannot Back Up the Log of the Model Database with NORECOVERY

Why This Error Happens

This error occurs because the model database is a system database that does not support transaction log backups using the WITH NORECOVERY option, as this option leaves the database in a restoring, inaccessible state. Since SQL Server depends on model being online and accessible at all times to create new user databases and for internal engine operations, Microsoft explicitly blocks any operation that could take it offline or leave it in a non-recovered state. This is a safeguard built into the SQL Server 2025 engine rather than a configuration or permissions error.

Step-by-Step Resolution Guide

Step 1: Verify the Target Database

  • Confirm that the backup command is actually targeting model and not a similarly named user database.
  • Run the following query to inspect current database states:
SELECT name, state_desc, recovery_model_desc FROM sys.databases;
  • If model was intentionally targeted, proceed to Step 2, as this is a restricted operation.

Step 2: Modify the Backup Command

  • Remove the WITH NORECOVERY clause from your T-SQL script or SQL Server Agent job step.
  • Use a standard log backup syntax instead:
BACKUP LOG model TO DISK = 'C:\Backups\model_log.bak';
  • If the goal was to restore model to a specific point in time, note that model cannot be restored over while the SQL Server instance is running, as the engine requires it to function.

Step 3: Re-evaluate the Backup Strategy for System Databases

  • Open SQL Server Management Studio (SSMS) and navigate to Management > Maintenance Plans.
  • Ensure that any maintenance plan backing up system databases (master, model, msdb) uses Full Backup types only, as log backups with recovery-altering options are unnecessary for model in most standard HA/DR strategies.
  • If model is in the FULL recovery model and you require log backups for compliance reasons, switch it to SIMPLE recovery to avoid unnecessary log growth and backup complexity:
ALTER DATABASE model SET RECOVERY SIMPLE;

Step 4: Restart the SQL Server Service (If State is Stuck)

  • If model appears to be in a “Restoring” state due to a failed attempt prior to hitting Error 4220, restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025.
  • This forces the engine to re-initialize model from its last known good state, as SQL Server will refuse to start if model is genuinely corrupted or stuck in recovery.

Alternative or Verification Steps

  • Run RESTORE DATABASE model WITH RECOVERY only if the database is stuck in a restoring state from a previous erroneous attempt; this will bring it back online immediately.
  • Verify the fix by running a standard full backup against model (BACKUP DATABASE model TO DISK = 'C:\Backups\model_full.bak') to confirm the instance recognizes the database as healthy and accessible.

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

Troubleshooting Guide: Error 4218 – Bulk-Logged Operations Exist in Database

Why This Error Happens

This error occurs because the database is using the Bulk-Logged recovery model, and a minimally logged (bulk) operation was performed since the last log backup. SQL Server blocks a subsequent BACKUP LOG operation in certain scenarios—such as when the log backup is being used for point-in-time restore chains or mirrored/Always On configurations—because bulk-logged transactions cannot be replayed to an exact point in time. This safeguard prevents data integrity issues on secondary replicas or during granular restores.

Step-by-Step Resolution Guide

Step 1: Identify the Recovery Model and Bulk Operations

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the SQL Server 2025 instance.
  • Run the following query to check the current recovery model:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm if BULK_LOGGED is set, and check recent operations like BULK INSERT, SELECT INTO, or index rebuilds with TF 610 enabled.

Step 2: Switch to FULL Recovery Model (If Point-in-Time Recovery Is Required)

  • Execute the following T-SQL command to change the recovery model:
  ALTER DATABASE YourDatabaseName SET RECOVERY FULL;
  • This ensures all future transactions are fully logged, allowing uninterrupted point-in-time restores and compatibility with Always On Availability Groups.
  • Note: This step requires a subsequent full or differential backup to re-establish the log chain.

Step 3: Perform a Full or Differential Backup Before Retrying Log Backup

  • Since switching recovery models breaks the log backup chain, take a full backup immediately:
  BACKUP DATABASE YourDatabaseName TO DISK = 'C:\Backups\YourDatabaseName_Full.bak';
  • Once the full backup completes, attempt the transaction log backup again:
  BACKUP LOG YourDatabaseName TO DISK = 'C:\Backups\YourDatabaseName_Log.trn';

Step 4: Verify Always On / Mirroring Compatibility (If Applicable)

  • If the database is part of an Always On Availability Group, confirm that the Bulk-Logged recovery model is not being used, as it is unsupported for synchronous replicas requiring point-in-time recovery.
  • Check replica health in SSMS under Always On High Availability > Availability Group Dashboard.
  • Adjust the recovery model on the primary replica only, then allow synchronization to propagate to secondaries.

Alternative or Verification Steps

  • Verify the fix by running BACKUP LOG YourDatabaseName TO DISK = 'C:\Backups\Test_Log.trn'; and confirming it completes without Error 4218.
  • If the issue persists, check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for additional context on blocked bulk operations or replica synchronization failures.

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

Troubleshooting Guide: Error 4217 – “BACKUP LOG cannot modify the database because the database is read-only”

Why This Error Happens

This error occurs because SQL Server attempts to truncate the transaction log as part of a log backup operation, but the database is currently set to READONLY mode, preventing any write operations including log truncation markers. This commonly happens after restoring a database with the READONLY option, attaching a database from a read-only filesystem, or when a database is intentionally set to read-only for reporting purposes but log backup jobs were not excluded from maintenance plans. Despite the error, SQL Server typically continues the backup operation but skips the log truncation step, which can lead to unexpected log chain behavior.

Step-by-Step Resolution Guide

Step 1: Verify the Current Database State

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the SQL Server 2025 instance.
  • Run the following query to check the database status:
  SELECT name, is_read_only, recovery_model_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • Confirm whether is_read_only returns 1, validating the root cause.

Step 2: Determine Intent (Permanent vs. Temporary Read-Only)

  • If the database was intentionally set to read-only (e.g., for a reporting replica), exclude it from transaction log backup jobs in SQL Server Agent.
  • Navigate to SQL Server Agent > Jobs in SSMS and edit the maintenance plan or backup job step to skip read-only databases using a conditional check.
  • If the read-only state was unintentional, proceed to Step 3 to revert it.

Step 3: Set the Database Back to READ_WRITE

  • If write access and proper log backups are required, change the database mode using Transact-SQL:
  ALTER DATABASE YourDatabaseName 
  SET READ_WRITE WITH NO_WAIT;
  • Ensure no active connections are blocking the change; if necessary, use WITH ROLLBACK IMMEDIATE to force disconnect active sessions before altering the mode.
  • Verify the file permissions on the physical .mdf/.ldf files located typically in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ to ensure the Windows Server 2025 OS level permissions are not forcing a read-only file attribute.

Step 4: Update Maintenance Plans and Backup Scripts

  • Modify existing SQL Server Agent jobs or Maintenance Plan Wizard tasks to filter out read-only databases explicitly if they are meant to remain in that state long-term.
  • Use a dynamic script check before the backup command:
  IF (SELECT is_read_only FROM sys.databases WHERE name = 'YourDatabaseName') = 0
  BEGIN
      BACKUP LOG YourDatabaseName TO DISK = 'YourBackupPath.trn'
  END

Alternative or Verification Steps

  • To verify the fix, manually execute a BACKUP LOG command against the specific database and confirm the operation completes without Error 4217 in the SQL Server Error Log or Windows Event Viewer.
  • If the database must remain strictly read-only for compliance reasons, switch the recovery model to SIMPLE to prevent the system from attempting log backups entirely, using ALTER DATABASE YourDatabaseName SET RECOVERY SIMPLE;.

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

Troubleshooting Guide: SQL Server Error 4215 – Log Not Truncated (Pending Replication/CDC)

Why This Error Happens

This error occurs because SQL Server’s transaction log cannot be truncated when there are log records that have not yet been consumed by the Log Reader Agent (for Transactional Replication) or the Capture Job (for Change Data Capture). This typically happens when the Log Reader Agent or CDC Capture job is stopped, disabled, or failing silently, causing a backlog of unprocessed transactions. Additionally, this can occur if replication or CDC was improperly removed from the database, leaving orphaned metadata that still signals pending log records to SQL Server.

Step-by-Step Resolution Guide

Step 1: Verify the Status of the Log Reader Agent or CDC Capture Job

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Navigate to Replication > Local Publications (if using Transactional Replication) and check if the Log Reader Agent job is running under SQL Server Agent > Jobs.
  • For CDC, run the following query to check job status:
  EXEC sys.sp_cdc_help_jobs;
  • If the job is stopped or disabled, right-click and select Start Job at Step… in SSMS.

Step 2: Check SQL Server Agent Service Status on Windows Server 2025 / Windows 11

  • Open Services.msc (Win + R, type services.msc).
  • Locate SQL Server Agent (MSSQLSERVER) or your named instance.
  • Ensure the Service Status is Running and the Startup Type is set to Automatic.
  • If stopped, right-click and select Start, then re-check the Log Reader Agent job status.

Step 3: Identify and Clear the Blocking Transaction Log Records

  • Run the following query to identify the oldest active transaction blocking log truncation:
  SELECT log_reuse_wait_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the result shows REPLICATION, verify replication is configured correctly; if CDC, check sys.dm_cdc_log_scan_sessions for scan errors.
  • Restart the Log Reader Agent job to attempt processing the backlog.

Step 4: Manually Mark Transactions as Distributed or Captured (If Replication/CDC is Decommissioned)

  • If replication or CDC is no longer in use but the error persists, run sp_repldone to manually clear the pending log markers:
  USE YourDatabaseName;
  EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1;
  • Caution: Only run this command if you are certain replication/CDC data is no longer needed, as this permanently discards pending transaction markers.

Step 5: Force a Transaction Log Backup

  • Once the blocking job is running or sp_repldone has been executed, force a log backup to clear the virtual log files (VLFs):
  BACKUP LOG YourDatabaseName TO DISK = 'C:\Backups\YourDatabaseName_Log.trn';
  • Monitor the log file size via DBCC SQLPERF(LOGSPACE); to confirm truncation has occurred.

Alternative or Verification Steps

  • Verification: Run DBCC SQLPERF(LOGSPACE); to confirm the “Log Space Used (%)” has decreased, indicating successful truncation.
  • Alternative: If the Log Reader Agent continues to fail due to corruption, consider reinitializing the subscription or dropping and re-adding the CDC instance using sys.sp_cdc_disable_db and sys.sp_cdc_enable_db.

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

Troubleshooting Guide: Error 4212 — Cannot Back Up the Log of the Master Database

Why This Error Happens

The master database operates exclusively in the SIMPLE recovery model, which SQL Server enforces at all times regardless of administrative overrides. Because the SIMPLE recovery model automatically truncates the transaction log after every checkpoint, there is no persistent log chain available for a BACKUP LOG operation to capture. This is a hard architectural restriction in SQL Server 2025, not a permissions or corruption issue, so the fix lies in adjusting the backup strategy rather than the database configuration.

Step-by-Step Resolution Guide

Step 1: Confirm the Recovery Model of the Master Database

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your instance.
  • Run the following query to verify:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'master';
  • Confirm the result returns SIMPLE. This is expected and cannot be changed.

Step 2: Replace the Log Backup Command with a Full Database Backup

  • Locate the maintenance plan, SQL Agent job, or script that is issuing the BACKUP LOG master command.
  • Replace it with a full backup command instead:
  BACKUP DATABASE master 
  TO DISK = 'C:\SQLBackups\master_full.bak' 
  WITH INIT, STATS = 10;
  • Ensure the target path (e.g., C:\SQLBackups\) exists and the SQL Server service account has write permissions to it.

Step 3: Update SQL Server Agent Jobs or Maintenance Plans

  • Open SQL Server Agent > Jobs in SSMS.
  • Edit any job step referencing BACKUP LOG master and remove it, or disable that specific step.
  • If using a Maintenance Plan Wizard, uncheck “Transaction Log” backups for the master database in the backup task configuration — only “Full” should be selected for system databases.

Step 4: Schedule Regular Full Backups for System Databases

  • Since master, model, and msdb cannot use log backups, schedule frequent full backups (e.g., daily) to minimize data loss exposure.
  • Example SQL Agent schedule: Daily at 2:00 AM, BACKUP DATABASE master TO DISK = 'C:\SQLBackups\master_$(ESCAPE_SQUOTE(JOBID)).bak'.

Alternative or Verification Steps

  • Verify the fix by manually executing the BACKUP DATABASE master command in SSMS and confirming it completes with “100 percent processed” and no error 4212 is thrown.
  • If automated jobs still fail, check the SQL Server Agent job history (right-click job > View History) to confirm the log backup step was successfully removed or disabled.

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

Troubleshooting Guide: SQL Server Error 4214 — “BACKUP LOG Cannot Be Performed”

Why This Error Happens

This error occurs because SQL Server requires a full database backup to exist before it can start a chain of transaction log backups. It is commonly triggered when the database recovery model was recently switched from SIMPLE to FULL (or BULK_LOGGED) without taking an immediate full backup afterward, leaving no valid starting point for the log chain. It can also occur if the database is new and has never had a full backup performed, or if the backup history/chain was broken by an external process.

Step-by-Step Resolution Guide

Step 1: Verify the Current Recovery Model

  • Open SQL Server Management Studio (SSMS) and connect to the Windows Server 2025 instance.
  • Run the following query to check the database state:
  SELECT name, recovery_model_desc, log_reuse_wait_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If recovery_model_desc shows FULL or BULK_LOGGED, proceed to Step 2.

Step 2: Perform a Full Database Backup

  • This is the mandatory fix. You cannot back up the log without first establishing a base backup point.
  • Execute the following T-SQL command, replacing the path with your designated backup directory (e.g., E:\SQLBackups\):
  BACKUP DATABASE [YourDatabaseName] 
  TO DISK = 'E:\SQLBackups\YourDatabaseName_Full.bak' 
  WITH INIT, COMPRESSION;
  • Ensure the SQL Server Service Account has Write permissions on the target folder via Windows 11/Server 2025 File Explorer security settings.

Step 3: Attempt the Transaction Log Backup

  • Once the full backup completes successfully, immediately attempt the log backup that previously failed.
  • Run the command:
  BACKUP LOG [YourDatabaseName] 
  TO DISK = 'E:\SQLBackups\YourDatabaseName_Log.trn';
  • Check the “Messages” tab in SSMS to confirm the backup processed the correct number of pages without throwing Error 4214 again.

Step 4: Check for Third-Party Backup Interference

  • If the error persists, verify that no other backup software (like Veeam or Azure Backup agents) is “stealing” the log chain by taking copy-only backups that corrupt the native sequence.
  • Check the msdb.dbo.backupset table to review the history of type (D for Full, L for Log) to ensure the sequence is intact.

Alternative or Verification Steps

  • Verify the Fix: Query sys.databases again; the log_reuse_wait_desc column should change from NOTHING to a normal state, and subsequent scheduled log backup jobs in the SQL Server Agent should report “Succeeded.”
  • Alternative Solution: If a Full Backup is too resource-intensive for the production window, you can temporarily switch the database to SIMPLE recovery model to clear the log, then switch it back to FULL and schedule a Full Backup during the next maintenance window.

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

Troubleshooting Guide: Error 4202 – BACKUP LOG Failure Due to Bulk Logged Changes and Unavailable Filegroups

Why This Error Happens

This error occurs because the database uses the Bulk-Logged recovery model and minimally logged operations (such as BULK INSERT, SELECT INTO, or index rebuilds) have modified extents on a filegroup that is currently offline, corrupted, or otherwise inaccessible. SQL Server 2025 requires read access to every data extent touched by bulk-logged operations when backing up the transaction log, because the log backup must capture the actual data pages rather than just log records. If even one filegroup containing bulk-logged changes cannot be read, the entire log backup operation is blocked to prevent an inconsistent or unrecoverable backup chain.

Step-by-Step Resolution Guide

Step 1: Identify the Unavailable Filegroup

  • Run the following query to check filegroup and file status:
  • SELECT name, state_desc, physical_name FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Look for any file with a state_desc value other than ONLINE (e.g., OFFLINE, RECOVERY_PENDING, or SUSPECT).
  • Cross-reference the physical file path to confirm it exists on disk at the expected location (e.g., D:\SQLData\YourDB_FG2.ndf).

Step 2: Restore or Reconnect the Missing File

  • If the underlying disk or volume was disconnected, reattach the storage in Windows Server 2025 Disk Management and verify drive letter consistency.
  • If the file is corrupted or missing, restore it from the most recent full or differential backup using:
  • RESTORE DATABASE YourDatabaseName FILE = 'YourDB_FG2' FROM DISK = 'E:\Backups\YourDB_Full.bak' WITH NORECOVERY;
  • Apply any subsequent differential or log backups in sequence to bring the filegroup back online.

Step 3: Bring the Filegroup Back Online

  • Once files are restored, run ALTER DATABASE YourDatabaseName SET ONLINE; if the entire database was marked offline.
  • For a single filegroup, use ALTER DATABASE YourDatabaseName MODIFY FILEGROUP YourDB_FG2 ONLINE; if supported for your edition.
  • Confirm the filegroup state has changed by re-running the sys.master_files query from Step 1.

Step 4: Switch to FULL Recovery Model (If Bulk-Logged Is Not Required)

  • Open SQL Server Management Studio (SSMS) and right-click the database, then select Properties > Options.
  • Change the Recovery Model from “Bulk-logged” to “Full” to prevent future occurrences tied to minimally logged operations.
  • Alternatively, run: ALTER DATABASE YourDatabaseName SET RECOVERY FULL;

Step 5: Retry the Log Backup

  • Execute the log backup command once all filegroups report ONLINE:
  • BACKUP LOG YourDatabaseName TO DISK = 'E:\Backups\YourDB_Log.trn';
  • Confirm the backup completes without raising Error 4202 again.

Alternative or Verification Steps

  • Verify success by querying sys.databases and confirming log_reuse_wait_desc no longer shows LOG_BACKUP and the database state is ONLINE for all files.
  • If the filegroup cannot be recovered (e.g., permanent hardware failure), take a full database backup immediately after switching to the Full recovery model, since the broken log chain will require a fresh backup baseline before log backups can resume.

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

Troubleshooting Guide: SQL Server Error 4208 — “Statement Not Allowed While Recovery Model is SIMPLE”

Why This Error Happens

This error occurs because the database’s recovery model is set to SIMPLE, which automatically truncates the transaction log after each checkpoint and does not support log backups. Statements such as BACKUP LOG or operations relying on log chain continuity (like certain Always On, log shipping, or point-in-time restore configurations) require either the FULL or BULK_LOGGED recovery model to function. This mismatch typically happens when a database was created with default settings, restored from a SIMPLE-model backup, or manually changed by an administrator unaware of downstream dependencies.

Step-by-Step Resolution Guide

Step 1: Verify the Current Recovery Model

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check the current setting:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm the recovery_model_desc column returns SIMPLE.

Step 2: Change the Recovery Model to FULL or BULK_LOGGED

  • Execute the ALTER DATABASE command to switch the model:
  ALTER DATABASE [YourDatabaseName] SET RECOVERY FULL;
  • Use BULK_LOGGED instead if the workload involves frequent minimally logged bulk operations:
  ALTER DATABASE [YourDatabaseName] SET RECOVERY BULK_LOGGED;
  • Ensure you have ALTER permission on the database (sysadmin or db_owner role required).

Step 3: Take a Full Database Backup Immediately

  • Switching to FULL recovery does not start the log chain until a full backup is taken.
  • Run the following in SSMS or via T-SQL:
  BACKUP DATABASE [YourDatabaseName] 
  TO DISK = 'C:\SQLBackups\YourDatabaseName_Full.bak' 
  WITH INIT, COMPRESSION;
  • Confirm the backup file is created at C:\SQLBackups\ (adjust path based on your Windows Server 2025 storage configuration).

Step 4: Enable Scheduled Transaction Log Backups

  • Since FULL recovery requires regular log backups to prevent uncontrolled log growth, configure a SQL Server Agent Job.
  • Open SQL Server Agent → Jobs → New Job, and schedule:
  BACKUP LOG [YourDatabaseName] 
  TO DISK = 'C:\SQLBackups\YourDatabaseName_Log.trn';
  • Set the schedule interval (e.g., every 15–30 minutes) based on your Recovery Point Objective (RPO).

Alternative or Verification Steps

  • Re-run the original statement that triggered Error 4208 (e.g., BACKUP LOG) to confirm it now executes without error.
  • If switching the recovery model isn’t feasible due to business requirements, remain in SIMPLE mode and remove dependencies on log backups by using full/differential backups only for recovery planning.

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

Troubleshooting Guide: SQL Server Error 4199 — “Argument Value Invalid for Function Argument”

Why This Error Happens

Error 4199 occurs when a T-SQL function (commonly built-in functions like FORMAT, JSON_VALUE, STRING_SPLIT, or newer SQL Server 2025 vector/AI functions) receives a parameter that falls outside its accepted data type, range, or enumeration of valid values. This typically stems from application code passing malformed input, a mismatch between client driver versions and the new SQL Server 2025 function signatures, or corrupted/truncated data being fed into the function from an upstream source. It can also surface after an in-place upgrade where deprecated argument formats are no longer silently accepted.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Function and Query Triggering the Error

  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full error text, which names the specific function and argument position.
  • Enable SET XACT_ABORT ON and capture the failing query using Extended Events (xEvents) with the error_reported event filtered on error_number = 4199.
  • Cross-reference the query against recent application deployments or ORM-generated SQL.

Step 2: Validate Input Parameters Against Function Requirements

  • Review Microsoft’s updated SQL Server 2025 Books Online entry for the specific function to confirm valid argument ranges (many functions tightened validation in this release).
  • Manually test the function in SSMS with sanitized/hardcoded values to isolate whether the issue is the argument type (e.g., passing VARCHAR where INT is expected) or an out-of-range value (e.g., negative index in SUBSTRING).
  • Add explicit CAST or CONVERT statements in the application query to enforce correct data types before the value reaches the function.

Step 3: Update Client Drivers and Compatibility Level

  • Confirm the application is using the latest ODBC Driver 18+ or Microsoft.Data.SqlClient NuGet package, since legacy drivers may format function calls incompatible with SQL Server 2025’s stricter parser.
  • Check database compatibility level by running:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDBName';
  • If the database is running an older compatibility level (e.g., 140 or 150), consider testing at level 170 in a staging environment to align function behavior with SQL Server 2025 standards.

Step 4: Sanitize Upstream Data Sources

  • If the argument originates from an ETL pipeline, SSIS package, or external API, add validation logic (e.g., TRY_CONVERT or TRY_CAST) before the value is passed into the function.
  • Reject or default NULL, empty strings, or out-of-bound numeric values at the data ingestion layer rather than at the SQL function call.

Alternative or Verification Steps

  • Re-run the original failing query/stored procedure in SSMS against a test database to confirm the error no longer appears, and monitor the ERRORLOG for 24 hours to ensure no recurrence.
  • If the error persists after driver and data validation, temporarily wrap the function call in a TRY...CATCH block with ERROR_MESSAGE() logging to capture the exact invalid value in real time for deeper root-cause analysis.

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

Troubleshooting Guide: Error 4198 – Unicode-Only Collation in Partition Function Parameters

Why This Error Happens

This error occurs when a partition function is created or altered using a column or parameter defined with a Unicode-only collation (such as certain _SC supplementary character-aware collations or newer Unicode-exclusive collations introduced in SQL Server 2025). SQL Server restricts partition function parameters to collations that are valid across both Unicode (nvarchar/nchar) and non-Unicode (varchar/char) data types, since the internal boundary comparison logic requires compatibility with legacy data type storage. Essentially, the collation you selected for the partitioning column is too restrictive for how SQL Server internally evaluates partition boundaries.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Collation

  • Run the following query to inspect the partition function and its parameter data type/collation:
  SELECT pf.name AS PartitionFunctionName, 
         t.name AS DataType, 
         c.collation_name
  FROM sys.partition_functions pf
  JOIN sys.partition_parameters pp ON pf.function_id = pp.function_id
  JOIN sys.types t ON pp.system_type_id = t.system_type_id
  CROSS APPLY (SELECT name, collation_name FROM sys.columns WHERE system_type_id = pp.system_type_id) c;
  • Confirm whether the collation name contains _SC or references a Unicode-only collation (e.g., Japanese_XJIS_140_SC_UTF8 or similar UTF8-exclusive collations).

Step 2: Change the Column/Parameter to a Compatible Collation

  • Alter the underlying column to use a standard, non-Unicode-exclusive collation such as SQL_Latin1_General_CP1_CI_AS or Latin1_General_100_CI_AS_SC.
  • Example T-SQL fix:
  ALTER TABLE dbo.YourTable
  ALTER COLUMN PartitionColumn NVARCHAR(50) 
  COLLATE Latin1_General_100_CI_AS_SC;
  • Ensure this collation change is applied before re-attempting the CREATE PARTITION FUNCTION statement.

Step 3: Recreate the Partition Function

  • Drop the existing (failed or old) partition function if it exists:
  DROP PARTITION FUNCTION YourPartitionFunction;
  • Recreate it using the column with the updated, compatible collation:
  CREATE PARTITION FUNCTION YourPartitionFunction (NVARCHAR(50) COLLATE Latin1_General_100_CI_AS_SC)
  AS RANGE LEFT FOR VALUES ('A', 'M', 'Z');

Step 4: Validate Database and Server Collation Defaults

  • Check if the database-level default collation is also set to a Unicode-only collation using:
  SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Collation');
  • If necessary, update the database default collation via SQL Server Management Studio (SSMS) → Database Properties → Options tab, or run ALTER DATABASE ... COLLATE.

Alternative or Verification Steps

  • After recreating the partition function, run sys.partition_functions again to confirm no errors are thrown and the collation listed is no longer Unicode-exclusive.
  • If the issue persists, as a workaround, convert the partitioning column to a non-Unicode data type (VARCHAR instead of NVARCHAR) paired with a standard Windows collation, then rebuild all dependent indexes and partition schemes.

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

Troubleshooting Guide: SQL Server Error 4197 – Internal Query Compilation Error During Binding

Why This Error Happens

Error 4197 typically occurs when SQL Server’s query optimizer encounters an inconsistency while binding query elements to internal metadata structures, often triggered by corrupted query plans cached in the plan cache. This can also stem from outdated or malformed statistics on tables referenced in the query, causing the binder to fail when resolving column or object references. In some cases, this error surfaces due to incompatibilities introduced by recent cumulative updates or corrupted system catalog views after an in-place upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure Cache

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC FREEPROCCACHE; to clear potentially corrupted cached execution plans.
  • If the issue is isolated to a specific database, use DBCC FLUSHPROCINDB (<database_id>); instead for a more targeted flush.

Step 2: Update Statistics and Rebuild Indexes

  • Execute EXEC sp_updatestats; on the affected database to refresh outdated statistics.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption.
  • Rebuild indexes using ALTER INDEX ALL ON YourTableName REBUILD; for tables involved in the failing query.

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

  • Check your current version by running SELECT @@VERSION;.
  • 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 write access to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Restart the SQL Server service through services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 4: Isolate the Offending Query

  • Use SQL Server Profiler or Extended Events to capture the exact query triggering the binding error.
  • Simplify the query incrementally (remove joins, subqueries, or CTEs one at a time) to identify the specific clause causing the failure.
  • Check for recently altered views, functions, or computed columns referenced in the query, as schema drift is a common trigger.

Alternative or Verification Steps

  • Re-run the original failing query after completing Steps 1–3; if it executes without Error 4197, the plan cache corruption or statistics issue was the root cause.
  • If the error persists, open a case with Microsoft Support and provide the Extended Events trace from Step 4, as this may indicate a genuine optimizer bug requiring a hotfix.

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

Troubleshooting Guide: Error 4196 in Microsoft SQL Server 2025

Why This Error Happens

Error 4196 occurs because SQL Server does not permit the OUTPUT clause to reference a column whose value is derived from a window function (such as ROW_NUMBER(), RANK(), SUM() OVER(), or similar analytic expressions). This restriction exists because the OUTPUT clause captures row-level changes during DML operations (INSERT, UPDATE, DELETE), and window functions require a defined result set context that cannot be reliably evaluated at the exact moment a single row is modified. Essentially, the engine cannot guarantee the window function’s computed value is valid for the OUTPUT stream since the “window” of rows may change due to the very operation being performed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Definition

  • Locate the table or view definition referenced in the error message (the %ls.%.*ls placeholder will show the exact schema and column name in your actual error output).
  • Check if the column is a computed column defined with a window function, e.g., ALTER TABLE dbo.Sales ADD RowNum AS ROW_NUMBER() OVER (ORDER BY SaleID).
  • Run sp_helptext 'YourTableName' or query sys.computed_columns to confirm the expression.

Step 2: Remove the Window Function from the OUTPUT Clause

  • Rewrite your INSERT, UPDATE, or DELETE statement to exclude the specific computed column from the OUTPUT list.
  • Example fix: Change OUTPUT inserted.RowNum, inserted.SaleID to simply OUTPUT inserted.SaleID.
  • If you need the windowed value, calculate it separately after the DML operation completes using a standard SELECT statement with the window function applied to the final table state.

Step 3: Use a Temporary Table or Table Variable as a Workaround

  • If you require the OUTPUT data for further processing, redirect the output of the non-windowed columns into a temporary table first.
  • Syntax example: OUTPUT inserted.SaleID, inserted.Amount INTO #TempResults.
  • Once the DML transaction commits, run a secondary query against #TempResults or the base table to apply the window function logic (e.g., SELECT *, ROW_NUMBER() OVER (ORDER BY Amount) FROM #TempResults).

Step 4: Restart the Database Engine Service (If Schema Changes Were Made)

  • If you altered the computed column definition to remove the window function dependency, ensure the schema cache is refreshed.
  • Open Services.msc on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart to clear any cached execution plans referencing the old schema.

Alternative or Verification Steps

  • Verification: Re-run the original DML statement with the OUTPUT clause excluding the window-function-based column; if the statement executes without Error 4196, the fix is confirmed.
  • Alternative: If business logic strictly requires the ranked/aggregated value immediately, wrap the entire operation in a MERGE statement instead of INSERT/UPDATE, as MERGE sometimes allows restructuring the output logic via a subsequent CTE (Common Table Expression) pass rather than relying on the inserted/deleted virtual tables directly for computed window values.

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

Troubleshooting Guide: SQL Server Error 4194 – Invalid RANGE Window Frame Delimiter

Why This Error Happens

This error occurs when a T-SQL query uses a window function with a RANGE clause combined with offset-based frame delimiters (such as N PRECEDING or N FOLLOWING), which SQL Server does not support. SQL Server’s query optimizer strictly enforces that RANGE can only be paired with UNBOUNDED PRECEDING, UNBOUNDED FOLLOWING, or CURRENT ROW. This typically happens after migrating queries from another RDBMS (like PostgreSQL or Oracle) that permits more flexible RANGE syntax, or when a developer intends to use ROWS but mistakenly types RANGE instead.

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 located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025.
  • Look for the OVER() clause in the query containing a RANGE BETWEEN definition.
  • Confirm the frame delimiter uses a numeric offset, e.g., RANGE BETWEEN 3 PRECEDING AND CURRENT ROW.

Step 2: Replace RANGE with ROWS (Recommended Fix)

  • In most cases, the intended logic works correctly if you simply switch the keyword from RANGE to ROWS.
  • Update the query syntax: change RANGE BETWEEN 3 PRECEDING AND CURRENT ROW to ROWS BETWEEN 3 PRECEDING AND CURRENT ROW.
  • Re-run the query in SQL Server Management Studio (SSMS) or Azure Data Studio to confirm the syntax error (4194) is resolved.
  • Note: ROWS operates on physical row counts, while RANGE operates on logical value ranges, so verify the business logic still matches your requirements.

Step 3: Adjust Logic if Logical Range Behavior is Required

  • If you specifically need value-based range logic (not physical row counts), restructure the query to use UNBOUNDED PRECEDING and CURRENT ROW instead of a numeric offset.
  • Example valid syntax: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  • If a sliding numeric range is mandatory, consider refactoring the query using a self-join or APPLY operator to manually simulate the boundary logic.

Step 4: Update ORM or Migration Scripts

  • If the query was auto-generated by an ORM (Entity Framework, Hibernate) or migrated from another database engine, check the source mapping templates.
  • Search your codebase or migration scripts for .Range( or equivalent builder methods and patch the template to force ROWS generation for SQL Server targets.

Alternative or Verification Steps

  • Run the corrected query directly in SSMS connected to your SQL Server 2025 instance; a successful execution with a result set (rather than Error 4194) confirms the fix.
  • If the error persists, verify the SQL Server Compatibility Level of the database (right-click Database → Properties → Options) is set to 170 (SQL Server 2025) to ensure the latest window function parser logic is being used.

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

Troubleshooting Guide: SQL Server Error 4195 (NTILE Function Column Reference)

Why This Error Happens

Error 4195 occurs when a T-SQL query attempts to pass a column reference directly into the NTILE() function’s argument (the bucket count), which SQL Server’s query parser does not permit. The SQL Server 2025 engine requires the argument to NTILE to be a constant, a standalone scalar expression, a subquery, or a reference to a column from an outer query scope—not a direct column from the same row-level scope as the windowing function. This is a syntax/logic design limitation rather than a permissions or connectivity issue, and it typically surfaces after a schema change, a migrated query from an older SQL Server version, or a manually written dynamic bucket count.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Check the SQL Server error log via EXEC sp_readerrorlog; or Event Viewer under Applications and Services Logs > MSSQLSERVER on Windows Server 2025 to locate the exact statement and object (stored procedure, view, or function) referenced in the error text.
  • Note the specific column name mentioned in the error message (e.g., %.*ls will resolve to the actual column name like SalesAmount).

Step 2: Rewrite the NTILE Argument as a Variable or Constant

  • Replace the inline column reference inside NTILE(column_name) with a pre-declared variable or literal constant.
  • Example fix:
  DECLARE @BucketCount INT = 4;
  SELECT CustomerID, SalesAmount,
         NTILE(@BucketCount) OVER (ORDER BY SalesAmount) AS Quartile
  FROM Sales.Orders;
  • If the bucket count must be dynamic based on row data, populate the variable using a separate SELECT ... INTO @Variable statement before the main query.

Step 3: Use a Subquery or CTE for Correlated Values

  • If the column value is derived from another table or aggregate, wrap it in a subquery rather than referencing it inline.
  • Example:
  SELECT o.CustomerID, o.SalesAmount,
         NTILE((SELECT MAX(BucketConfig) FROM dbo.Config)) 
         OVER (ORDER BY o.SalesAmount) AS Quartile
  FROM Sales.Orders o;
  • Ensure the subquery returns a single scalar INT or BIGINT value to avoid a secondary type-conversion error.

Step 4: Update and Redeploy Stored Procedures/Views

  • Script out the affected stored procedure or view using sp_helptext 'ObjectName'.
  • Apply the corrected syntax from Steps 2–3 and redeploy using ALTER PROCEDURE or ALTER VIEW.
  • Clear the plan cache for that object with EXEC sp_recompile 'ObjectName'; to ensure SQL Server does not reuse a stale, invalid execution plan.

Alternative or Verification Steps

  • Run the corrected query in SSMS and confirm it executes without raising Error 4195; check the Messages tab for a clean “Command(s) completed successfully” result.
  • If the error persists in a legacy application connecting via an older OLE DB or ODBC driver, update the client driver (Microsoft OLE DB Driver 19+ for SQL Server) on the Windows 11 client machine, as older drivers sometimes mis-parse windowing function syntax before it reaches the server.

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

Troubleshooting Guide: SQL Server Error 4193 – Invalid Window Frame with OVER Clause

Why This Error Happens

This error occurs when a window function that does not support frame specifications (such as LAG, LEAD, NTILE, ROW_NUMBER, RANK, or DENSE_RANK) is incorrectly paired with a ROWS or RANGE clause inside the OVER() statement. SQL Server 2025’s query parser strictly validates frame compatibility at compile time, so even syntactically plausible frame definitions are rejected if the function itself is frame-insensitive. This is almost always a T-SQL authoring issue rather than a server configuration, permissions, or corruption problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query text from the error message or SQL Server error log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025).
  • Use SQL Server Management Studio (SSMS) or Azure Data Studio to re-run the query in isolation and confirm the error reproduces.
  • Note which window function is being used alongside the OVER() clause.

Step 2: Remove or Correct the Invalid Frame Clause

  • Check if the function is one of the ranking or offset functions: ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), LAG(), LEAD().
  • These functions do not accept ROWS BETWEEN ... AND ... or RANGE BETWEEN ... AND ...; remove the frame clause entirely.
  • Example fix:
  • Incorrect: SELECT LAG(SalesAmount) OVER (ORDER BY OrderDate ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM Sales;
  • Corrected: SELECT LAG(SalesAmount) OVER (ORDER BY OrderDate) FROM Sales;

Step 3: Validate Function Compatibility with Aggregate Window Functions

  • If you intended to use a moving aggregate (e.g., running total, moving average), switch to an aggregate function like SUM(), AVG(), MIN(), or MAX() which does support frame clauses.
  • Example: SELECT SUM(SalesAmount) OVER (ORDER BY OrderDate ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM Sales;
  • Confirm the PARTITION BY and ORDER BY clauses still meet your business logic requirements after the fix.

Step 4: Re-Deploy and Test the Corrected Query

  • Save the corrected stored procedure, view, or ad hoc script.
  • Recompile any dependent stored procedures using EXEC sp_recompile 'YourProcedureName';.
  • Re-run the query in SSMS to confirm no syntax or execution errors remain.

Alternative or Verification Steps

  • Run the query against a small test dataset and confirm it executes without Error 4193, then validate the returned result set matches expected business logic (e.g., correct lag/lead values or ranking order).
  • If the error persists in a complex query, use SET PARSEONLY ON; before running the batch to isolate pure syntax errors without full execution.

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

Troubleshooting Guide: SQL Server Error 4192 – Collation Conflict

Why This Error Happens

Error 4192 occurs when a query or operation attempts to compare, join, or concatenate text data from columns, databases, or temporary objects that use different collations, and SQL Server cannot implicitly determine which collation rules to apply. This typically happens when the server-level collation (set during installation) differs from the database-level collation, or when a query references tempdb objects while the user database uses a non-default collation. It can also arise after a migration or restore where source and destination instances were configured with mismatched collation settings.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Collations

  • Run the following query to check server, database, and column-level collations:
  SELECT SERVERPROPERTY('Collation') AS ServerCollation;
  SELECT name, collation_name FROM sys.databases;
  SELECT name, collation_name FROM sys.columns WHERE collation_name IS NOT NULL;
  • Note any discrepancies between the server default (often SQL_Latin1_General_CP1_CI_AS) and the database or column collations involved in the failing query.
  • Check the exact error message in SQL Server Management Studio (SSMS) or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER to identify which two collations are in conflict.

Step 2: Apply the COLLATE Clause to Force Resolution

  • Modify the offending query to explicitly cast the collation on one side of the comparison:
  SELECT * FROM TableA a
  JOIN TableB b
    ON a.ColumnX COLLATE DATABASE_DEFAULT = b.ColumnY COLLATE DATABASE_DEFAULT;
  • For temp table conflicts (a common cause since tempdb defaults to the server collation), explicitly define collation when creating the temp table:
  CREATE TABLE #TempTable (
      ColumnX NVARCHAR(100) COLLATE Latin1_General_CI_AS
  );
  • Save and re-run the query to confirm the error no longer appears.

Step 3: Align Database Collation with Server Collation (If Applicable)

  • If the conflict is systemic (affecting many queries), consider changing the database collation to match the server:
  ALTER DATABASE YourDatabaseName COLLATE SQL_Latin1_General_CP1_CI_AS;
  • Note: This only changes the default collation for new objects; existing columns must be altered individually:
  ALTER TABLE YourTable
  ALTER COLUMN YourColumn NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS;
  • Back up the database first using SSMS or BACKUP DATABASE before applying collation changes, as this is a schema-altering operation.

Step 4: Rebuild Instance-Level Collation (Last Resort)

  • If the server-level collation itself is incorrect for your organization’s needs, you may need to rebuild system databases using the setup.exe command-line utility with the /SQLCOLLATION switch:
  Setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=YourAdminAccount /SQLCOLLATION=Latin1_General_CI_AS
  • This action is destructive to master, model, msdb, and tempdb — ensure all user databases are backed up and scripts for logins/jobs are exported beforehand.

Alternative or Verification Steps

  • After applying fixes, re-run the original query or stored procedure that triggered Error 4192 and confirm it executes without the collation conflict message.
  • Use sys.fn_helpcollations() to list all valid collations on the instance and cross-reference them against your application’s expected locale settings to prevent recurrence.

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

Troubleshooting Guide: SQL Server Error 4191 — Collation Conflict

Why This Error Happens

This error occurs when a T-SQL operation (such as a UNION, JOIN, or comparison) references two or more character columns, variables, or expressions that have different collations, and SQL Server cannot implicitly determine which collation should take precedence. This is extremely common in environments where a database’s collation differs from the instance-level default collation, or when linked servers/temp tables (tempdb) use a different collation than the user database. It can also surface after migrating databases between servers configured with different language/locale settings during SQL Server 2025 setup.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Objects and Their Collations

  • Run the following query to check collation settings at multiple levels:
  SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Collation') AS DBCollation;
  SELECT SERVERPROPERTY('Collation') AS ServerCollation;
  • For the specific columns involved in the failing query, run:
  SELECT name, collation_name 
  FROM sys.columns 
  WHERE object_id = OBJECT_ID('YourTableName');
  • Note any mismatches between ServerCollation, DBCollation, and individual column collations.

Step 2: Apply the COLLATE Clause to Force Consistency

  • Modify the offending query to explicitly cast both sides of the comparison/join to the same collation using the COLLATE keyword.
  • Example fix:
  SELECT a.col1 
  FROM TableA a
  JOIN TableB b 
    ON a.col1 COLLATE DATABASE_DEFAULT = b.col1 COLLATE DATABASE_DEFAULT;
  • For a more permanent fix, alter the column’s collation directly:
  ALTER TABLE TableName 
  ALTER COLUMN ColumnName NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS;

Step 3: Check tempdb Collation Alignment

  • If the error involves temp tables (#TempTable), verify that tempdb is using the same collation as your user database, since tempdb defaults to the instance collation.
  • Navigate to SQL Server Configuration Manager on Windows Server 2025/Windows 11, locate the instance properties, and confirm the server-level collation under Advanced settings.
  • If a mismatch exists, rebuild the instance collation using the command line (requires service restart):
  Setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=YourAdminAccount /SQLCOLLATION=SQL_Latin1_General_CP1_CI_AS

Step 4: Restart SQL Server Service and Validate

  • Open Services.msc on Windows Server 2025, locate SQL Server (MSSQLSERVER), and restart the service to ensure all cached execution plans are cleared.
  • Re-run the original query that triggered Error 4191 to confirm resolution.

Alternative or Verification Steps

  • Verify the fix by executing DBCC FREEPROCCACHE; to clear cached query plans, then re-run the original problematic query to ensure Error 4191 no longer appears.
  • As an alternative, if altering column collations is not feasible due to application dependencies, wrap all cross-database or cross-table string comparisons in COLLATE DATABASE_DEFAULT directly within views or stored procedures to normalize behavior without schema changes.

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

Troubleshooting Guide: SQL Server Error 4190 – PIVOT Operator Not Allowed in Recursive CTE

Why This Error Happens

This error occurs because SQL Server’s query engine enforces strict syntactical limitations on recursive Common Table Expressions (CTEs) to prevent infinite execution loops and ambiguous result-set shapes. The PIVOT operator dynamically transforms rows into columns, which conflicts with the engine’s requirement that the recursive member of a CTE must have a schema (column count and type) that is deterministic and matches the anchor member exactly. Since PIVOT operations can alter the column structure unpredictably between recursive iterations, SQL Server 2025 blocks this operation specifically within the recursive part of the query to maintain query plan stability.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic Query Segment

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the specific CTE referenced in the error message ‘%.*ls’.
  • Isolate the recursive member (the part of the UNION ALL statement that references the CTE name itself).
  • Confirm that a PIVOT clause is applied directly within this recursive SELECT statement.

Step 2: Restructure the Query Using a Non-Recursive Pre-Processing Step

  • Move the PIVOT logic out of the recursive CTE and into a separate, non-recursive CTE or a temporary table.
  • Create a staging temporary table (e.g., #StagingData) to hold the pivoted results before the recursion begins.
  • Example syntax adjustment: Run the PIVOT first to populate #StagingData, then reference #StagingData inside the UNION ALL recursive member instead of performing the pivot inline.

Step 3: Utilize CASE Statements as a PIVOT Alternative

  • If moving the logic to a temporary table is not feasible due to application architecture, replace the PIVOT operator with standard CASE WHEN statements.
  • Since CASE statements do not alter the underlying rowset mechanics in the same way PIVOT does, they are permitted within recursive anchors and members.
  • Rewrite the aggregation logic to manually transpose rows to columns using MAX(CASE WHEN [Column] = 'Value' THEN [Metric] END).

Step 4: Validate CTE Column Matching

  • Ensure that after removing the PIVOT operator, the column count and data types in the recursive member exactly match the anchor member.
  • Check for implicit conversion errors that may arise from replacing PIVOT with CASE statements, specifically regarding NULL handling in unmatched columns.

Alternative or Verification Steps

  • Verification: Execute the modified query in a test environment and check the “Messages” tab in SSMS for the absence of Error 4190; confirm the result set returns the expected transposed columns.
  • Alternative: If complex pivoting logic is required, consider using a standard recursive CTE to generate the hierarchical/recursive dataset first, and apply the PIVOT operator to the final result set outside the CTE (in the main outer query) rather than inside the recursive loop.

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

Troubleshooting Guide: SQL Server Error 4189 — Legacy LOB Type Encoding Conflict

Why This Error Happens

This error occurs because SQL Server 2025 attempts to apply a UTF-8 or UTF-16 collation to a legacy Large Object (LOB) column of type text or ntext. These deprecated data types were architecturally never updated to support variable-width Unicode encodings like UTF-8, as they rely on older fixed-width storage mechanisms. Consequently, when a database or column-level collation change triggers an implicit conversion on these old types, the engine blocks the operation to prevent data corruption.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Columns and Collation

  • Run a metadata query to find every instance of text or ntext in your schema, as these are the root cause.
  • Use the following T-SQL to scan your current database:
SELECT t.name AS TableName, c.name AS ColumnName, ty.name AS DataType
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.types ty ON c.user_type_id = ty.user_type_id
WHERE ty.name IN ('text', 'ntext');
  • Note the specific UTF-8 collation (e.g., Latin1_General_100_CI_AS_SC_UTF8) you are trying to apply, as this is likely the trigger.

Step 2: Migrate Legacy Columns to Modern Types

  • Alter the table schema to replace the legacy types with their modern, UTF-8 compatible equivalents.
  • For text columns, convert to varchar(max).
  • For ntext columns, convert to nvarchar(max).
  • Execute the alteration via SSMS or command line:
ALTER TABLE YourTableName
ALTER COLUMN YourColumnName VARCHAR(MAX);
  • Ensure no active triggers or replication jobs are locking the table during this schema change on Windows Server 2025.

Step 3: Re-apply the Collation Change

  • Once the schema conversion is complete, re-run the original command that triggered the error (e.g., ALTER DATABASE... COLLATE or ALTER TABLE... COLLATE).
  • Verify there are no remaining dependencies, such as Full-Text Indexes, pointing to the old LOB columns before proceeding.
  • If a Full-Text Index exists, you must drop it temporarily using DROP FULLTEXT INDEX ON YourTableName before altering the column type, then recreate it post-migration.

Step 4: Restart the SQL Server Service

  • Navigate to the Services manager on Windows Server 2025 (services.msc) to clear any cached execution plans referencing the old schema.
  • Restart the “SQL Server (MSSQLSERVER)” service to ensure the Database Engine recognizes the new column definitions globally.

Alternative or Verification Steps

  • Verification: Re-run the metadata query from Step 1; if the result set is empty, no legacy LOB types remain, and the collation change should succeed without Error 4189.
  • Alternative: If altering the column directly causes constraint violations, create a new varchar(max) column, migrate the data using an UPDATE statement, drop the old text column, and rename the new column to match the original name.

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

Troubleshooting Guide: SQL Server Error 4187

Why This Error Happens

This error occurs when a variable declared in T-SQL code has a data type with insufficient precision, scale, or storage capacity to hold the value being retrieved from a table column. Common root causes include assigning an NVARCHAR or DECIMAL column to a variable declared as VARCHAR or a smaller DECIMAL precision, or fetching a BIGINT column into an INT variable. SQL Server 2025 enforces strict type-safety checks during assignment operations (such as SELECT INTO, cursor FETCH INTO, or direct variable assignment) to prevent silent truncation or rounding that could corrupt data integrity.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Column and Variable

  • Open the stored procedure, function, or script referenced in the error message.
  • Note the exact column name ‘%.*ls’ provided in the error text — this pinpoints the source column.
  • Run the following query to inspect the column’s actual data type and size:
  SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME = 'YourColumnName';

Step 2: Correct the Variable Declaration

  • Locate the DECLARE statement for the offending variable in your script.
  • Update the variable’s data type to match or exceed the source column’s capacity.
  • Example fix: Change DECLARE @Price DECIMAL(5,2) to DECLARE @Price DECIMAL(10,4) if the column requires higher precision.
  • For string types, ensure VARCHAR(50) is upgraded to VARCHAR(255) or NVARCHAR(MAX) if the source column uses extended Unicode or longer lengths.

Step 3: Use Explicit Casting as a Temporary Workaround

  • If modifying the variable type is not immediately feasible, wrap the column reference in an explicit CAST or CONVERT function to force truncation intentionally.
  • Example: SET @Variable = CAST(ColumnName AS VARCHAR(50)).
  • Note: This suppresses the error but may cause silent data loss, so use only as a short-term patch.

Step 4: Deploy and Test in a Non-Production Environment

  • Save the updated script and deploy it to a Windows Server 2025 test instance running SQL Server 2025.
  • Execute the procedure manually via SQL Server Management Studio (SSMS) to confirm the error no longer triggers.
  • Check the SQL Server Error Log (Management > SQL Server Logs in SSMS) to confirm Error 4187 no longer appears during execution.

Alternative or Verification Steps

  • Run the corrected stored procedure or script in SSMS and confirm it executes without raising Error 4187, then validate the output data matches expected source values exactly (no truncated strings or rounded numbers).
  • If the error persists across multiple objects, consider auditing the entire schema using sp_help 'TableName' to standardize variable declarations against a consistent data dictionary, preventing recurrence in future development.

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

Troubleshooting Guide: SQL Server Error 4188 — Legacy LOB Types Do Not Support UTF-8/UTF-16 Encodings

Why This Error Happens

This error occurs because a column, variable, or parameter is defined using a legacy large object (LOB) type—such as text, ntext, or image—while simultaneously being assigned a UTF-8 or UTF-16 collation (such as Latin1_General_100_CI_AS_SC_UTF8 or any UTF-16 enabled collation). SQL Server 2025 enforces stricter validation against deprecated LOB types because they lack the internal storage structure needed to handle variable-width Unicode encodings correctly. Since Microsoft has deprecated text/ntext/image in favor of varchar(max), nvarchar(max), and varbinary(max), the engine blocks this type-collation combination to prevent data corruption or truncation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column or Parameter

  • Run the failing query or stored procedure in SQL Server Management Studio (SSMS) to capture the exact error text, which includes the column/parameter name and collation.
  • Use the following query to scan your database for legacy LOB columns:
  SELECT t.name AS TableName, c.name AS ColumnName, ty.name AS DataType, c.collation_name
  FROM sys.columns c
  JOIN sys.tables t ON c.object_id = t.object_id
  JOIN sys.types ty ON c.user_type_id = ty.user_type_id
  WHERE ty.name IN ('text', 'ntext', 'image');
  • Note every instance where collation_name contains UTF8 or is a UTF-16 scoped collation.

Step 2: Alter the Column to a Modern LOB Type

  • Convert text columns to varchar(max), ntext to nvarchar(max), and image to varbinary(max).
  • Execute an ALTER TABLE statement, for example:
  ALTER TABLE dbo.YourTable
  ALTER COLUMN YourColumn varchar(max) COLLATE Latin1_General_100_CI_AS_SC_UTF8;
  • If the column is used in a stored procedure or function parameter, update the CREATE PROCEDURE or CREATE FUNCTION definition to use varchar(max)/nvarchar(max) instead of the legacy type.

Step 3: Update Application and ORM Mappings

  • Check connection strings and ORM models (Entity Framework, Dapper, etc.) for any explicit mapping to SqlDbType.Text, SqlDbType.NText, or SqlDbType.Image.
  • Change these mappings to SqlDbType.VarChar or SqlDbType.NVarChar with MaxLength = -1 (which maps to MAX).
  • Redeploy or restart the application pool (IIS) or service on Windows Server 2025/Windows 11 to ensure the updated schema metadata is cached correctly.

Step 4: Rebuild Dependent Indexes and Statistics

  • Since altering LOB column types can invalidate full-text indexes or statistics tied to the old type, rebuild them:
  ALTER FULLTEXT INDEX ON dbo.YourTable START FULL POPULATION;
  UPDATE STATISTICS dbo.YourTable;
  • Confirm no other dependent views, triggers, or computed columns still reference the legacy type by querying sys.sql_expression_dependencies.

Alternative or Verification Steps

  • Re-run the original failing query/procedure after the schema change; Error 4188 should no longer appear, and data should insert/select without encoding warnings.
  • If altering the column directly is not feasible (e.g., due to replication or legacy app constraints), create a new varchar(max)/nvarchar(max) column, migrate the data using UPDATE ... SET NewColumn = CAST(OldColumn AS varchar(max)), then drop the old column and rename the new one.

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

Troubleshooting Guide: SQL Server Error 4186 (OUTPUT Clause Column Reference)

Why This Error Happens

This error occurs because SQL Server cannot guarantee deterministic behavior for the OUTPUT clause when a referenced column is derived from a computed column definition that calls a function. By default, SQL Server assumes any function not marked as “schemabound” performs data access (reading from tables), which makes the resulting value unsafe to capture in an OUTPUT clause during an INSERT, UPDATE, or DELETE operation. Essentially, the engine refuses to reference the column because it cannot verify at compile-time whether the underlying function will return consistent results outside of its original query context.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Computed Column

  • Query the system catalog to find the exact definition of the computed column causing the issue.
  • Run the following T-SQL to inspect definitions:
SELECT name, definition 
FROM sys.computed_columns 
WHERE object_id = OBJECT_ID('YourTableName');
  • Note the specific user-defined function (UDF) being called within that column’s expression.

Step 2: Schema-Bind the Underlying Function

  • Modify the T-SQL function used in the computed column to include the WITH SCHEMABINDING option. This explicitly tells the optimizer the function does not access external data, provided it genuinely doesn’t.
  • Example fix for the function definition:
ALTER FUNCTION dbo.YourFunctionName()
RETURNS INT
WITH SCHEMABINDING 
AS
BEGIN
    RETURN 1; -- Ensure no table references exist unless schema-bound
END;
  • Ensure the function strictly adheres to deterministic logic to pass the schema-binding validation.

Step 3: Modify the DML Statement to Bypass the Restriction

  • If schema-binding the function is not feasible (e.g., it legitimately needs to access other tables), refactor your query to avoid referencing the specific computed column directly in the OUTPUT clause.
  • Instead of outputting the computed column directly, insert into a temporary table or table variable using the OUTPUT INTO clause, referencing only the “inserted” base columns required for the primary key.
DECLARE @OutputTable TABLE (ID INT);

INSERT INTO YourTable (Col1, Col2)
OUTPUT inserted.ID INTO @OutputTable
VALUES (1, 2);

Step 4: Restart Services and Clear Plan Cache

  • Once schema changes are applied, restart the SQL Server service to ensure no stale execution plans are cached.
  • Open Services.msc on Windows Server 2025, locate SQL Server (MSSQLSERVER), and select Restart.
  • Alternatively, clear the specific plan cache via T-SQL: DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Verify the Fix: Re-run the original INSERT/UPDATE statement with the OUTPUT clause; the query should execute successfully without throwing Error 4186.
  • Alternative Check: If the error persists, query sys.sql_modules to confirm the is_schema_bound flag is set to 1 for the specific function, ensuring the metadata update was successfully applied.

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

Troubleshooting Guide: SQL Server Error 4185 – “This action cannot be performed on a system type”

Why This Error Happens

Error 4185 occurs when a user or application attempts to execute an action—such as ALTER, DROP, or modifying properties—on a system-defined data type or system object that SQL Server protects from direct manipulation. This typically happens when scripts or migration tools mistakenly target system types (like sys.types entries) instead of user-defined types (UDTs), or when deployment packages generated for one database are replayed against system catalogs. Corrupted or outdated DACPAC/BACPAC files and third-party ORM tools that auto-generate schema scripts are common triggers for this conflict in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object

  • Open SQL Server Management Studio (SSMS) and run the following query to confirm whether the target object is a system type:
  SELECT name, is_user_defined FROM sys.types WHERE name = 'YourTypeName';
  • If is_user_defined = 0, this confirms the object is a protected system type and cannot be altered directly.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact timestamp and query context tied to Error 4185.

Step 2: Correct the Script or Deployment Package

  • If using SSDT or Visual Studio Database Projects, review the .sql deployment script for any ALTER TYPE or DROP TYPE statements referencing base types (e.g., int, varchar, sysname).
  • Edit the script to target only user-defined types, typically prefixed or stored under a custom schema (e.g., dbo.MyCustomType).
  • If the issue stems from a DACPAC, regenerate it using:
  SqlPackage.exe /Action:Extract /SourceConnectionString:"Server=localhost;Database=YourDB;Integrated Security=true" /TargetFile:"C:\Temp\YourDB.dacpac"

Step 3: Validate Permissions and Ownership

  • Ensure the executing login does not have elevated rights (like sysadmin) that might allow partial execution against system catalogs, masking the real intent of the failing script.
  • Run the following to check type ownership:
  SELECT t.name, s.name AS SchemaOwner 
  FROM sys.types t
  JOIN sys.schemas s ON t.schema_id = s.schema_id
  WHERE t.name = 'YourTypeName';
  • Reassign ownership if the user-defined type was mistakenly created in the sys or dbo system-reserved namespace.

Step 4: Re-run the Operation in Isolation

  • Isolate the failing statement and test it independently in a new query window against a non-production database copy.
  • Use SET NOEXEC ON; before execution to validate syntax without committing changes, then toggle SET NOEXEC OFF; once confirmed safe.

Alternative or Verification Steps

  • Verification: Re-run the original deployment or migration script. If successful, query sys.messages for Error 4185 to confirm no new occurrences are logged in the SQL Server Error Log.
  • Alternative Fix: If the error persists during automated CI/CD deployments, bypass the conflict by explicitly excluding system schema comparisons in your DACPAC publish profile by setting ExcludeObjectTypes=Types in the .publish.xml configuration file.

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

Why This Error Happens

This error occurs because SQL Server maintains an internal snapshot of a table’s schema (including filtered indexes and filtered statistics) while a query compiles and executes its execution plan. When concurrent DDL operations—such as rapid ALTER TABLE, index rebuilds, or statistics updates—modify the schema while the optimizer is still trying to resolve the filtered index predicate, SQL Server cannot guarantee a consistent read and aborts the operation. This is especially common in high-concurrency OLTP environments where automated maintenance jobs or application logic issue frequent schema-altering statements against tables with filtered indexes.

Step-by-Step Resolution Guide

Step 1: Identify the Source of Frequent Schema Changes

  • Query sys.dm_exec_query_stats and sys.dm_os_wait_stats to correlate the error timestamp with recent DDL activity.
  • Check SQL Server Agent job history and any application-level migration scripts for repeated ALTER TABLE, CREATE/DROP INDEX, or UPDATE STATISTICS calls on the affected table.
  • Use Extended Events (sqlserver.object_altered) to capture a live trace of schema modification events in real time.

Step 2: Reduce or Batch Schema Alteration Frequency

  • Consolidate repeated ALTER TABLE statements into a single batch operation instead of looping per-row or per-transaction changes.
  • If an ORM or application layer is dynamically altering schema (e.g., adding columns per request), refactor the logic to perform schema changes during a maintenance window only.
  • Disable or reschedule automated statistics/index maintenance jobs (in SQL Server Agent or Maintenance Plans) so they do not overlap with peak query traffic.

Step 3: Review and Optimize Filtered Indexes/Statistics

  • Run sp_helpindex 'TableName' to list all filtered indexes and evaluate whether each is still necessary.
  • Drop redundant filtered indexes using DROP INDEX IndexName ON TableName; if they are not actively improving query performance.
  • Recreate essential filtered indexes with CREATE INDEX ... WHERE clauses only after confirming the underlying query patterns genuinely benefit from filtering.

Step 4: Apply Cumulative Updates and Configuration Checks

  • Ensure Windows Server 2025 / Windows 11 and SQL Server 2025 are patched with the latest Cumulative Update (CU) from the Microsoft Update Catalog, as this specific concurrency issue has known fixes in recent builds.
  • Verify MAXDOP and Cost Threshold for Parallelism settings in SQL Server Management Studio (SSMS) under Server Properties > Advanced are tuned to reduce plan recompilation pressure.

Alternative or Verification Steps

  • Re-run the original failing query immediately after reducing DDL frequency; if it completes without Error 4184, the schema contention has been resolved.
  • As a temporary workaround, wrap the query in a retry loop with TRY...CATCH and a short WAITFOR DELAY '00:00:01' to handle transient schema-locking conflicts until the root cause (excessive DDL) is fully remediated.

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

Troubleshooting Guide: Error 4177 — “The FROM Clause of a PROB_MATCH Query Must Consist of a Single Derived Table”

Why This Error Happens

This error occurs when a PROB_MATCH function call (used in SQL Server’s Fuzzy Grouping/Probabilistic Matching functionality) is executed against a FROM clause that references multiple tables, joins, or raw table references instead of a single, properly wrapped derived table. SQL Server’s query optimizer requires the matching engine to operate on one consolidated result set so it can correctly compute similarity scores and internal indexing structures. This typically happens due to manually written T-SQL queries that bypass the SSIS Fuzzy Lookup/Fuzzy Grouping transformation wizard, or due to corrupted/malformed query templates generated by third-party ETL tools on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and locate the query triggering Error 4177, usually found in SSIS package logs at C:\Program Files\Microsoft SQL Server\160\DTS\Log.
  • Check the FROM clause for multiple comma-separated tables, explicit JOIN statements, or multiple subqueries at the top level.
  • Confirm the error context using sys.dm_exec_requests to pinpoint the exact session ID running the PROB_MATCH operation.

Step 2: Wrap the Query into a Single Derived Table

  • Rewrite the query so that all joins, filters, and unions are nested inside one outer SELECT * FROM (...) AS DerivedTable.
  • Example correction:
  SELECT * FROM (
      SELECT a.CustomerName, b.Address
      FROM dbo.Customers a
      INNER JOIN dbo.AddressBook b ON a.CustomerID = b.CustomerID
  ) AS SourceData
  • Ensure the derived table has a valid alias (e.g., AS SourceData) — PROB_MATCH will fail silently or throw 4177 again if the alias is missing.

Step 3: Update SSIS Fuzzy Grouping/Lookup Transformation Settings

  • Open the SSIS package in Visual Studio 2022 (with SQL Server Data Tools for SQL Server 2025 installed).
  • Double-click the Fuzzy Grouping or Fuzzy Lookup transformation and verify the Reference Table dropdown points to a single view or derived table, not a multi-table join defined inline.
  • If using a custom SQL statement, paste the corrected single-derived-table query from Step 2 into the “Use a query to generate matching table” field.

Step 4: Rebuild and Validate the Execution Plan

  • Clear the cached execution plan using:
  DBCC FREEPROCCACHE;
  • Re-run the query in SSMS to confirm SQL Server 2025 accepts the single derived table structure without throwing Error 4177.
  • Check the Query Store (Object Explorer > Databases > [YourDB] > Query Store) to confirm the new plan is cached correctly.

Alternative or Verification Steps

  • Run the corrected query independently in a new SSMS query window and confirm it returns results without error before re-integrating it into the SSIS package.
  • If the error persists, create a Database View encapsulating the join logic (CREATE VIEW vw_MatchSource AS ...) and reference that view directly in the PROB_MATCH call instead of an inline derived table.

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

Troubleshooting Guide: Error 4176 — Too Many Parameters Specified for FULLTEXTTABLE of Type “Simple”

Why This Error Happens

This error occurs when a CONTAINSTABLE or FREETEXTTABLE query passes more search parameters than the Full-Text Engine’s “Simple” predicate type allows, typically because the query exceeds the internal parameter limit defined by SQL Server’s full-text search architecture. It is commonly triggered by dynamically generated queries that concatenate an excessive number of search terms, columns, or weighted conditions into a single FULLTEXTTABLE call. In some cases, this also surfaces after upgrading to SQL Server 2025 if legacy applications were built against older full-text parameter thresholds that have since changed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the exact query from the application log or SQL Server error log that triggered Error 4176.
  • Check the number of parameters passed inside the CONTAINSTABLE() or FREETEXTTABLE() function call.
  • Use SQL Server Profiler or Extended Events to capture the full query text if it’s generated dynamically by an application.

Step 2: Reduce the Parameter Count in the Query

  • Break large search term lists into smaller batches (e.g., groups of 10-20 terms per call) and execute multiple FULLTEXTTABLE queries, then UNION the results.
  • Simplify weighted terms by combining synonyms or near-duplicate search conditions into fewer OR-based clauses.
  • Avoid dynamically appending user-supplied search terms without a server-side cap; enforce a maximum term limit in application code (e.g., in C# or application middleware) before the query reaches SQL Server.

Step 3: Adjust Full-Text Search Configuration

  • Open SQL Server Configuration Manager and verify the Full-Text Filter Daemon Launcher (MSSQLFDLauncher) service is running under Windows Server 2025.
  • Run EXEC sp_fulltext_service 'verify_signature', 0; in SSMS if signature verification is interfering with filter loading (test in a non-production environment first).
  • Rebuild the full-text catalog if parameter handling appears corrupted:
  ALTER FULLTEXT CATALOG YourCatalogName REBUILD;

Step 4: Update SQL Server 2025 Cumulative Updates

  • Navigate to the Microsoft Update Catalog and check for the latest Cumulative Update (CU) for SQL Server 2025, since parameter-handling limits for FULLTEXTTABLE have been adjusted in past CUs.
  • Install the update via Setup.exe /ACTION=Patch /IAcceptSQLServerLicenseTerms /Quiet in an elevated PowerShell session on Windows Server 2025.
  • Restart the SQL Server service (net stop MSSQLSERVER then net start MSSQLSERVER) after the patch completes.

Alternative or Verification Steps

  • Re-run the original query with a reduced parameter set and confirm Error 4176 no longer appears in the SSMS Messages tab or the SQL Server error log (Logs\ERRORLOG under the SQL Server install directory).
  • If the error persists, switch the query logic to use CONTAINSTABLE with the ISABOUT clause and explicit weighting, which handles large term sets more efficiently than the default “Simple” predicate type.

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

Troubleshooting Guide: Error 4175 — “Nested Updates Cannot Be Performed on CLR Types That Are Not Format.Structured”

Why This Error Happens

This error occurs when a CLR user-defined type (UDT) column is updated using a nested UPDATE syntax (e.g., UPDATE table.column.Mutator()) while the type itself is serialized using Format.Native or Format.UserDefined instead of Format.Structured. SQL Server 2025 requires structured format to support mutator methods and nested update operations because non-structured formats are treated as atomic binary blobs that cannot be partially modified in place. This typically stems from a CLR assembly or UDT definition that was built incorrectly, or a legacy assembly migrated from an older SQL Server version without updating its serialization attributes.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Type and Assembly

  • Run the following query to locate the type causing the issue:
  SELECT name, is_user_defined, is_binary_ordered 
  FROM sys.types 
  WHERE is_user_defined = 1;
  • Cross-reference the assembly backing the type using sys.assembly_types and sys.assemblies.
  • Confirm the type’s serialization format by inspecting the [Serializable] and SqlUserDefinedType attributes in the original C# or VB.NET source code.

Step 2: Modify the CLR Type Definition to Use Format.Structured

  • Open the source project for the UDT in Visual Studio 2026 (or your CLR development environment).
  • Update the attribute declaration on the class to explicitly set structured format:
  [Serializable]
  [SqlUserDefinedType(Format.Structured, 
      IsByteOrdered = true, 
      MaxByteSize = 8000)]
  public struct MyCustomType : INullable, IBinarySerialize
  • Ensure the type implements IBinarySerialize with proper Read and Write methods, as Format.Structured requires this interface for serialization control.
  • Rebuild the assembly as a .dll targeting .NET 9.0 (compatible with SQL Server 2025 CLR integration).

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

  • Disable CLR strict security checks temporarily if blocked by signing requirements:
  EXEC sp_configure 'clr strict security', 0;
  RECONFIGURE;
  • Drop the existing type and assembly:
  DROP TYPE dbo.MyCustomType;
  DROP ASSEMBLY MyAssembly;
  • Re-register the updated assembly:
  CREATE ASSEMBLY MyAssembly 
  FROM 'C:\CLR_Assemblies\MyAssembly.dll'
  WITH PERMISSION_SET = SAFE;

  CREATE TYPE dbo.MyCustomType 
  EXTERNAL NAME MyAssembly.[MyCustomType];
  • Restore clr strict security to its original value (typically 1) once registration succeeds.

Step 4: Rebuild Dependent Tables and Indexes

  • Any table columns referencing the old UDT must be altered or recreated to bind to the newly structured type.
  • Run DBCC CHECKDB against the affected database to confirm no corruption occurred during the type swap.
  • Rebuild clustered indexes on tables containing the UDT column to refresh internal metadata:
  ALTER INDEX ALL ON dbo.YourTable REBUILD;

Alternative or Verification Steps

  • Verify the fix by executing a nested update against the UDT column (e.g., UPDATE YourTable SET UdtColumn.MutatorMethod(value) WHERE Id = 1;) — it should complete without raising Error 4175.
  • If reworking the CLR assembly is not feasible, use a workaround by retrieving the full UDT value, modifying it in application code or T-SQL variables, and performing a full column replacement (UPDATE YourTable SET UdtColumn = @NewValue) instead of a nested mutator call.

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

Troubleshooting Guide: SQL Server Error 4174 — Delayed CLR Type Instantiation Fetch Value Query

Why This Error Happens

This error occurs when a query attempts to retrieve a value from a CLR user-defined type (UDT) or large object (LOB) column using delayed/lazy fetch semantics, but the underlying column reference does not resolve to a valid large value type at execution time. This typically happens due to a mismatch between the assembly’s serialization format (native vs. user-defined) and the column metadata stored in the database, often triggered after a CLR assembly update, an in-place upgrade to SQL Server 2025, or corrupted type metadata in the system catalog. It can also surface when a query plan caches a stale reference to a CLR type that has since been altered or dropped and recreated with different properties.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration and Assembly Status

  • Run SELECT * FROM sys.assemblies; to confirm the CLR assembly backing the UDT is marked as is_visible = 1 and not in a faulted state.
  • Check sp_configure 'clr enabled'; to ensure CLR integration is active (value should be 1).
  • Run ALTER ASSEMBLY <AssemblyName> WITH REBUILD; if the assembly shows signs of corruption or version mismatch.

Step 2: Clear and Rebuild the Query Plan Cache

  • Execute DBCC FREEPROCCACHE; to remove potentially stale execution plans referencing outdated CLR type metadata.
  • Run DBCC FREESYSTEMCACHE('ALL'); to flush system-level metadata caches tied to UDT definitions.
  • Re-run the failing query immediately after to see if the error persists with a freshly compiled plan.

Step 3: Recreate the CLR Type Column Reference

  • Identify the affected column using SELECT name, system_type_id, user_type_id FROM sys.columns WHERE user_type_id > 256; to isolate CLR-based columns.
  • Script out the table, drop the column referencing the CLR UDT, and recreate it using ALTER TABLE <TableName> ADD <ColumnName> <UDTName>; to force fresh metadata binding.
  • Reload or re-cast the data into the new column using UPDATE statements with explicit CONVERT or CAST operations.

Step 4: Update SQL Server 2025 Cumulative Package

  • Navigate to Windows Update or the SQL Server Installation Center on Windows Server 2025 / Windows 11 and check for the latest Cumulative Update (CU) under Microsoft SQL Server 2025 Setup.
  • Apply the update via Setup.exe /Action=Patch /IAcceptSQLServerLicenseTerms /Quiet from an elevated PowerShell session if deploying silently across multiple nodes.
  • Restart the SQL Server service (net stop MSSQLSERVER && net start MSSQLSERVER) after patching completes.

Alternative or Verification Steps

  • Re-run the original query with SET STATISTICS XML ON; to confirm the execution plan no longer references a broken CLR serialization path, and validate the result set returns the correct large value data.
  • If the error persists, isolate the issue by querying the UDT column in isolation (SELECT <Column>.ToString() FROM <Table>) rather than as part of a larger JOIN or computed expression, as this confirms whether the root cause is plan-level or assembly-level.

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

Troubleshooting Guide: SQL Server Error 4172 — “Incorrect Use of Full-Text %s”

Why This Error Happens

Error 4172 occurs when a Transact-SQL statement references a full-text search function (such as CONTAINS, FREETEXT, CONTAINSTABLE, or FREETEXTTABLE) with invalid syntax, an incorrect column reference, or against a table/column that is not properly enabled for full-text indexing. This typically happens when the full-text catalog or index is missing, disabled, corrupted, or when the query references a column not included in the full-text index definition. It can also occur if the full-text index population is incomplete or the underlying index has become inconsistent after a database upgrade or restore.

Step-by-Step Resolution Guide

Step 1: Verify the Full-Text Index Exists and Is Active

  • Run SELECT * FROM sys.fulltext_indexes WHERE object_id = OBJECT_ID('YourTableName'); to confirm an index exists on the target table.
  • Check the is_enabled column; if it returns 0, the full-text index is disabled.
  • Confirm the specific column used in your query (e.g., in CONTAINS(ColumnName, 'SearchTerm')) is actually part of the full-text index definition using sys.fulltext_index_columns.

Step 2: Validate Full-Text Query Syntax

  • Double-check that CONTAINS and FREETEXT are used with correct parameters: CONTAINS(column_name, '"search_term"').
  • Ensure you are not mixing CONTAINSTABLE/FREETEXTTABLE (which require a JOIN and return a table) with CONTAINS/FREETEXT (which are used in a WHERE clause).
  • Confirm wildcard searches use proper formatting, e.g., CONTAINS(column_name, '"server*"').

Step 3: Rebuild or Repopulate the Full-Text Catalog

  • Open SQL Server Management Studio (SSMS) and navigate to Database > Storage > Full Text Catalogs.
  • Right-click the relevant catalog and select Rebuild, or run:
  ALTER FULLTEXT CATALOG YourCatalogName REBUILD;
  • Follow with a full repopulation:
  ALTER FULLTEXT INDEX ON YourTableName START FULL POPULATION;
  • Monitor progress via SELECT * FROM sys.dm_fts_index_population;.

Step 4: Confirm the Full-Text Feature Is Installed

  • On Windows Server 2025 / Windows 11, open SQL Server Installation Center and verify “Full-Text and Semantic Extractions for Search” is installed under Database Engine Services.
  • If missing, re-run SQL Server 2025 Setup, select Add Features, and check the Full-Text component before completing installation.

Alternative or Verification Steps

  • Re-run the original query after rebuilding the index; if it executes without Error 4172, the fix was successful.
  • As an alternative, drop and recreate the full-text index from scratch using CREATE FULLTEXT INDEX ON YourTableName(ColumnName) KEY INDEX YourPrimaryKeyIndex; if rebuilding does not resolve the inconsistency.

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

Troubleshooting Guide: SQL Server Error 4173 — “Is Not a Valid Scoring Function Name”

Why This Error Happens

This error occurs when SQL Server 2025’s native scoring engine (used for PREDICT/scoring operations against ONNX or in-database ML models) cannot locate or validate the scoring function name referenced in a PREDICT statement or a model’s metadata. This typically happens due to a typo or case-sensitivity mismatch in the function name, a corrupted or incompatible model schema stored in the RxPredict/native scoring catalog, or missing registration of the scoring function after a model import. It can also surface after a failed or partial upgrade where the internal scoring function catalog became out of sync with the installed model binaries.

Step-by-Step Resolution Guide

Step 1: Validate the Scoring Function Name and Syntax

  • Open the query that raised the error and inspect the exact string passed to the PREDICT clause or scoring function parameter.
  • Confirm there are no leading/trailing spaces, incorrect casing, or special characters in the function name.
  • Cross-check the name against the list of valid scoring functions by running:
  SELECT name, scoring_function_type FROM sys.native_scoring_functions;

Step 2: Verify the Model and Function Registration

  • Check whether the model was registered correctly using sp_rxPredict or the native PREDICT model catalog:
  SELECT * FROM sys.models WHERE model_name = 'YourModelName';
  • If the function is missing or shows as NULL, re-import the model using:
  EXEC sp_rxPredict @model = @model_binary, @inputData = N'SELECT * FROM InputTable';
  • Ensure the model file (ONNX or PMML) was exported using a compatible version matching SQL Server 2025’s native scoring engine.

Step 3: Repair the Native Scoring Catalog

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and confirm the rxLibs and mlModelSvc.dll components are present and not flagged by antivirus/Windows Defender exclusions.
  • Restart the SQL Server Launchpad service via services.msc or:
  Restart-Service MSSQLLaunchpad
  • If the catalog remains corrupted, drop and recreate the model entry:
  DROP EXTERNAL MODEL [YourModelName];
  CREATE EXTERNAL MODEL [YourModelName] 
  FROM 'C:\Models\model.onnx' 
  WITH (FORMAT = 'ONNX');

Step 4: Apply the Latest Cumulative Update

  • Confirm you are running the latest SQL Server 2025 CU, as early releases had known native scoring catalog sync bugs.
  • Check your current build:
  SELECT @@VERSION;
  • Download and apply the latest CU from the Microsoft Update Catalog if your build number predates the fix.

Alternative or Verification Steps

  • Re-run the original PREDICT query after completing the steps above; the error should no longer appear, and results should return normally.
  • If the issue persists, enable extended events tracing (xe_store.scoring_errors) to capture the exact internal function lookup failure and compare against Microsoft’s native scoring function reference list for SQL Server 2025.

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

Troubleshooting Guide: Error 4171 – Alias Not Specified for Aggregate in PROB_MATCH SELECT List

Why This Error Happens

This error occurs because SQL Server 2025’s query parser requires every computed column or aggregate function (such as SUM(), COUNT(), AVG(), or the newer PROB_MATCH() fuzzy-matching aggregate) in a SELECT list to have an explicit column alias. Without a defined alias, the engine cannot generate a valid internal column name for the result set, especially when the aggregate is used inside a view, CTE, or subquery. This is commonly triggered when legacy queries or auto-generated scripts (from BI tools or migration utilities) are run against SQL Server 2025 without updating syntax to meet stricter ANSI compliance checks introduced in this version.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio and locate the exact query referenced in the Error 4171 message in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • Search specifically for instances of PROB_MATCH(...) in SELECT clauses without a trailing AS keyword.
  • Use the following command to pull recent error details if the query text isn’t visible in the client:
  SELECT * FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL);

Step 2: Apply an Explicit Alias to the Aggregate

  • Modify the T-SQL script to include an AS alias immediately following the PROB_MATCH function call.
  • Incorrect syntax (causes error):
  SELECT CustomerID, PROB_MATCH(Name, Address) FROM Staging.Customers;
  • Corrected syntax:
  SELECT CustomerID, PROB_MATCH(Name, Address) AS MatchScore FROM Staging.Customers;

Step 3: Update Views or Stored Procedures

  • If the error originates from a persisted object rather than an ad-hoc query, use ALTER VIEW or ALTER PROCEDURE to inject the alias permanently.
  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Stored Procedures in SSMS to locate and edit the specific object.
  • Save and recompile the object using EXEC sp_refreshsqlmodule 'YourViewName'; to clear any cached execution plans referencing the old syntax.

Step 4: Check for Linked Server or ETL Pass-Through Queries

  • If the query is generated dynamically by an external tool (e.g., SSIS, Power BI, or a custom .NET application), check the connection string or OLE DB provider settings for “pass-through” query generation.
  • Update the source application’s query builder logic to append aliases automatically, specifically looking in config files located at C:\Program Files\Microsoft SQL Server\160\DTS\Binn\ for SSIS packages.

Alternative or Verification Steps

  • Verification: Re-run the corrected query in SSMS; a successful execution with a populated MatchScore (or equivalent) column header confirms the fix.
  • Alternative: If modifying the alias is not immediately possible due to third-party software restrictions, wrap the entire query in a derived table/subquery and alias the column at the outer level: SELECT T.*, T.Col1 AS Alias1 FROM (SELECT PROB_MATCH(...) AS Col1 FROM Table) AS T;.

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

Why This Error Happens

Error 4170 occurs when a Transact-SQL query attempts to use the ANY, SOME, or ALL keyword against an expression that is not a valid subquery result set (a “multiset”). This typically happens when a developer uses ANY/SOME with a scalar subquery, a comma-separated list, or a malformed subquery that SQL Server 2025’s parser cannot resolve into a row-set. It is a query construction issue rather than a server configuration or permissions problem, meaning the fix lies entirely within the T-SQL code itself.

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 Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • Look specifically for WHERE column = ANY (...) or = SOME (...) clauses.
  • Confirm whether the parenthetical expression following ANY/SOME is a full SELECT statement or just a static value/list.

Step 2: Correct the Subquery Syntax

  • Rewrite the clause so the ANY/SOME keyword is followed by a complete, valid subquery rather than a static list.
  • Incorrect: WHERE SalaryID = ANY (100, 200, 300)
  • Correct (Subquery): WHERE SalaryID = ANY (SELECT SalaryID FROM dbo.Salaries WHERE Region = 'West')
  • If you are simply trying to match a list of static values, replace ANY (...) with the IN (...) operator instead, as IN supports static lists natively: WHERE SalaryID IN (100, 200, 300).

Step 3: Validate Data Types and Multiset Compatibility

  • Ensure the column on the left side of the comparison operator matches the data type of the column being returned inside the subquery’s SELECT list.
  • Check that the subquery does not return multiple columns (it should return a single column representing a set of rows).
  • Save the script and re-run it in a new query window to parse for syntax errors (Ctrl + F5 in SSMS to parse without execution).

Step 4: Check ORM or Application-Generated Queries

  • If the query was not written manually but generated by an Object-Relational Mapper (ORM) like Entity Framework or Hibernate, update the ORM to the latest patch compatible with SQL Server 2025.
  • Clear the ORM’s query cache to ensure it regenerates the SQL using correct ANSI standard syntax.

Alternative or Verification Steps

  • Verification: Execute the corrected query in a test environment using SET SHOWPLAN_TEXT ON to ensure the execution plan compiles without throwing Error 4170.
  • Alternative: If refactoring the ANY clause is complex, replace the entire logic with an EXISTS clause (e.g., WHERE EXISTS (SELECT 1 FROM Table WHERE Condition)), which often provides better performance and avoids multiset ambiguity entirely.

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

Troubleshooting Guide: Error 4169 – Multiple TREAT Applications in Full-Text Property Reference

Why This Error Happens

Error 4169 occurs when a query attempts to apply the TREAT AS clause more than once to the same expression within a full-text property reference, which SQL Server 2025’s query parser explicitly disallows. This typically arises from malformed Dynamic Data Masking or type-casting logic layered over a CONTAINS/FREETEXT predicate, often introduced by ORM-generated queries or nested views referencing the same full-text indexed column. In some cases, this is also triggered by corrupted or outdated query plan cache entries that retain a stale, double-cast execution plan after a schema change.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement triggering Error 4169 using SQL Server Profiler or Extended Events (xel trace filtered on Error Number = 4169).
  • Check the query execution plan XML for repeated <ScalarOperator>TREAT</ScalarOperator> nodes referencing the same column.
  • Note the specific full-text indexed column and table name involved.

Step 2: Review and Simplify the TREAT/CAST Logic

  • Open the query or stored procedure in SQL Server Management Studio (SSMS) 21.
  • Remove redundant TREAT AS or nested CAST/CONVERT calls wrapping the same full-text column reference.
  • Rewrite the predicate so CONTAINS() or FREETEXT() references the raw column directly, e.g., WHERE CONTAINS(ProductDescription, 'wireless') instead of double-wrapped type assertions.
  • If the query originates from an ORM (Entity Framework, Hibernate), inspect the generated SQL and override it with a raw SQL query or stored procedure call.

Step 3: Clear and Rebuild the Full-Text Catalog

  • Open SSMS and connect to the affected instance.
  • Run: ALTER FULLTEXT CATALOG [YourCatalogName] REBUILD;
  • Rebuild the specific full-text index: ALTER FULLTEXT INDEX ON [Schema].[TableName] START FULL POPULATION;
  • Clear the stale query plan cache: DBCC FREEPROCCACHE; (use cautiously on production during a maintenance window).

Step 4: Update SQL Server Cumulative Updates

  • Navigate to Windows Update or the Microsoft Update Catalog on Windows Server 2025 / Windows 11.
  • Confirm SQL Server 2025 is patched to the latest Cumulative Update (CU), as early CU releases had known full-text parser regressions affecting TREAT handling.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell after patching.

Alternative or Verification Steps

  • Re-run the original query after the catalog rebuild and confirm Error 4169 no longer appears in sys.dm_exec_requests or the SQL Server error log (Get-Content "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG").
  • If the error persists, isolate the query further by testing the CONTAINS predicate alone (without any TREAT/CAST wrapping) in a new session to confirm the full-text index itself is healthy.

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

Troubleshooting Guide: SQL Server Error 4168 — Invalid PROB_MATCH Project Item

Why This Error Happens

Error 4168 occurs when SQL Server’s query optimizer encounters an inconsistency between the internal SELECT list and the PROB_MATCH project item used during execution plan binding, typically caused by corrupted query metadata, an outdated or malformed execution plan cached in memory, or incompatibility introduced after an in-place upgrade to SQL Server 2025. This error is also frequently triggered by corrupted system catalog views or inconsistent statistics objects that the query processor relies on to resolve column references. In rare cases, it stems from a damaged plan cache entry that was not properly invalidated after a schema change (such as a dropped or altered column) on the underlying table or view.

Step-by-Step Resolution Guide

Step 1: Clear the Plan Cache for the Affected Database

  • Open SQL Server Management Studio (SSMS) 21 or later and connect to the instance reporting the error.
  • Run the following command to clear cached execution plans for the specific database, replacing YourDatabaseName accordingly:
  DBCC FLUSHPROCINDB (DB_ID('YourDatabaseName'));
  • Re-execute the failing query to see if the error persists after the stale plan is removed.

Step 2: Run Database Consistency Checks

  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to identify any catalog or page-level corruption.
  • Pay close attention to errors referencing sys.syscolpars, sys.sysiscols, or view definitions, as these frequently correlate with PROB_MATCH binding failures.
  • If corruption is found, restore from a known-good backup rather than relying solely on repair options, since REPAIR_ALLOW_DATA_LOSS can mask deeper schema issues.

Step 3: Recompile and Rebuild Affected Views or Stored Procedures

  • Identify the view or query referenced in the error message (check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025).
  • Drop and recreate the view using sp_refreshview 'YourViewName'; to force SQL Server to rebind the SELECT list correctly.
  • For stored procedures, run EXEC sp_recompile 'YourProcedureName'; to clear any stale execution metadata.

Step 4: Verify Compatibility Level Settings

  • Confirm the database compatibility level matches SQL Server 2025 requirements by running:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is outdated (e.g., inherited from a migrated SQL Server 2019/2022 database), update it:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to apply changes cleanly.

Step 5: Apply the Latest Cumulative Update

  • Check the currently installed build number with SELECT @@VERSION;.
  • Download and install the latest Cumulative Update for SQL Server 2025 from the Microsoft Update Catalog, as this error has known fixes in post-RTM patches related to optimizer binding logic.
  • Reboot the Windows Server 2025 host after installation to ensure all binaries are properly replaced.

Alternative or Verification Steps

  • To verify the fix, re-run the original failing query along with SET SHOWPLAN_XML ON; to confirm the execution plan compiles without referencing an invalid PROB_MATCH item.
  • If the error persists after all steps, isolate the issue by scripting out the view/procedure definition, dropping it entirely, and recreating it from scratch rather than using ALTER, as this forces a full metadata rebuild in the system catalog.

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

Troubleshooting Guide: SQL Server Error 4167 (PROB_MATCH Subquery Conflict)

Why This Error Happens

Error 4167 occurs when a query containing fuzzy matching or probabilistic logic (PROBMATCH) includes multiple subqueries that reference different base tables instead of a single common table. SQL Server’s query optimizer cannot resolve the execution plan because the PROBMATCH predicate requires all referenced subqueries to be scoped to the same underlying table structure. This typically results from manually written T-SQL joins, auto-generated queries from BI tools, or corrupted view definitions that mix table references incorrectly.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and locate the query from the error log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Run the following command to isolate the exact statement ID:
  SELECT * FROM sys.dm_exec_requests WHERE session_id = @@SPID;
  • Confirm that the query contains more than one PROB_MATCH() subquery clause.

Step 2: Rewrite the Subqueries to Reference a Single Base Table

  • Edit the T-SQL script so all PROB_MATCH calls point to the same table alias.
  • Example fix:
  -- Incorrect
  WHERE PROB_MATCH(A.Name, B.Name) AND PROB_MATCH(A.Name, C.Name)

  -- Corrected
  WHERE PROB_MATCH(A.Name, A.AltName)
  • If joining multiple tables is required, pre-stage the data into a temporary table first using SELECT INTO #TempTable.

Step 3: Clear the Plan Cache and Rebuild Statistics

  • Flush any cached execution plans that may still reference the broken query:
  DBCC FREEPROCCACHE;
  • Update statistics on the base table to ensure the optimizer recalculates the fuzzy match plan:
  UPDATE STATISTICS dbo.YourBaseTable;

Step 4: Validate SQL Server Configuration Manager Settings

  • Open SQL Server Configuration Manager (via sqlservermanager17.msc on Windows Server 2025 / Windows 11).
  • Confirm the Fuzzy Lookup/Grouping transformation component is correctly registered under SQL Server Integration Services if the query originates from an SSIS package.
  • Restart the SQL Server (MSSQLSERVER) service to apply changes.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm no error 4167 appears in the Messages tab; check sys.messages to confirm error 4167 is no longer logged for the session.
  • If the issue persists, use SQL Server Profiler to trace the exact execution plan and confirm whether a third-party ORM (e.g., Entity Framework) is auto-generating the conflicting subqueries—regenerate the ORM mapping if so.

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

Why This Error Happens

Error 4166 (“Invalid PROBMATCH subquery”) occurs when SQL Server’s fuzzy matching engine encounters a malformed or unsupported subquery structure inside a PROBMATCH() function call, typically used in Data Quality Services (DQS) or Master Data Services (MDS) matching policies. This is commonly triggered by schema drift in the reference knowledge base, corrupted matching policy metadata, or a subquery that references columns outside the scope of the matching domain. It can also surface after an in-place upgrade to SQL Server 2025 if legacy matching policies created in earlier versions use deprecated subquery syntax that the new query optimizer no longer silently tolerates.

Step-by-Step Resolution Guide

Step 1: Validate the Matching Policy Metadata

  • Open SQL Server Management Studio (SSMS) and connect to the DQS/MDS instance.
  • Run EXEC dbo.sp_validate_matching_policy @PolicyName = 'YourPolicyName'; to check for orphaned or malformed subquery references.
  • Look specifically for NULL or mismatched domain_id values in the mdm.tbl_MatchingRule table.

Step 2: Rebuild the PROB_MATCH Subquery Definition

  • Navigate to C:\Program Files\Microsoft SQL Server\160\DQS\Data (adjust version path for SQL Server 2025 installs) and locate the policy export XML.
  • Open the matching policy in DQS Client, delete the affected PROB_MATCH clause, and manually recreate it, ensuring all referenced columns exist in the current knowledge base schema.
  • Save and republish the policy using Publish Knowledge Base from the DQS Client menu.

Step 3: Clear Cached Execution Plans

  • Run the following in a new query window to purge stale cached plans that may still reference the broken subquery:
  • DBCC FREEPROCCACHE;
  • DBCC DROPCLEANBUFFERS; (only in non-production environments)
  • Restart the SQL Server DQS Cleansing service via services.msc on Windows Server 2025 / Windows 11.

Step 4: Apply the Latest Cumulative Update

  • Confirm your build number with SELECT @@VERSION;.
  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as several known PROB_MATCH parser bugs are patched in post-RTM builds.
  • Reboot the server and re-run the matching job to confirm resolution.

Alternative or Verification Steps

  • Re-execute the original matching job or SSIS Fuzzy Lookup task; if Error 4166 no longer appears in the SQL Server Error Log (Application and Services Logs > SQL Server in Event Viewer), the fix is confirmed.
  • If the error persists, export the matching policy to XML, manually strip all PROB_MATCH subqueries, and rebuild the policy from scratch rather than editing the corrupted version.

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

Troubleshooting Guide: SQL Server Error 4164 — “A GROUP BY clause in a PROB_MATCH query can only have key columns”

Why This Error Happens

This error occurs when a PROB_MATCH function call—used in SQL Server’s fuzzy/probabilistic matching operations—is paired with a GROUP BY clause that references non-key columns. The SQL Server 2025 query optimizer requires that any column used in GROUP BY alongside PROB_MATCH must be part of the defined key set (primary key, unique index, or explicitly declared match key) for the matching algorithm to correctly partition and score candidate rows. This typically results from schema drift, an outdated matching index, or a query written against a table where key constraints were altered or dropped after the matching logic was created.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Columns

  • Capture the full query text from SQL Server Management Studio (SSMS) or the Extended Events session that logged Error 4164.
  • Locate the GROUP BY clause and list every column referenced.
  • Cross-reference each column against sys.indexes and sys.index_columns to confirm which are actual key columns.

Step 2: Verify and Repair the Key Column Definitions

  • Run the following to inspect current key metadata:
SELECT i.name AS IndexName, c.name AS ColumnName, ic.is_included_column
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE i.object_id = OBJECT_ID('YourTableName') AND i.is_primary_key = 1;
  • If a required column is missing from the key, rebuild the primary key or unique index to include it:
ALTER TABLE YourTableName DROP CONSTRAINT PK_YourTableName;
ALTER TABLE YourTableName ADD CONSTRAINT PK_YourTableName PRIMARY KEY (KeyColumn1, KeyColumn2);
  • On Windows Server 2025, ensure this is run with a login holding ALTER permission on the schema (check via sys.fn_my_permissions).

Step 3: Rewrite the GROUP BY Clause to Use Only Key Columns

  • Remove any non-key columns from the GROUP BY clause.
  • If non-key columns are needed for output, move them into an aggregate function (e.g., MAX(), MIN()) or a subsequent JOIN after the PROB_MATCH operation completes.
  • Example corrected pattern:
SELECT k.KeyColumn1, k.KeyColumn2, MAX(t.NonKeyColumn) AS DisplayValue
FROM dbo.YourTable t
JOIN PROB_MATCH(...) AS k ON t.KeyColumn1 = k.KeyColumn1
GROUP BY k.KeyColumn1, k.KeyColumn2;

Step 4: Rebuild the Fuzzy Matching Index (If Applicable)

  • Navigate to the matching index definition under Object Explorer > Databases > YourDB > Indexes in SSMS.
  • Drop and recreate the matching index so it aligns with the updated key schema:
DROP INDEX IX_FuzzyMatch ON dbo.YourTableName;
CREATE INDEX IX_FuzzyMatch ON dbo.YourTableName (KeyColumn1, KeyColumn2);
  • Restart the SQL Server service via services.msc on Windows Server 2025 to clear cached execution plans referencing the old index.

Alternative or Verification Steps

  • Re-run the original query and confirm Error 4164 no longer appears in the SSMS Messages tab or the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • If the error persists, use DBCC FREEPROCCACHE to clear any stale cached query plans, then re-execute the query to force a fresh optimization pass.

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

Troubleshooting Guide: SQL Server Error 4165 — “The score override argument…”

Why This Error Happens

Error 4165 typically occurs when the Query Optimizer’s automatic tuning feature (specifically the “score override” hint used in cardinality estimation or plan forcing) receives an invalid or out-of-range argument value. This is often triggered by corrupted Query Store data, malformed plan hints injected via OPTION clauses, or incompatible trace flags left over from a migration to SQL Server 2025. In some cases, it stems from a botched upgrade where legacy compatibility-level settings conflict with the new adaptive query processing engine.

Step-by-Step Resolution Guide

Step 1: Validate the Query and Hint Syntax

  • Open the offending query in SQL Server Management Studio (SSMS) 21 and check for any manually inserted OPTION (USE HINT(...)) or QUERYTRACEON clauses.
  • Remove any custom SCORE OVERRIDE or cardinality estimation hints temporarily to confirm they are the trigger.
  • Run the query in isolation using SET SHOWPLAN_XML ON to inspect the execution plan for malformed hint arguments.

Step 2: Clear and Rebuild Query Store Data

  • Navigate to Database Properties > Query Store in SSMS and set the operation mode to OFF temporarily.
  • Run the following command to purge corrupted plan data:
  ALTER DATABASE [YourDB] SET QUERY_STORE CLEAR;
  • Re-enable Query Store with ALTER DATABASE [YourDB] SET QUERY_STORE = ON; and allow it to rebuild baseline statistics.

Step 3: Verify Trace Flags and Compatibility Level

  • Check active trace flags using DBCC TRACESTATUS(-1); and disable any flags related to legacy cardinality estimation (e.g., 9481, 2312) that may conflict with SQL Server 2025’s native optimizer.
  • Confirm the database compatibility level matches SQL Server 2025 standards:
  ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025 to clear the plan cache fully.

Step 4: Update SQL Server Cumulative Updates

  • Go to Windows Update or the Microsoft Update Catalog and check for the latest Cumulative Update (CU) for SQL Server 2025, as this error is linked to a known optimizer bug patched in early CUs.
  • Install the update and reboot the server if prompted.

Alternative or Verification Steps

  • Re-run the original query that threw Error 4165 and confirm it executes without exceptions; check the SQL Server Error Log (Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log) for recurrence.
  • If the error persists, disable Automatic Tuning entirely via ALTER DATABASE [YourDB] SET AUTOMATIC_TUNING (FORCE_LAST_GOOD_PLAN = OFF); as a temporary workaround while awaiting a vendor patch.

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

Troubleshooting Guide: Error 4163 — “GROUP BY Clause Required in PROB_MATCH Query” (SQL Server 2025)

Why This Error Happens

This error occurs because SQL Server 2025’s PROB_MATCH function — used for probabilistic fuzzy matching operations — is implemented as an aggregate function internally, requiring an explicit GROUP BY clause to define the scope of comparison for each match set. When a query calls PROB_MATCH alongside other selected columns without grouping those columns, the query optimizer cannot determine how to partition the rows for scoring, triggering Error 4163. This is typically a query construction issue rather than a server configuration or permissions problem, though outdated compatibility levels or corrupted statistics on the matching columns can sometimes mask the root cause.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Locate the exact query referenced in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) or Activity Monitor.
  • Confirm the query includes a PROB_MATCH() function call mixed with non-aggregated columns in the SELECT list.

Step 2: Add the Required GROUP BY Clause

  • Edit the query so every non-aggregated column in the SELECT list is included in a GROUP BY clause.
  • Example corrected syntax:
  SELECT CustomerName, AddressLine1,
         PROB_MATCH(CustomerName, AddressLine1) OVER (PARTITION BY RegionID) AS MatchScore
  FROM dbo.CustomerStaging
  GROUP BY CustomerName, AddressLine1, RegionID;
  • If using PROB_MATCH in a windowed context, ensure PARTITION BY columns align with your intended match groups instead of (or alongside) GROUP BY.

Step 3: Validate Database Compatibility Level

  • Right-click the database in SSMS → Properties → Options → confirm Compatibility Level is set to 170 (SQL Server 2025).
  • Alternatively, run:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 170;
  • Older compatibility levels can cause PROB_MATCH to behave unpredictably or throw inconsistent grouping errors.

Step 4: Rebuild Statistics on Matching Columns

  • Run UPDATE STATISTICS dbo.CustomerStaging WITH FULLSCAN; on the table(s) referenced in the PROB_MATCH call.
  • This ensures the query optimizer has accurate cardinality estimates when evaluating the grouped probabilistic match sets.

Alternative or Verification Steps

  • Re-execute the corrected query and confirm it returns results without Error 4163; check sys.dm_exec_query_stats to verify the execution plan no longer flags a missing aggregation context.
  • If the error persists, isolate PROB_MATCH into a derived table or CTE with its own explicit GROUP BY, then join it back to the main query to avoid column-scope conflicts.

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

Troubleshooting Guide: SQL Server Error 4162 — “A PROBMATCH Table Can Only Be Used Inside of a PROBMATCH Query”

Why This Error Happens

This error occurs when a query references a specialized PROBMATCH table object outside the context of a valid PROBMATCH query scope, which SQL Server 2025 requires for probabilistic matching operations. This typically happens due to incorrectly scoped T-SQL syntax, a session that has lost its PROBMATCH context due to connection pooling or state reset, or an outdated/corrupted query plan cache referencing a deprecated schema binding. It can also surface after an in-place upgrade from SQL Server 2022, where legacy fuzzy-matching logic conflicts with the new native PROBMATCH engine introduced in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Validate the Query Scope and Syntax

  • Open the offending query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio and confirm the PROB_MATCH table is declared inside a WITH PROB_MATCH (...) query block.
  • Ensure there is no GO batch separator splitting the PROB_MATCH declaration from its consuming SELECT statement.
  • Check for nested views or CTEs that reference the PROB_MATCH table outside the required wrapper function sys.fn_probmatch_scope().

Step 2: Clear the Procedure and Plan Cache

  • Run DBCC FREEPROCCACHE; to remove any stale execution plans that may be incorrectly binding the PROB_MATCH object.
  • Run DBCC DROPCLEANBUFFERS; in a non-production environment to force SQL Server to re-evaluate table metadata.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if cache clearing does not resolve the binding issue.

Step 3: Verify Database Compatibility Level

  • Open SSMS, right-click the target database, select Properties > Options, and confirm the Compatibility Level is set to 170 (SQL Server 2025).
  • If the level is lower (e.g., 160 or earlier), run:
    ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;
  • Re-run the PROB_MATCH query after the compatibility level change to confirm the engine now recognizes native probabilistic matching syntax.

Step 4: Reinstall or Repair the Probabilistic Matching Feature Component

  • Launch the SQL Server 2025 Installation Center from the Start Menu on Windows Server 2025 / Windows 11.
  • Navigate to Maintenance > Repair, select the affected instance, and allow the installer to repair the “Probabilistic Matching Engine” feature component.
  • Reboot the server once the repair completes to ensure all related services (SQLBrowser, SQLAgent) reload the correct binaries.

Alternative or Verification Steps

  • Verify the fix by executing a minimal test query using WITH PROB_MATCH (TestTable) SELECT * FROM TestTable; — if it executes without Error 4162, the context binding is restored.
  • If the error persists, review the SQL Server Error Log (via EXEC sp_readerrorlog; or located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for related 4162-series warnings that may indicate a corrupted system catalog requiring a full DBCC CHECKDB repair.

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

Troubleshooting Guide: Error 4161 – “Only CLR Types Are Allowed in Delayed CLR Type Fetching”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to resolve a user-defined type (UDT) or CLR-based column using delayed type fetching, but the underlying assembly metadata has become inconsistent or points to a non-CLR type definition. It is frequently triggered by corrupted assembly catalog entries, a mismatched or partially upgraded sys.assemblies table, or an incompatible CLR assembly that was registered under an older database compatibility level. In some cases, this also surfaces after an in-place upgrade where legacy CLR integration settings were not fully migrated to the new Windows Server 2025 / SQL Server 2025 runtime.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run sp_configure 'clr enabled' to confirm CLR integration is turned on.
  • If disabled, enable it using:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator).

Step 2: Validate and Rebuild Assembly Metadata

  • Query the system catalog to identify the problematic assembly:
  SELECT name, assembly_id, clr_name FROM sys.assemblies;
  • Drop and recreate any assembly showing a NULL or malformed clr_name value:
  DROP ASSEMBLY [YourAssemblyName];
  CREATE ASSEMBLY [YourAssemblyName]
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Ensure the .dll file path is accessible from the SQL Server service account.

Step 3: Check Database Compatibility Level

  • Confirm the database compatibility level matches SQL Server 2025 requirements:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If outdated, update it:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 170;
  • Re-run the query or stored procedure that originally triggered Error 4161.

Step 4: Repair System Catalog Corruption (If Needed)

  • Run DBCC CHECKDB('YourDatabase') WITH DATA_PURITY; to rule out catalog-level corruption.
  • If corruption is detected in system tables related to CLR types, restore from the last known good backup rather than attempting automated repair, as REPAIR_ALLOW_DATA_LOSS can affect CLR metadata integrity.

Alternative or Verification Steps

  • After applying the fix, re-execute the original query or application call that referenced the CLR type; confirm Error 4161 no longer appears in the SQL Server error log (Management > SQL Server Logs in SSMS).
  • As an alternative, if the assembly is no longer needed, drop all dependent UDTs and functions referencing it, then fully remove and recreate the assembly from a verified source .dll to eliminate any residual metadata corruption.

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

Why This Error Happens

Error 4160 occurs when SQL Server 2025 needs to perform “delayed fetching” of a large CLR-based column (such as a geography, geometry, hierarchyid, or custom CLR UDT) but cannot locate a unique key or suitable index on the base table to retrieve that row efficiently. This typically happens when the table lacks a primary key, unique index, or clustered index, forcing the query processor to fail when it tries to defer-load large CLR values during execution plans, DBCC CHECKDB operations, or replication snapshot processes. It can also surface if existing indexes have become fragmented, disabled, or are missing due to a schema change that was not fully propagated to dependent objects.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Table and CLR Column

  • Run the failing query again with SET SHOWPLAN_XML ON or capture the full error text — it will include the table name in place of %.*ls.
  • Use sp_help 'TableName' in SQL Server Management Studio (SSMS) 21 to list all columns and confirm which one uses a CLR data type (e.g., geography, geometry, hierarchyid, or a custom SQLCLR UDT).
  • Check existing keys with:
  EXEC sp_helpindex 'TableName';

Step 2: Add a Primary Key or Unique Index

  • If the table has no primary key, add one on an appropriate integer or GUID column:
  ALTER TABLE dbo.TableName
  ADD CONSTRAINT PK_TableName PRIMARY KEY CLUSTERED (ID);
  • If a primary key already exists but is non-clustered only, consider adding a clustered index, since delayed CLR fetching relies on a clustered or unique key path to re-locate the row.
  • Avoid using the CLR column itself as part of the key — CLR UDTs are not reliably comparable for indexing purposes.

Step 3: Rebuild Indexes and Update Statistics

  • After adding the key, rebuild all indexes on the table to ensure the engine recognizes the new key structure:
  ALTER INDEX ALL ON dbo.TableName REBUILD;
  UPDATE STATISTICS dbo.TableName;
  • This step resolves cases where metadata was stale after a prior schema modification.

Step 4: Validate CLR Assembly and Database Integrity

  • Confirm the CLR assembly backing the UDT is still registered and in a healthy state:
  SELECT name, permission_set_desc, is_user_defined
  FROM sys.assemblies;
  • Run DBCC CHECKDB('YourDatabase') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption that may be interfering with the delayed fetch mechanism.
  • On Windows Server 2025 / Windows 11 hosts, also confirm the SQL Server service account has read/execute permissions on the CLR assembly DLL path under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ if assemblies are loaded EXTERNAL_ACCESS or UNSAFE.

Step 5: Restart the SQL Server Service

  • After applying the key and rebuilding indexes, restart the instance to clear cached query plans referencing the old table structure:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This ensures the plan cache no longer holds a stale execution plan that triggered the original 4160 error.

Alternative or Verification Steps

  • Re-run the original query or job that triggered Error 4160; it should now execute without failure, and sp_helpindex should confirm a valid primary/unique key exists.
  • If the error persists, drop and recreate the CLR column’s parent table (in a test environment first) with a proper primary key defined at creation time, then re-import data — this resolves rare cases where legacy schema migrations left orphaned key metadata.

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

Troubleshooting Guide: Error 4159 in Microsoft SQL Server 2025

Why This Error Happens

Error 4159 occurs when a query references a CLR user-defined type (UDT) in a computed context—such as a computed column, check constraint, or indexed view—where SQL Server defers (delays) the evaluation of the CLR instance, but that delayed instance implicitly depends on a column from the local base table that was not explicitly passed as an argument. This typically happens after upgrading to SQL Server 2025 or Windows Server 2025, where stricter CLR binding validation exposes previously tolerated schema-binding gaps in assemblies. It can also surface due to an outdated or improperly registered CLR assembly (.dll) that no longer aligns with the updated .NET runtime integration in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object

  • Run the following query to locate the computed column, constraint, or view causing the error:
  • SELECT object_name(object_id), name, definition FROM sys.computed_columns WHERE definition LIKE '%YourCLRType%';
  • Cross-reference the result with sys.assembly_types to confirm the CLR type involved.
  • Check SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact object and line number tied to Error 4159.

Step 2: Correct the CLR Method Invocation

  • Open the definition of the computed column or constraint in SQL Server Management Studio (SSMS) 21.
  • Ensure the base table column is explicitly passed as a parameter to the CLR method, rather than relying on implicit binding:
  • Example fix: ALTER TABLE dbo.YourTable ADD ComputedCol AS dbo.YourCLRFunction(BaseColumn) PERSISTED;
  • Avoid referencing this or instance-level CLR state that implicitly pulls from the table without explicit parameterization.

Step 3: Rebuild and Redeploy the CLR Assembly

  • Recompile the SQLCLR assembly using the .NET 9 SDK (required baseline for SQL Server 2025 compatibility).
  • Drop and re-register the assembly:
  • ALTER ASSEMBLY YourAssembly FROM 'C:\SQLCLR\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Verify clr strict security is enabled and the assembly is properly signed with a certificate trusted in master.

Step 4: Rebuild Dependent Computed Columns/Indexes

  • Drop and recreate any persisted computed columns or indexed views that reference the corrected CLR type:
  • DROP INDEX IX_YourView ON dbo.YourView;
  • ALTER TABLE dbo.YourTable DROP COLUMN ComputedCol; then re-add with the corrected definition.
  • This forces SQL Server to re-validate the delayed CLR binding against the updated assembly.

Alternative or Verification Steps

  • Verify the fix by running DBCC CHECKCONSTRAINTS and executing a test SELECT against the affected computed column to confirm no Error 4159 is raised.
  • If the error persists, as a fallback, replace the CLR-based computed column with an equivalent native T-SQL scalar function (non-CLR), which bypasses delayed CLR instance evaluation entirely.

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

Troubleshooting Guide: SQL Server Error 4158 – “The field is referenced more than once in the set list”

Why This Error Happens

Error 4158 occurs when a MERGE or UPDATE statement’s SET clause references the same column name more than once within the same assignment list, which SQL Server’s query parser rejects as ambiguous. This typically results from poorly constructed dynamic SQL, auto-generated scripts (such as those from ORM tools or data migration utilities), or copy-paste errors where a column was duplicated accidentally. It can also surface when self-joins or multi-table UPDATE statements fail to properly qualify column names, causing the engine to interpret two different source columns as the same target field.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement from SQL Server Management Studio (SSMS) output or the application’s exception log — the error message will include the specific field name in place of %.*ls.
  • Use SQL Server Profiler or Extended Events (sqlserver.error_reported filtered on Error Number = 4158) to trace which stored procedure or application call triggered it.
  • Check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for a timestamped entry correlating with the failure.

Step 2: Inspect and Correct the SET Clause

  • Open the query in SSMS and manually review the SET list for duplicate column assignments, e.g. SET Name = @Name, Name = @NewName.
  • Remove or consolidate the duplicate assignment so each column appears exactly once.
  • If the query is dynamically generated (common in Entity Framework, Dapper, or custom ETL scripts), inspect the code that builds the SET string and add deduplication logic before execution.

Step 3: Review Multi-Table or MERGE Statement Logic

  • For MERGE statements, confirm that the WHEN MATCHED THEN UPDATE SET clause isn’t unintentionally updating the same target column from two different source conditions.
  • For multi-table UPDATE statements using joins, fully qualify each column with its table alias (e.g., SET t1.Status = t2.Status) to avoid ambiguous resolution.
  • Rebuild and test the corrected query in isolation using SSMS before redeploying it to the application or stored procedure.

Step 4: Patch and Update SQL Server Components

  • Ensure SQL Server 2025 is running the latest Cumulative Update via SQL Server Setup > Check for Updates, since parser-related bugs in dynamic SQL generation are occasionally addressed in patches.
  • On Windows Server 2025/Windows 11, confirm Windows Update has applied the latest .NET Framework and Visual C++ Redistributable packages, as these can affect client driver query construction.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after applying updates.

Alternative or Verification Steps

  • Re-run the corrected query directly in SSMS against a test database to confirm Error 4158 no longer appears and the expected rows are updated.
  • If using an ORM or code-generation tool, regenerate the affected query/mapping and run a unit test against a staging environment to verify duplicate field references are not reintroduced in future builds.

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

Why This Error Happens

Error 4157 typically occurs when a T-SQL statement references a property name (commonly in sp_dbmmonitorupdate, fn_listextendedproperty, extended properties, or SSIS/replication configuration calls) that does not exist or is misspelled in the current SQL Server 2025 schema. This often happens after an in-place upgrade from an older SQL Server version where deprecated property names were removed, or when a script/tool was written against a different SQL Server build with a mismatched metadata catalog. It can also surface due to corrupted or outdated system stored procedures following an incomplete patch/update installation on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Property Name Causing the Error

  • Capture the full error message text, including the property name inside the quotes (e.g., "REPLICATION_STATE").
  • Run the failing script manually in SQL Server Management Studio (SSMS) 21 to isolate the exact line/procedure call.
  • Cross-reference the property name against Microsoft’s official SQL Server 2025 system catalog documentation to confirm it is valid or deprecated.

Step 2: Validate and Correct Extended Properties or System Function Calls

  • Open Object Explorer in SSMS, navigate to the target database, and check Properties > Extended Properties for mismatched or renamed entries.
  • If the error originates from sp_addextendedproperty, sp_updateextendedproperty, or fn_listextendedproperty, verify the property parameter matches supported values exactly (case-sensitive in some collations).
  • Update any legacy scripts (e.g., replication or monitoring jobs) to use the renamed property supported in SQL Server 2025, such as replacing deprecated monitoring properties with their current equivalents.

Step 3: Repair System Metadata and Reapply Service Pack/CU

  • Close SSMS and stop the SQL Server service via services.msc or net stop MSSQLSERVER.
  • Run sqlservr.exe -c -m from an elevated Command Prompt to start SQL Server in single-user maintenance mode.
  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out catalog corruption.
  • Reinstall the latest Cumulative Update for SQL Server 2025 from the Microsoft Update Catalog to restore any missing or corrupted system stored procedures.

Step 4: Rebuild Affected Jobs or Monitoring Scripts

  • If the error comes from a SQL Server Agent job or replication monitor, open SQL Server Agent > Jobs, locate the failing job step, and edit the T-SQL command.
  • Remove or replace any obsolete property references with current ones listed in sys.extended_properties or the updated replication stored procedure documentation.

Alternative or Verification Steps

  • Re-run the original script or job after corrections; confirm no Error 4157 appears in the SQL Server Error Log (EXEC xp_readerrorlog 0, 1;).
  • If the issue persists, restore a known-good backup of the msdb database (where job/property metadata resides) and compare extended property definitions against the current script to locate the discrepancy.

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

Why This Error Happens

Error 4156 occurs when a nested INSERT statement (typically an INSERT...EXEC or an INSERT targeting a table via OPENROWSET/OPENQUERY) attempts to write into a table that has a CHECK constraint, FOREIGN KEY constraint, or an INSTEAD OF trigger defined on it. SQL Server 2025 enforces this restriction because nested INSERT operations cannot validate constraint logic reliably within the same transactional scope. This is a design limitation rather than a corruption issue, and it most commonly surfaces after a schema migration or when a stored procedure calling pattern uses EXEC to populate a table that was recently altered to include new constraints.

Step-by-Step Resolution Guide

Step 1: Identify the Target Table and Constraint

  • Run sp_helpconstraint 'YourTableName' in SQL Server Management Studio (SSMS) to list all CHECK, FOREIGN KEY, and trigger definitions.
  • Confirm whether the nested INSERT is using INSERT INTO TargetTable EXEC StoredProcedureName or an OPENROWSET call.
  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact table name referenced in the 4156 message.

Step 2: Remove or Relocate the Conflicting Constraint

  • Script out the CHECK constraint using SSMS (Right-click Table > Script Table as > CREATE To > New Query Editor Window).
  • Temporarily disable the constraint with:
    ALTER TABLE YourTableName NOCHECK CONSTRAINT ALL;
  • Execute the nested INSERT/EXEC process to confirm the constraint was the blocking factor.
  • Re-enable the constraint afterward using ALTER TABLE YourTableName WITH CHECK CHECK CONSTRAINT ALL;.

Step 3: Refactor the Insert Logic

  • Replace the INSERT...EXEC pattern with a staging table that has no constraints.
  • Insert data into the staging table first using INSERT INTO StagingTable EXEC StoredProcedureName;.
  • Move validated data from the staging table to the final constrained table using a standard INSERT INTO FinalTable SELECT * FROM StagingTable; (this is NOT a nested insert, so constraints will apply correctly).
  • Drop or truncate the staging table after the transfer using TRUNCATE TABLE StagingTable;.

Step 4: Update Server Configuration (If Using OPENROWSET)

  • Navigate to SQL Server Configuration Manager on Windows Server 2025.
  • Confirm “Ad Hoc Distributed Queries” is enabled via:
    EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'Ad Hoc Distributed Queries', 1; RECONFIGURE;
  • Restart the SQL Server service from services.msc to apply configuration changes.

Alternative or Verification Steps

  • Run the original stored procedure call manually in SSMS and confirm no 4156 error appears in the Messages tab; check the target table row count increased as expected.
  • If the error persists, verify no INSTEAD OF trigger exists on the target table using SELECT * FROM sys.triggers WHERE parent_id = OBJECT_ID('YourTableName'); — triggers combined with nested inserts also trigger this error and require the same staging-table workaround.

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

Why This Error Happens

Error 4154 occurs when the SQL Server 2025 query parser encounters the UNNEST operator applied to a value that the engine cannot resolve as a native MULTISET collection type. This typically happens when a JSON array, a table-valued variable, or an OPENJSON result set is passed into UNNEST without being explicitly cast, or when the database is running in a compatibility level that does not fully support the new ANSI SQL:2023 multiset extensions introduced in SQL Server 2025. In rare cases, a corrupted or outdated cached execution plan can also cause the engine to misidentify the data type being passed to UNNEST.

Step-by-Step Resolution Guide

Step 1: Verify Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check the current compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is below 170 (SQL Server 2025), update it:
  ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;

Step 2: Correct the Query Syntax for Multiset Casting

  • Ensure any JSON array or table expression passed to UNNEST is explicitly cast:
  SELECT * FROM UNNEST(CAST(@jsonArray AS MULTISET));
  • If using OPENJSON, confirm it returns a multiset-compatible structure rather than a raw rowset:
  SELECT value FROM OPENJSON(@json) WITH (value NVARCHAR(MAX) '$');
  • Avoid passing scalar variables or non-collection types directly into UNNEST.

Step 3: Update SQL Server Drivers and Client Tools

  • On Windows Server 2025 / Windows 11, confirm you are using the ODBC Driver 18+ or OLE DB Driver 19+ for SQL Server, as older drivers do not recognize the new multiset type.
  • Download the latest driver from the official Microsoft Download Center and reinstall.
  • Restart the SQL Server (MSSQLSERVER) service after installation via services.msc.

Step 4: Clear and Rebuild the Execution Plan Cache

  • Corrupted cached plans can cause type-resolution errors. Clear the plan cache for the affected database:
  DBCC FREEPROCCACHE;
  • Re-run the query to force SQL Server to generate a fresh execution plan with correct type inference.

Step 5: Apply the Latest Cumulative Update (CU)

  • Check Windows Update or the SQL Server Installation Center for the latest Cumulative Update for SQL Server 2025.
  • Install the update, as early CUs for 2025 contained known parser bugs related to ANSI multiset handling in UNNEST.

Alternative or Verification Steps

  • After applying the fix, run the query in SSMS with Actual Execution Plan enabled — the plan should show a valid Table Valued Function [UNNEST] operator without type-conversion warnings.
  • If the error persists, isolate the issue by testing the UNNEST expression independently in a new session using CAST(... AS MULTISET) to confirm whether the root cause is syntax-based or driver/version-based.

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

Why This Error Happens

This error occurs when SQL Server 2025 encounters a nested INSERT...EXEC statement where the inner stored procedure or dynamic SQL attempts to return more than one column in its result set. The Query Optimizer strictly enforces a single-column restriction on nested inserts because the outer INSERT statement cannot resolve a multi-column mapping when a secondary execution context is already active. This typically surfaces after upgrading to SQL Server 2025 on Windows Server 2025, where stricter parsing of nested procedure calls now flags syntax that may have silently worked—or thrown a different warning—in older engine versions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Nested INSERT Statement

  • Open SQL Server Management Studio (SSMS) and locate the exact stored procedure or batch referenced in the error output.
  • Check the sys.dm_exec_sql_text DMV or SQL Server Profiler/Extended Events trace to capture the exact query text that triggered Error 4155.
  • Confirm whether the procedure contains an INSERT INTO TableName EXEC AnotherProcedure pattern where AnotherProcedure itself contains a nested INSERT...EXEC.

Step 2: Refactor the Nested Logic to Avoid Double EXEC Nesting

  • Rewrite the inner procedure to populate a temporary table (#TempTable) or table variable instead of directly nesting another EXEC inside an INSERT.
  • Example fix:
  INSERT INTO #TempResults
  EXEC dbo.InnerProcedure;

  INSERT INTO FinalTable (Col1)
  SELECT Col1 FROM #TempResults;
  • Ensure the inner SELECT statement being inserted ultimately resolves to exactly one column per INSERT target when nesting cannot be avoided.

Step 3: Validate Compatibility Level and Query Hints

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDBName'; to confirm the database compatibility level matches SQL Server 2025 standards (170).
  • If the procedure was migrated from an older SQL Server version, test with ALTER DATABASE YourDBName SET COMPATIBILITY_LEVEL = 160; temporarily to see if legacy parsing resolves the issue (useful for diagnosis, not a permanent fix).
  • Remove any unnecessary OUTPUT clauses or multi-column SELECT statements inside the nested EXEC call.

Step 4: Apply Latest Cumulative Update

  • On Windows Server 2025, open Windows Update or use SSMS > Help > Check for Updates to confirm you are on the latest Cumulative Update (CU) for SQL Server 2025, as early CUs had known parser regressions affecting nested INSERT...EXEC validation.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) after patching.

Alternative or Verification Steps

  • Re-run the original stored procedure or batch in SSMS and confirm Error 4155 no longer appears in the Messages tab; check the Windows Event Viewer (Application Log) to ensure no related SQL Server exceptions were logged.
  • If the error persists, bypass nested execution entirely by converting the inner procedure logic into a Table-Valued Function (TVF) and referencing it directly in the outer INSERT INTO ... SELECT statement.

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

Troubleshooting Guide: SQL Server Error 4153

Why This Error Happens

Error 4153 occurs when SQL Server encounters a data type mismatch that it cannot implicitly convert, typically during BULK INSERT, OPENROWSET, or SELECT INTO operations where the source data format doesn’t align with the destination column’s defined data type. This is commonly caused by incorrect format file definitions, mismatched column ordinals between source and destination, or attempting to map incompatible types (such as treating a varchar field as datetime or XML as nvarchar without proper casting). Corrupted or outdated format files (.fmt or .xml) used in bulk import operations are also a frequent root cause.

Step-by-Step Resolution Guide

Step 1: Verify the Source and Destination Schema

  • Run sp_help 'YourTableName' in SQL Server Management Studio (SSMS) to inspect the exact data types and ordinal positions of the destination table.
  • Compare this against the source file or query output column-by-column to identify the specific type mismatch referenced in the error.
  • Pay close attention to precision/scale differences (e.g., decimal(10,2) vs float).

Step 2: Inspect and Regenerate the Format File

  • If using BULK INSERT or bcp, locate the format file (commonly stored in paths like C:\SQLData\Import\format.xml).
  • Regenerate the format file using the bcp utility to ensure it matches the current table schema:
  • bcp YourDatabase.dbo.YourTable format nul -c -x -f C:\SQLData\Import\newformat.xml -t, -S YourServerName -T
  • Open the new XML file and verify the <COLUMN> tags match the SOURCE and xsi:type attributes correctly.

Step 3: Apply Explicit Type Casting in the Query

  • If the error occurs in a SELECT INTO or INSERT...SELECT statement, modify the query to explicitly cast the problematic column.
  • Example syntax: SELECT CAST(SourceColumn AS NVARCHAR(50)) FROM SourceTable.
  • Save the script in SSMS and re-run the query to confirm the cast resolves the conflict.

Step 4: Check for XML/JSON Type Conflicts

  • If the error involves XML or JSON data types, ensure the destination column is not attempting to treat raw text as structured XML without validation.
  • Use CONVERT(XML, YourColumn) explicitly rather than relying on implicit conversion during the insert.
  • Restart the SQL Server Database Engine service via services.msc on Windows Server 2025 if schema caching causes the old type definition to persist after changes.

Alternative or Verification Steps

  • Verification: Re-run the original BULK INSERT or SELECT INTO statement; if successful, query the top 10 rows of the destination table using SELECT TOP 10 * FROM YourTable to ensure data integrity and correct type casting.
  • Alternative: If the format file continues to cause issues, bypass it entirely by using the OPENROWSET(BULK...) function with explicit WITH schema declarations to force the correct data types during import.

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

Troubleshooting Guide: SQL Server Error 4152 — “Type is not a CLR type”

Why This Error Happens

This error occurs when SQL Server attempts to reference, assign, or cast a database type that was expected to be a CLR (Common Language Runtime) user-defined type, but the type is actually a native SQL type or does not exist in the CLR type catalog. This commonly happens after a database restore or migration where the CLR assembly backing the type was not properly registered, or when a type name collision occurs between a native alias type and a CLR type sharing the same name. It can also result from a corrupted or missing assembly binary that SQL Server 2025 cannot resolve to the metadata entry in sys.assembly_types.

Step-by-Step Resolution Guide

Step 1: Verify the Type Registration in the Database

  • Run the following query to confirm whether the type is registered as a CLR type:
  SELECT name, is_assembly_type FROM sys.types WHERE name = 'YourTypeName';
  • If is_assembly_type returns 0, the type exists but is not linked to a CLR assembly — this confirms the root cause.
  • Cross-check against sys.assembly_types to see if the assembly binding is missing.

Step 2: Re-register or Re-deploy the CLR Assembly

  • Confirm CLR integration is enabled on the instance:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Drop and recreate the affected type binding to the assembly:
  DROP TYPE dbo.YourTypeName;
  CREATE TYPE dbo.YourTypeName EXTERNAL NAME YourAssembly.[YourClassName];
  • Ensure the .dll assembly file used during deployment matches the version originally compiled against the database schema.

Step 3: Check for Assembly Corruption or Version Mismatch

  • Navigate to the SQL Server binaries directory (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\) and confirm the assembly file hasn’t been altered or deleted post-upgrade to SQL Server 2025.
  • Re-import the assembly using:
  ALTER ASSEMBLY YourAssembly FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via services.msc or:
  Restart-Service -Name "MSSQLSERVER"

Step 4: Resolve Naming Conflicts Between Native and CLR Types

  • Query sys.types for duplicate type names across schemas:
  SELECT name, schema_id, is_assembly_type FROM sys.types WHERE name = 'YourTypeName';
  • Rename or fully schema-qualify the CLR type reference in your T-SQL code (e.g., dbo.MyClrType instead of just MyClrType) to eliminate ambiguity with system or native alias types.

Alternative or Verification Steps

  • After re-deployment, test by declaring a variable of the type (DECLARE @x dbo.YourTypeName;) — if no error is thrown, the CLR type binding is successfully restored.
  • If the issue persists, drop the assembly entirely (DROP ASSEMBLY YourAssembly) and perform a clean redeployment from source using CREATE ASSEMBLY ... FROM 'path' WITH PERMISSION_SET = SAFE, then recreate all dependent types and functions.

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

Troubleshooting Guide: SQL Server Error 4151 — NULLIF Argument Type Ambiguity

Why This Error Happens

This error occurs because the NULLIF function requires its first argument to have an explicitly determinable data type, and passing a bare NULL constant (e.g., NULLIF(NULL, column_name)) leaves the SQL Server 2025 query parser unable to resolve a type during the compilation phase. This is not a server configuration issue or permissions problem — it is a T-SQL syntax/type-resolution limitation enforced by the Query Optimizer before execution begins. It commonly surfaces in dynamically generated SQL, ORM-generated queries, or stored procedures where a variable or parameter resolves to NULL without a cast.

Step-by-Step Resolution Guide

Step 1: Identify the Offending NULLIF Statement

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Locate the exact query using the statement text from the error message in SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Search for all instances of NULLIF( in the stored procedure, view, or application-generated query.

Step 2: Explicitly Cast the First Argument

  • Rewrite the offending expression to include an explicit CAST or CONVERT so SQL Server can resolve the type.
  • Example fix: change NULLIF(NULL, [ColumnName]) to NULLIF(CAST(NULL AS INT), [ColumnName]) — replacing INT with the actual expected data type (e.g., VARCHAR(50), DATETIME2).
  • If the value originates from an application layer (C#, Java, Python), ensure the parameter is bound with an explicit SQL type rather than passed as a generic null/None.

Step 3: Audit Dynamic SQL and ORM-Generated Queries

  • If using Entity Framework Core, Dapper, or similar ORMs, check generated SQL via SQL Server Profiler or Extended Events session (Query_Completed event).
  • Add explicit type hints in LINQ expressions or stored procedure parameters (e.g., (int?)null instead of null in C#).
  • For dynamic SQL built with sp_executesql, ensure parameter definitions explicitly declare types in the @params string.

Step 4: Recompile and Test the Corrected Query

  • Run sp_recompile 'YourProcedureName'; to clear the cached execution plan.
  • Execute the corrected query in isolation using SSMS to confirm Error 4151 no longer appears.
  • Check Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) to confirm no related errors were logged during execution.

Alternative or Verification Steps

  • Verify the fix by running the query directly in SSMS with SET SHOWPLAN_ALL ON; to confirm the execution plan compiles without type-resolution errors.
  • If the error persists in ORM-generated code, as an alternative, replace NULLIF logic entirely with a CASE WHEN column IS NULL THEN NULL ELSE column END construct, which avoids the type-inference requirement altogether.

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

Troubleshooting Guide: SQL Server Error 4150 — Hints Not Allowed on Recursive CTE References

Why This Error Happens

This error occurs because SQL Server’s query optimizer does not permit table hints (such as NOLOCK, INDEX, or FORCESEEK) to be applied directly to the recursive member reference inside a Common Table Expression (CTE). The recursive invocation of the CTE is treated as a self-referencing virtual table rather than a physical table, so the engine cannot resolve physical access hints against it. This typically surfaces after a code migration, a copy-pasted query template, or an ORM-generated script that appends default hints to every table reference without distinguishing recursive CTE calls.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open the query indicated in the error message (visible in SSMS, Query Store, or the application’s exception log).
  • Locate the WITH cte_name AS (...) block and find the recursive anchor/recursive member section.
  • Search specifically for hint syntax like WITH (NOLOCK), WITH (INDEX(...)), or WITH (FORCESEEK) attached to the recursive self-reference (the part of the UNION ALL that calls the CTE itself).

Step 2: Remove the Hint from the Recursive Reference

  • Edit the T-SQL script and strip out the hint clause only from the recursive member’s reference to the CTE (not necessarily the anchor member, which may still reference a base table with a hint).
  • Example fix:
  • Incorrect: SELECT * FROM cte_name WITH (NOLOCK) WHERE ...
  • Corrected: SELECT * FROM cte_name WHERE ...
  • Save the corrected script and redeploy it to the relevant stored procedure, view, or function using SSMS or your deployment pipeline (e.g., Azure DevOps, SSDT project).

Step 3: Audit for Template-Generated Hints

  • If the query was generated by an ORM (Entity Framework, Dapper) or a code generator, check the template or interceptor responsible for injecting hints globally.
  • Update the generation logic to exclude CTE recursive blocks, or add a post-processing regex step to strip hints from WITH ... AS (...) recursive sections before execution.
  • Re-run the generated SQL in SSMS to confirm Error 4150 no longer appears.

Step 4: Validate Query Logic Without the Hint

  • Since hints like NOLOCK were likely used for performance tuning, re-evaluate whether the recursive CTE needs alternative tuning.
  • Consider using OPTION (MAXRECURSION n) at the end of the outer query instead, which is supported and does not trigger Error 4150.
  • Test execution plans using SET STATISTICS IO, TIME ON to ensure performance remains acceptable after hint removal.

Alternative or Verification Steps

  • Run the corrected query directly in SSMS or Azure Data Studio connected to your SQL Server 2025 instance; confirm it executes without raising Error 4150 and returns expected recursive results.
  • If hints are required for performance reasons, move them to the anchor member or to the outer SELECT statement wrapping the CTE invocation instead of the recursive self-reference, and validate via SET SHOWPLAN_XML ON that the hint is applied correctly without errors.

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

Troubleshooting Guide: SQL Server Error 4148 — “XML methods are not allowed in a GROUP BY clause”

Why This Error Happens

This error occurs because SQL Server does not permit direct invocation of XML data type methods (such as .value(), .query(), or .nodes()) within a GROUP BY clause, as these methods are non-deterministic in this context and cannot be used to define grouping sets. The engine requires that any value used for grouping be a static, comparable scalar, and XML method calls do not meet this requirement when evaluated inline. This is a T-SQL syntax limitation rather than a server configuration or permissions issue, meaning it cannot be resolved through Windows Server 2025 or Windows 11 system settings alone.

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 exact query referenced in the error log or application stack trace.
  • Check the GROUP BY clause for any direct calls like GROUP BY XmlColumn.value('(/Root/Element)[1]', 'varchar(50)').

Step 2: Move the XML Method Call to the SELECT or CROSS APPLY Clause

  • Rewrite the query so the XML method is evaluated in the SELECT list or via a CROSS APPLY operator, assigning it to an alias.
  • Example fix:
  SELECT XmlColumn.value('(/Root/Element)[1]', 'varchar(50)') AS ExtractedValue, COUNT(*)
  FROM dbo.YourTable
  GROUP BY XmlColumn.value('(/Root/Element)[1]', 'varchar(50)');

This above syntax still fails — instead, use a derived table or CTE (see Step 3).

Step 3: Use a Common Table Expression (CTE) or Subquery

  • Wrap the XML extraction logic inside a CTE or derived table first, then perform the GROUP BY on the resulting alias column.
  • Corrected example:
  ;WITH ExtractedData AS (
      SELECT XmlColumn.value('(/Root/Element)[1]', 'varchar(50)') AS ExtractedValue
      FROM dbo.YourTable
  )
  SELECT ExtractedValue, COUNT(*)
  FROM ExtractedData
  GROUP BY ExtractedValue;
  • Ensure the extracted column uses an explicit data type cast (e.g., varchar(50)) to avoid implicit conversion issues.

Step 4: Validate Query Execution Plan and Indexes

  • Run SET SHOWPLAN_XML ON to confirm the query compiles without raising Error 4148.
  • If the table has an XML index, verify it aligns with the extraction path used in the CTE to maintain performance after the rewrite.

Step 5: Update Application Code and Stored Procedures

  • Search stored procedures, views, and ORM-generated queries (e.g., Entity Framework, Dapper) for similar GROUP BY patterns on XML columns.
  • Deploy the corrected T-SQL to your SQL Server 2025 instance via SSMS or your CI/CD deployment pipeline.

Alternative or Verification Steps

  • Re-execute the original query (or application workflow) and confirm Error 4148 no longer appears in SQL Server logs (Event Viewer > Windows Logs > Application, filtered by Source “MSSQLSERVER”).
  • As an alternative, consider shredding the XML column into a persisted computed column with an index, then use that computed column directly in GROUP BY to avoid repeated XML parsing overhead.

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

Troubleshooting Guide: SQL Server Error 4147 — Non-ANSI Outer Join Operators

Why This Error Happens

This error occurs because SQL Server 2025 has fully deprecated the legacy *= and =* outer join syntax that was used in older versions of Transact-SQL. By default, the ANSI_NULLS and compatibility level settings in modern databases reject this non-standard syntax to enforce ANSI SQL-92 compliant join behavior. This typically surfaces when legacy applications, stored procedures, or migrated scripts written for SQL Server 2000 or earlier are executed against a database with a current compatibility level.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Stored Procedure

  • Capture the exact query text from the error message or SQL Server error log.
  • Use sys.dm_exec_query_stats combined with sys.dm_exec_sql_text to locate the procedure or ad-hoc batch containing *= or =*.
  • Search application source code or SSIS packages for legacy join syntax if the query originates externally.

Step 2: Rewrite the Query Using ANSI Join Syntax

  • Replace *= with LEFT OUTER JOIN ... ON syntax.
  • Replace =* with RIGHT OUTER JOIN ... ON syntax.
  • Example conversion:
  -- Old (invalid in SQL Server 2025)
  SELECT * FROM TableA, TableB WHERE TableA.ID *= TableB.ID

  -- New (ANSI-compliant)
  SELECT * FROM TableA LEFT OUTER JOIN TableB ON TableA.ID = TableB.ID
  • Test the rewritten query in SQL Server Management Studio (SSMS) to confirm correct result sets.

Step 3: Check Database Compatibility Level (Temporary Workaround Only)

  • Open SSMS and right-click the database, then select Properties > Options.
  • Note the current Compatibility Level value (e.g., 160 for SQL Server 2022, 170 for SQL Server 2025).
  • Run the following to temporarily lower compatibility level as a stopgap while code is rewritten:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 80;
  • Understand this is not officially supported long-term, as Microsoft has removed the old join parser entirely in SQL Server 2025 — this step may not resolve the error at all and should not be relied upon as a permanent fix.

Step 4: Update Application Code and Deployment Scripts

  • Search all .sql, .dtsx, and application connection layers (ORMs, stored procedures, views) for legacy syntax patterns.
  • Use a script like the following to scan stored procedure definitions:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%*=%' OR definition LIKE '%=*%';
  • Deploy corrected scripts through your standard CI/CD or change management pipeline.

Step 5: Validate ANSINULLS and ANSIWARNINGS Session Settings

  • Ensure connections use SET ANSI_NULLS ON and SET ANSI_WARNINGS ON, as required defaults in SQL Server 2025.
  • Check client driver configuration (ODBC, OLE DB, or ADO.NET) to confirm these settings aren’t being overridden at the connection string level.

Alternative or Verification Steps

  • Re-run the corrected query or execute the stored procedure manually in SSMS to confirm Error 4147 no longer appears and result sets match expected output.
  • If immediate rewriting isn’t feasible, consider isolating legacy workloads on a separate instance running an older supported SQL Server version until code remediation is complete, since compatibility-level workarounds are not guaranteed in 2025.

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

Why This Error Happens

Error 4146 occurs when the CREATE STATISTICS or UPDATE STATISTICS command is executed against a column that does not support statistical indexing—typically columns with data types like XML, geography, geometry, image, text, ntext, or non-deterministic computed columns. SQL Server 2025’s query optimizer requires deterministic, comparable data to build a valid statistics object, and it rejects the request at the parser level if the target column fails this validation. This is not a permissions or connectivity issue; it is a schema-level restriction enforced by the Database Engine itself.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Open SQL Server Management Studio (SSMS) 21 and run the failing script in a new query window against the affected database.
  • Note the exact column name referenced in the error message—SQL Server will explicitly name it in the 4146 output.
  • Run sp_help 'TableName' or query sys.columns to check the data type of that column.

Step 2: Verify Data Type Compatibility

  • Cross-reference the column’s data type against unsupported types: XML, geography, geometry, image, text, ntext, sql_variant (partial support), and rowversion/timestamp columns.
  • If the column is a computed column, run the following to check determinism:
  SELECT name, is_computed, definition 
  FROM sys.computed_columns 
  WHERE object_id = OBJECT_ID('YourTableName');
  • Confirm whether the computed column expression uses non-deterministic functions (e.g., GETDATE(), NEWID()).

Step 3: Modify the Statistics Target

  • Remove the unsupported column from the CREATE STATISTICS column list and target only deterministic, comparable columns instead.
  • Example corrected syntax:
  CREATE STATISTICS stat_SalesDate 
  ON dbo.Orders (OrderDate, CustomerID);
  • If statistics are needed on an XML or spatial column, use a computed persisted column with a deterministic extraction (e.g., XML.value() cast to VARCHAR) and build statistics on that computed column instead.

Step 4: Rebuild and Validate the Statistics Object

  • Drop any partially created or broken statistics object first:
  DROP STATISTICS dbo.Orders.stat_SalesDate;
  • Re-run the corrected CREATE STATISTICS statement from Step 3.
  • Check sys.stats and sys.stats_columns to confirm the object was created successfully:
  SELECT s.name, c.column_id, col.name AS column_name
  FROM sys.stats s
  JOIN sys.stats_columns c ON s.stats_id = c.stats_id AND s.object_id = c.object_id
  JOIN sys.columns col ON c.object_id = col.object_id AND c.column_id = col.column_id
  WHERE s.object_id = OBJECT_ID('dbo.Orders');

Alternative or Verification Steps

  • Run DBCC SHOW_STATISTICS ('dbo.Orders', 'stat_SalesDate') to confirm the statistics object populates correctly with histogram and density data.
  • If the target data genuinely requires indexing on an XML or spatial column, create a Primary XML Index or Spatial Index instead, since these indexing structures natively support those data types without relying on standard column statistics.

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

Troubleshooting Guide: SQL Server Error 4145

Why This Error Happens

Error 4145 (“An expression of non-boolean type specified in a context where a condition is expected”) occurs when T-SQL code uses a non-Boolean expression — such as an assignment, a scalar value, or a function returning a non-logical type — inside a control-of-flow statement like IF, WHILE, or CASE WHEN. This is commonly triggered by syntax carried over from older SQL Server versions or other database platforms (like MySQL or Oracle) that allow looser boolean coercion. It can also surface after upgrading to SQL Server 2025, since the updated query optimizer and parser enforce stricter ANSI SQL compliance on conditional expressions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Procedure

  • Check the SQL Server error log or Activity Monitor for the exact batch that triggered Error 4145.
  • Run the failing query manually in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance to capture the full error context, including line number.
  • Look specifically for IF, WHILE, CASE, or ON clauses where a variable or function result is used directly instead of a comparison.

Step 2: Correct the Expression Syntax

  • Rewrite any bare variable or assignment used as a condition. For example, change:
    IF @Status = 1 SET @Result = 1 (if mistakenly written as IF @Result = @Status) into an explicit comparison: IF @Status = 1.
  • Ensure functions returning INT, BIT, or VARCHAR are explicitly compared to a value, e.g., replace IF dbo.GetFlag(@ID) with IF dbo.GetFlag(@ID) = 1.
  • Update any legacy code migrated from MySQL/Oracle that relied on implicit truthy/falsy evaluation (e.g., WHILE @Counter should become WHILE @Counter > 0).

Step 3: Validate Compatibility Level Settings

  • Open SSMS, right-click the database, and go to Properties > Options > Compatibility Level.
  • Confirm the database is set to the correct level for SQL Server 2025 (160 or higher) to ensure the parser behavior matches documented standards.
  • If legacy applications depend on older parsing leniency, test in a staging environment before changing compatibility levels in production.

Step 4: Review Linked Stored Procedures, Triggers, and Functions

  • Use sp_helptext or script out all stored procedures, triggers, and user-defined functions associated with the failing operation.
  • Search for conditional blocks (IF, WHILE, CASE) and cross-reference each with Step 2’s correction pattern.
  • Recompile affected objects using EXEC sp_recompile 'ObjectName'; after making corrections.

Alternative or Verification Steps

  • Re-run the original failing query or application workflow in SSMS or Query Store to confirm Error 4145 no longer appears and execution completes successfully.
  • If the error persists in a third-party application, check for vendor-released hotfixes or compatibility patches for SQL Server 2025, as the stricter parser may require an updated application build.

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

Why This Error Happens

Error 4144 occurs because SQL Server does not support table hints (such as NOLOCK, INDEX, or ROWLOCK) when the target of an INSERT statement is a remote or linked server table. This limitation exists because the query optimizer cannot push locking or indexing directives across the network boundary to a remote provider, as the remote instance manages its own execution plan and locking behavior. The error is almost always triggered by application code or stored procedures that were migrated from local-table logic without accounting for the linked server syntax restrictions.

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 that references Error 4144.
  • Use SQL Server Profiler or Extended Events (xEvents) on the Windows Server 2025 instance to trace the batch text containing the INSERT INTO [LinkedServer].[Database].[Schema].[Table] syntax.
  • Confirm the hint (e.g., WITH (ROWLOCK)) is attached directly to the remote table reference.

Step 2: Remove or Relocate the Table Hint

  • Edit the stored procedure or ad-hoc query to strip the hint from the remote INSERT target, for example changing:
    INSERT INTO [LinkedServer]...[Table] WITH (ROWLOCK) SELECT * FROM LocalTable
    to:
    INSERT INTO [LinkedServer]...[Table] SELECT * FROM LocalTable
  • If locking behavior is required, apply the hint to the source table instead, since hints are only disallowed on the remote insert target, not on local source tables.

Step 3: Validate Linked Server Configuration

  • Open SQL Server Management Studio (SSMS) and navigate to Server Objects > Linked Servers to confirm the provider (e.g., SQLNCLI, MSOLEDBSQL) supports the operation being attempted.
  • Run EXEC sp_serveroption 'LinkedServerName', 'rpc out', 'true'; if remote procedure calls are needed instead of direct INSERT statements.
  • Deploy the corrected procedure to a test environment running Windows Server 2025 to confirm the query compiles without Error 4144.

Step 4: Refactor Using a Staging Table (If Hints Are Required)

  • If query hints are mandatory for performance tuning, insert data into a local staging table first using the hint.
  • Then run a second, hint-free INSERT statement from the staging table to the remote linked server table.

Alternative or Verification Steps

  • Re-run the corrected stored procedure or query in SSMS and confirm it executes without throwing Error 4144 in the Messages tab.
  • If the error persists, check whether the remote table is referenced via synonym or view, as hidden hints embedded in underlying view definitions can also trigger this error indirectly.

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

Troubleshooting Guide: Error 4143 – “The bulk openrowset provider is not a valid target for %.*ls”

Why This Error Happens

This error occurs when OPENROWSET(BULK...) is used in a syntactically invalid context within a T-SQL statement, such as attempting to use it directly inside an INSERT, UPDATE, or as a standalone target instead of as a row source in the FROM clause. SQL Server 2025 strictly validates that the BULK provider can only act as a source of rows being read into a query, not as a destination for data modification. This frequently happens when legacy scripts written for older bulk import patterns are ported without adjusting the required INSERT INTO ... SELECT * FROM OPENROWSET(BULK...) structure.

Step-by-Step Resolution Guide

Step 1: Review the T-SQL Syntax Context

  • Confirm that OPENROWSET(BULK 'filepath', ...) is placed inside the FROM clause of a SELECT statement.
  • Invalid: INSERT OPENROWSET(BULK 'C:\Data\file.csv', ...) VALUES (...).
  • Valid: INSERT INTO TargetTable SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', SINGLE_CLOB) AS DataFile.

Step 2: Correct the Query Structure

  • Rewrite the statement so OPENROWSET(BULK...) only supplies data, never receives it.
  • Example corrected query:
  INSERT INTO dbo.ImportedData (Col1, Col2)
  SELECT Col1, Col2
  FROM OPENROWSET(BULK 'C:\ImportFiles\data.csv', FORMATFILE = 'C:\ImportFiles\format.xml') AS Source;
  • Ensure a table alias (e.g., AS Source) is always applied after the OPENROWSET call.

Step 3: Validate File Path and Permissions on Windows Server 2025

  • Check that the SQL Server service account has Read access to the folder, e.g., C:\ImportFiles\.
  • Use icacls C:\ImportFiles /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)R in an elevated PowerShell/Command Prompt to grant access if needed.
  • Confirm the file is not blocked by Windows (right-click file → Properties → Unblock, if downloaded from the internet).

Step 4: Check for Ad Hoc Distributed Queries Configuration

  • Run the following to ensure the feature is enabled (required for OPENROWSET):
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
  RECONFIGURE;
  • Restart the SQL Server 2025 service via SQL Server Configuration Manager after applying changes.

Alternative or Verification Steps

  • Run the corrected query in SQL Server Management Studio (SSMS) and confirm rows are successfully inserted without Error 4143 appearing in the Messages tab.
  • If the error persists, use BULK INSERT instead of OPENROWSET(BULK...) as an alternative syntax:
  BULK INSERT dbo.ImportedData FROM 'C:\ImportFiles\data.csv' WITH (FORMATFILE = 'C:\ImportFiles\format.xml');

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

Troubleshooting Guide: SQL Server Error 4142 – “Aggregates Are Not Allowed in the RECEIVE List”

Why This Error Happens

This error occurs because Service Broker’s RECEIVE statement does not support aggregate functions (such as COUNT, SUM, MAX, MIN, or AVG) within its column list. SQL Server 2025 enforces strict parsing rules on the RECEIVE statement since it is designed to retrieve raw message rows from a queue, not to perform set-based aggregation. This typically happens when a developer attempts to summarize message data directly in the RECEIVE clause instead of processing the raw data in a subsequent step or temporary table.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance.
  • Locate the stored procedure or script that triggered Error 4142 (check the SQL Server Error Log via Management > SQL Server Logs).
  • Look specifically for RECEIVE statements containing COUNT(*), SUM(), or similar functions in the column selection list.

Step 2: Refactor the RECEIVE Statement

  • Modify the query to select raw columns only (e.g., message_type_name, conversation_handle, message_body) instead of aggregates.
  • Example of incorrect syntax: RECEIVE COUNT(*) FROM MyQueue;
  • Example of corrected syntax: RECEIVE TOP(1) conversation_handle, message_body FROM MyQueue;
  • Save the script to a local path, such as C:\Scripts\SQL\FixBrokerQueue.sql, for version control.

Step 3: Implement a Temporary Table for Aggregation

  • If you need to count or sum the data retrieved from the queue, first RECEIVE the data into a table variable or temporary table.
  • Use the following logic: RECEIVE * FROM MyQueue INTO @TempTable;
  • Perform the required aggregate function (e.g., SELECT COUNT(*) FROM @TempTable) as a separate, subsequent query.

Step 4: Validate Service Broker Configuration

  • Ensure the Service Broker is enabled on the database to rule out configuration conflicts alongside the syntax fix.
  • Run the following T-SQL command to check status: SELECT is_broker_enabled FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the result is 0, enable it using: ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;

Alternative or Verification Steps

  • Verify the Fix: Execute the refactored stored procedure in a test environment. If the query compiles and returns raw row data without throwing Error 4142, the syntax correction was successful.
  • Alternative Approach: If you require real-time counting logic, use an OUTPUT clause in conjunction with the RECEIVE statement to capture data into a table structure before running COUNT or SUM operations in the application layer (C#/.NET or Python) rather than within the T-SQL batch itself.

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

Troubleshooting Guide: Error 4140 – READCOMMITTEDLOCK Lock Hint Not Allowed on INSERT Target Table

Why This Error Happens

This error occurs because SQL Server 2025 does not permit the READCOMMITTEDLOCK (or READCOMMITTED) table-level lock hint to be applied directly to the target table of an INSERT statement. The restriction exists because insert operations rely on exclusive locking semantics, and isolation-level hints like READCOMMITTEDLOCK are only valid for read operations (such as SELECT or FROM clauses) or tables being read within the same statement. This typically surfaces after a migration or query refactor where legacy T-SQL syntax, originally written for SELECT statements, was copied into an INSERT statement without removing the incompatible hint.

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 INSERT statement referenced in the error log.
  • Check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full query text tied to Error 4140.
  • Confirm the hint is applied directly after the target table name, e.g., INSERT INTO dbo.Orders WITH (READCOMMITTEDLOCK) ....

Step 2: Remove the Lock Hint from the INSERT Target

  • Edit the query and strip out WITH (READCOMMITTEDLOCK) or WITH (READCOMMITTED) from the table immediately following INSERT INTO.
  • If the intent was to control locking behavior during the insert, use SET TRANSACTION ISOLATION LEVEL READ COMMITTED; before the statement instead.
  • Example corrected syntax:
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
  INSERT INTO dbo.Orders (OrderID, CustomerID)
  SELECT OrderID, CustomerID FROM dbo.StagingOrders;

Step 3: Apply Hints Only to Source Tables (If Applicable)

  • If the INSERT ... SELECT pattern is being used, move the READCOMMITTEDLOCK hint to the source table in the FROM clause instead of the target.
  • Example: INSERT INTO dbo.Orders SELECT * FROM dbo.StagingOrders WITH (READCOMMITTEDLOCK);
  • Save and redeploy the corrected stored procedure or script via SSMS or your CI/CD deployment pipeline.

Step 4: Audit Stored Procedures and ORM-Generated Scripts

  • Search your codebase and database objects for similar patterns using:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%INSERT%READCOMMITTEDLOCK%';
  • Update any Entity Framework, Dapper, or other ORM-generated raw SQL templates that may be injecting this hint automatically.

Alternative or Verification Steps

  • Re-run the corrected INSERT statement in SSMS; a successful execution with no Error 4140 confirms the fix.
  • If the issue persists in automated jobs (SSIS packages, Agent Jobs), re-deploy the updated package/script and monitor the next scheduled run in SQL Server Agent Job History for a clean completion status.

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

Why This Error Happens

Error 4141 occurs when a CLR user-defined type (UDT) or CLR trigger attempts to modify its own data or schema while already executing within the context of another CLR operation on the same type. SQL Server’s CLR integration layer explicitly blocks recursive or nested ALTER/UPDATE operations against CLR types to prevent state corruption and deadlocks within the SQLCLR hosting environment. This is typically triggered by poorly designed trigger logic, recursive stored procedure calls, or an assembly that attempts self-referential updates during an active transaction.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Object

  • Open SQL Server Management Studio (SSMS) and run the following query to locate active CLR assemblies and types:
  SELECT * FROM sys.assemblies;
  SELECT * FROM sys.assembly_types;
  • Review the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact transaction or stored procedure name tied to Error 4141.
  • Cross-reference the stack trace with any custom CLR triggers (sys.triggers where type_desc = 'CLR_TRIGGER').

Step 2: Review and Refactor the CLR Trigger/Procedure Logic

  • Open the source code project (usually a .cs or .vb SQLCLR project) in Visual Studio 2022/2025.
  • Check for any method that calls SqlContext.Pipe.ExecuteAndSend() or performs an UPDATE/ALTER on the same CLR type from within another CLR method already modifying that type.
  • Remove or restructure recursive calls — move the secondary update logic into a separate transaction scope outside the original CLR context using SqlConnection with Context Connection=false.

Step 3: Rebuild and Redeploy the Assembly

  • In Visual Studio, right-click the SQLCLR project and select Rebuild.
  • Deploy the updated .dll using:
  ALTER ASSEMBLY YourAssemblyName
  FROM 'C:\Deploy\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via Services.msc (SQL Server (MSSQLSERVER)) to clear any cached CLR execution contexts.

Step 4: Adjust CLR Strict Security Settings (If Applicable)

  • Open a new query window in SSMS and verify CLR strict security configuration:
  EXEC sp_configure 'clr strict security', 0;
  RECONFIGURE;
  • Note: Only disable strict security temporarily for testing on Windows Server 2025; re-enable it after confirming the fix (sp_configure 'clr strict security', 1;) for production security compliance.

Alternative or Verification Steps

  • Re-run the original transaction or trigger that caused Error 4141 and confirm it completes without nested update exceptions in the Activity Monitor.
  • If the error persists, drop and recreate the CLR type entirely using DROP TYPE followed by CREATE TYPE ... EXTERNAL NAME, ensuring no overlapping transaction scopes exist in the assembly’s Invoke methods.

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

Troubleshooting Guide: SQL Server Error 4139

Why This Error Happens

Error 4139 occurs because SQL Server’s query optimizer cannot apply query hints (such as index hints, join hints, or locking hints) when a CLR table-valued function (TVF) is accessed indirectly through a view. This is a fundamental architectural limitation—hints require a direct reference to the object they modify, and the view layer breaks that direct binding between the hint and the underlying CLR TVF. The issue typically surfaces after a view is created or altered to wrap a CLR TVF, and a subsequent query against that view attempts to pass through a hint.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View and CLR Function

  • Run sp_helptext 'ViewName' to inspect the view definition and confirm it references a CLR table-valued function.
  • Check the exact query that triggers Error 4139 and note which hint (e.g., WITH (NOLOCK), WITH (INDEX(...))) is being applied.
  • Use SELECT * FROM sys.objects WHERE type = 'FT' to confirm the function is indeed a CLR TVF and not a T-SQL TVF.

Step 2: Remove or Relocate the Hint

  • Edit the query to strip the hint from the view reference directly: SELECT * FROM ViewName instead of SELECT * FROM ViewName WITH (NOLOCK).
  • If isolation level control is the goal, set it at the session level instead using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; before the query runs.
  • Save and redeploy the modified stored procedure, report query, or application code that generated the hinted call.

Step 3: Bypass the View and Query the CLR TVF Directly

  • Rewrite the query to call the CLR table-valued function directly instead of through the view wrapper, e.g., SELECT * FROM dbo.MyClrFunction(@param) WITH (hint) if direct hinting is supported on the function itself.
  • If business logic in the view is required, consider moving that logic into a T-SQL wrapper that calls the CLR TVF without a hint, then apply any needed hints at the outer T-SQL layer instead.
  • Test the rewritten query in SQL Server Management Studio (SSMS) against Microsoft SQL Server 2025 to confirm the error no longer appears.

Step 4: Rebuild or Simplify the View Definition

  • If multiple hints are routinely needed, redesign the view to avoid wrapping the CLR TVF directly—use CREATE OR ALTER VIEW to flatten the logic.
  • Drop unnecessary nested views that daisy-chain through the CLR function, since layered views amplify hint-resolution conflicts.
  • Validate the new view with sp_refreshview 'ViewName' to ensure metadata is current after the rebuild.

Alternative or Verification Steps

  • Verify the fix by executing the original failing query (or its application equivalent) and confirming it returns results without raising Error 4139 in SSMS or the Windows Server 2025 Event Viewer (Application log, source MSSQLSERVER).
  • As an alternative, if hint behavior is critical, migrate the CLR TVF logic into a native T-SQL inline table-valued function where supported, since T-SQL TVFs accessed through views have more flexible hint compatibility.

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

Troubleshooting Guide: SQL Server Error 4138 – Conflicting Locking Hints

Why This Error Happens

Error 4138 occurs when a query specifies a table locking hint (such as NOLOCK, ROWLOCK, or HOLDLOCK) that directly contradicts a locking hint already defined on an underlying view or inherited from a different part of the same query. SQL Server 2025’s query optimizer cannot resolve two incompatible locking strategies for the same object simultaneously, as this would create ambiguity in how the transaction isolation level is applied. This typically happens after a schema migration, a view redefinition, or when legacy T-SQL scripts combine hints like WITH (NOLOCK, TABLOCKX) which are logically exclusive.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Query and Object

  • Open SQL Server Management Studio (SSMS) 2025 and locate the exact query referenced in the error message (check the table name provided in the %.*ls placeholder).
  • Run sp_helptext 'ViewName' to inspect the underlying view definition if the error references a view rather than a base table.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full stack trace tied to Event ID 4138.

Step 2: Remove or Reconcile Duplicate Locking Hints

  • Edit the query to remove redundant or conflicting hints; for example, change WITH (NOLOCK, HOLDLOCK) to just WITH (NOLOCK) or WITH (HOLDLOCK) depending on the intended isolation behavior.
  • If the conflict originates in a view, open the view in SSMS Object Explorer, right-click, select Modify, and strip out the hardcoded locking hint so it does not clash with hints applied at the calling query level.
  • Save the updated view using ALTER VIEW dbo.ViewName AS ... and recompile dependent stored procedures with EXEC sp_recompile 'ViewName';.

Step 3: Validate Compatibility Level and Isolation Settings

  • Navigate to Database Properties > Options in SSMS and confirm the Compatibility Level matches SQL Server 2025 (160) to ensure hint parsing rules are current.
  • Check the session-level isolation setting by running DBCC USEROPTIONS; to confirm no conflicting SET TRANSACTION ISOLATION LEVEL command is layered on top of the table hints.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) after making schema changes.

Step 4: Rebuild Dependent Objects

  • Run sp_refreshview 'ViewName'; to force SQL Server to refresh metadata for the view after hint changes.
  • Re-deploy any affected stored procedures or functions that call the modified view to ensure cached execution plans are not using stale, conflicting hint metadata.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 4138; if it executes without returning the error and the expected result set is returned, the fix is confirmed.
  • As an alternative, if editing the view is not feasible, use SET LOCK_TIMEOUT combined with explicit transaction isolation levels (SET TRANSACTION ISOLATION LEVEL READ COMMITTED;) at the connection level instead of embedding hints directly in the query or view.

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

Troubleshooting Guide: Error 4137 – “A format file cannot be specified together with SINGLE_BLOB”

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) statement incorrectly combines the SINGLE_BLOB option with a FORMATFILE parameter in the same query. The SINGLE_BLOB option tells SQL Server to import the entire file as a single, unparsed binary value, which fundamentally conflicts with the purpose of a format file, since format files are used to define column-level parsing and mapping rules for structured data. Because these two options have mutually exclusive goals—one treats the data as unstructured and the other requires structured mapping—SQL Server 2025 rejects the syntax outright.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Query Syntax

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact BULK INSERT or OPENROWSET statement throwing Error 4137.
  • Check the WITH clause of your query for the simultaneous presence of SINGLE_BLOB and FORMATFILE = 'path\to\file.xml'.
  • Example of broken syntax: WITH (SINGLE_BLOB, FORMATFILE = 'C:\Data\format.xml').

Step 2: Determine Your Intended Import Type

  • Decide whether you actually need to import the file as unstructured binary data (images, JSON blobs, or XML files) or as structured tabular data (CSV, TXT).
  • If you need structured parsing (columns and rows), you must remove SINGLE_BLOB entirely.
  • If you need to treat the file as a single object (e.g., for use with OPENROWSET to load JSON into a variable), you must remove the FORMATFILE reference entirely.

Step 3: Modify the Query for Structured Data

  • Remove the SINGLE_BLOB keyword from the WITH clause if you require column mapping.
  • Ensure the format file path is accessible to the SQL Server service account, for example: C:\SQLData\Import\format.xml.
  • Update the syntax to: BULK INSERT dbo.YourTable FROM 'C:\Data\file.csv' WITH (FORMATFILE = 'C:\Data\format.xml', FIRSTROW = 2);

Step 4: Modify the Query for Binary/Blob Data

  • If unstructured data is required, remove the FORMATFILE parameter from the statement.
  • Update the syntax to use only the blob option: SELECT * FROM OPENROWSET(BULK 'C:\Data\image.jpg', SINGLE_BLOB) AS ImageData;
  • Verify there are no residual commas or syntax artifacts left from the removed parameter that could cause a secondary syntax error.

Alternative or Verification Steps

  • Execute the corrected query in a test environment first; a successful execution without Error 4137 confirms the syntax conflict has been resolved.
  • If you need both binary storage and metadata, consider importing the file via SINGLE_BLOB into a staging table with a VARBINARY(MAX) column first, and then use a separate, secondary script to parse and insert structured data into the final destination table.

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

Troubleshooting Guide: SQL Server Error 4136 — Conflicting Query Hints

Why This Error Happens

Error 4136 occurs when a T-SQL query specifies two or more table or query hints within the same OPTION clause or WITH hint block that are logically incompatible with one another, such as combining FORCESEEK with FORCESCAN, or LOOP JOIN with HASH JOIN in the same join hint context. SQL Server’s query optimizer validates hint combinations during the parsing/binding phase, and when it detects mutually exclusive directives, it rejects the entire query rather than attempting to guess which hint takes priority. This is almost always caused by application code, ORM-generated queries, or stored procedures that were written or modified without accounting for hint compatibility rules, rather than any server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Query and Hints Involved

  • Capture the full error message text, which substitutes the actual hint names into the %.*ls placeholders (e.g., “The hint ‘FORCESEEK’ cannot be used with the hint ‘FORCESCAN'”).
  • Use SQL Server Profiler, Extended Events, or the sys.dm_exec_query_stats / sys.dm_exec_sql_text DMVs to locate the exact batch or stored procedure text that triggered Error 4136.
  • Run the query manually in SSMS to reproduce the error and confirm which OPTION() or WITH() clause contains the conflict.

Step 2: Review and Correct the Conflicting Hint Syntax

  • Open the stored procedure, view, or inline query in SSMS or Azure Data Studio and locate the OPTION (...) or table hint WITH (...) block.
  • Remove one of the two conflicting hints — common conflicting pairs include FORCESEEK + FORCESCAN, NOLOCK + SERIALIZABLE, LOOP JOIN + MERGE JOIN, and READCOMMITTED + READUNCOMMITTED.
  • Save the corrected script, for example located at C:\Scripts\SQL\FixQueryHints.sql, and re-deploy the stored procedure using ALTER PROCEDURE.

Step 3: Check ORM and Application-Generated Queries

  • If the query originates from an ORM (Entity Framework, Dapper, Hibernate, etc.), inspect the query interceptor or raw SQL template responsible for injecting hints.
  • Search application configuration files or query-building classes for hardcoded hint strings and ensure only one isolation/join/index hint type is applied per query.
  • Rebuild and redeploy the application after removing the duplicate or conflicting hint logic.

Step 4: Clear and Rebuild the Plan Cache (If Cached Plans Persist Issues)

  • Run DBCC FREEPROCCACHE on the affected database or use sp_recompile 'SchemaName.ProcedureName' to force recompilation.
  • Confirm no plan guides are forcing the old hint combination by querying sys.plan_guides, and drop any obsolete guides with sp_control_plan_guide 'DROP', 'PlanGuideName'.

Alternative or Verification Steps

  • Re-run the corrected query or execute the stored procedure directly in SSMS to confirm Error 4136 no longer appears and an execution plan is generated successfully.
  • If the error persists, enable Query Store (ALTER DATABASE [YourDB] SET QUERY_STORE = ON;) to track historical query text and pinpoint any remaining hint conflicts across scheduled jobs or linked application modules.

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

Troubleshooting Guide: SQL Server Error 4134 – Computed Column Metadata Mismatch

Why This Error Happens

This error occurs when the metadata for a computed column stored on disk no longer matches the actual column definition recorded in the system catalog, typically due to an interrupted schema change, a failed ALTER TABLE operation, or disk-level corruption affecting page headers. It can also surface after an in-place upgrade (e.g., migrating to SQL Server 2025) where the computed column expression was altered or the collation/data type binding changed without a proper metadata refresh. In most cases, this is SQL Server’s built-in safeguard to prevent the engine from building or using a corrupted index on data that no longer aligns with its defined formula.

Step-by-Step Resolution Guide

Step 1: Run DBCC CHECKDB to Assess the Damage

  • Open SQL Server Management Studio (SSMS) or a query window connected to the affected instance.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output specifically for errors referencing the computed column and table named in the original Error 4134 message.
  • Note the table_id and column_id reported, as you will need them for validation in later steps.

Step 2: Identify and Script Out the Computed Column Definition

  • Query the system catalog to compare the stored definition against expectations: SELECT name, definition, is_persisted FROM sys.computed_columns WHERE object_id = OBJECT_ID('YourTableName');
  • Check if is_persisted matches what the application expects (persisted computed columns are physically stored and more prone to this mismatch).
  • Script the full table definition via SSMS (Right-click table > Script Table as > CREATE To) to preserve the current structure before making changes.

Step 3: Drop and Recreate the Computed Column

  • Run ALTER TABLE YourTableName DROP COLUMN YourComputedColumnName;
  • Re-add the column using the original (or corrected) expression: ALTER TABLE YourTableName ADD YourComputedColumnName AS (YourExpression) PERSISTED;
  • If the column was indexed, rebuild the index using CREATE INDEX IX_YourIndex ON YourTableName(YourComputedColumnName);

Step 4: Restore from Backup if Corruption Persists

  • If DBCC CHECKDB reports allocation or page-level corruption (not just metadata mismatch), isolate the affected table and restore it from the most recent clean full backup.
  • On Windows Server 2025, verify backup file integrity at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\ before restoring.
  • Use RESTORE DATABASE YourDatabaseName FROM DISK = 'BackupPath' WITH REPLACE, RECOVERY; only after confirming the backup predates the corruption event.

Step 5: Update Statistics and Rebuild Indexes

  • After recreating the column, run UPDATE STATISTICS YourTableName WITH FULLSCAN;
  • Rebuild all indexes on the table using ALTER INDEX ALL ON YourTableName REBUILD;
  • This ensures the query optimizer and storage engine are fully synchronized with the new metadata.

Alternative or Verification Steps

  • Re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; after completing the steps above — a clean result with zero allocation or consistency errors confirms the fix.
  • If the error reappears intermittently, check the Windows Event Viewer (Windows Logs > Application) for underlying disk I/O warnings (Event ID 129 or 153), as recurring metadata corruption is often a symptom of failing storage hardware rather than a SQL Server bug.

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

Troubleshooting Guide: SQL Server Error 4135 — Synonyms on Queues Not Allowed

Why This Error Happens

This error occurs because SQL Server’s Service Broker architecture explicitly prohibits the creation of synonyms that reference queue objects. Queues are specialized internal structures used strictly for message storage and retrieval within Service Broker conversations, and they do not support the abstraction layer that synonyms provide. When a developer or migration script attempts to create a synonym pointing to a queue object (rather than a table, view, or procedure), SQL Server 2025 rejects the DDL operation to maintain the integrity of the messaging subsystem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Synonym and Queue

  • Run a query against sys.synonyms to locate the synonym referenced in the error message.
  • Use the following script to cross-reference the base object type:
SELECT name, base_object_name 
FROM sys.synonyms 
WHERE name = 'YourSynonymName';
  • Confirm that the base_object_name points to a Service Broker queue by checking sys.service_queues.

Step 2: Drop the Invalid Synonym

  • Since synonyms cannot legally wrap queue objects, the only immediate fix is removal.
  • Execute the drop command in SQL Server Management Studio (SSMS) or via sqlcmd on Windows Server 2025:
DROP SYNONYM dbo.YourSynonymName;
  • Verify there are no dependent stored procedures or views still referencing this synonym before deletion.

Step 3: Redirect Application Logic to the Queue Directly

  • Update your application code or stored procedures to reference the queue object directly using SEND and RECEIVE statements rather than relying on synonym abstraction.
  • Example direct reference syntax:
RECEIVE TOP(1) * FROM dbo.YourActualQueueName;
  • Ensure connection strings and ORM mappings (e.g., Entity Framework) are updated to bypass the synonym layer for this specific object.

Step 4: Re-deploy and Validate Schema Scripts

  • If this error surfaced during a database migration or DACPAC deployment on Windows Server 2025, check your source control schema files for legacy synonym creation scripts targeting queues.
  • Remove these specific CREATE SYNONYM statements from your build pipeline (e.g., Azure DevOps or GitHub Actions YAML) to prevent recurrence in future deployments.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM sys.synonyms WHERE base_object_name LIKE '%YourQueueName%'; to confirm zero results are returned, verifying the orphaned synonym has been successfully purged.
  • Alternative: If the application architecture requires an abstraction layer for security reasons, create a stored procedure wrapper that internally executes the RECEIVE statement, and grant EXECUTE permissions on that procedure instead of attempting to synonym-wrap the queue.

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

Troubleshooting Guide: SQL Server Error 4133

Why This Error Happens

This error occurs when a T-SQL scalar function’s RETURN statement contains an invalid expression, such as a subquery that returns multiple columns, a table variable, or a non-scalar construct instead of a single value. SQL Server 2025’s parser strictly enforces that the RETURN clause in a scalar function must resolve to exactly one scalar value of a compatible data type. This commonly happens after code migrations, schema changes that alter column counts in referenced views, or when a SELECT statement inside the function inadvertently returns a result set rather than a single value.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Function Definition

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting Error 4133.
  • Run the following query to identify recently modified scalar functions:
  SELECT name, modify_date FROM sys.objects 
  WHERE type = 'FN' ORDER BY modify_date DESC;
  • Script out the function using sp_helptext '<FunctionName>' to inspect the RETURN statement.

Step 2: Correct the RETURN Expression

  • Ensure the expression immediately following RETURN evaluates to a single scalar value (e.g., RETURN @Result; not RETURN (SELECT * FROM Table);).
  • If using a subquery, wrap it to force a single column and row:
  RETURN (SELECT TOP 1 ColumnName FROM TableName WHERE Condition = @Param);
  • Replace any table-valued logic with a declared scalar variable assigned via SELECT ... INTO @Variable prior to the RETURN line.

Step 3: Validate Data Type Compatibility

  • Check that the data type declared in the function header (e.g., RETURNS INT) matches the data type of the expression in the RETURN statement.
  • Use CAST or CONVERT explicitly if there is a mismatch between the variable type and the function’s declared return type.
  • Save and re-deploy the function using CREATE OR ALTER FUNCTION to avoid dropping dependent permissions.

Step 4: Rebuild Dependent Objects

  • Navigate to the Programmability > Stored Procedures folder in SSMS Object Explorer to find any objects calling the fixed function.
  • Execute sp_refreshsqlmodule '<ProcedureName>' on dependent stored procedures to ensure the execution plan cache recognizes the updated scalar return type.
  • Restart the SQL Server Agent service via services.msc on Windows Server 2025 if cached job steps reference the old function schema.

Alternative or Verification Steps

  • Execute the function in isolation using SELECT dbo.FunctionName(@TestParam); to confirm it returns a single value without throwing Error 4133.
  • If the error persists, use sys.dm_exec_describe_first_result_set on the query body to programmatically identify exactly which column or expression is causing the multi-value conflict.

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

Troubleshooting Guide: SQL Server Error 4132 – OPTIMIZE FOR Clause Conversion Failure

Why This Error Happens

This error occurs when the literal value supplied in an OPTIMIZE FOR (@variable = value) query hint does not match the data type declared for that variable. SQL Server’s query optimizer performs a strict implicit conversion check during query compilation, and if the literal cannot be safely cast to the variable’s native type (for example, assigning a string literal to an int or datetime variable, or exceeding precision/scale limits on a decimal), compilation fails immediately. This is often introduced after application code changes, ORM-generated queries, or when parameter sniffing hints are manually added without validating the underlying schema.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Variable and Query

  • Capture the exact query text using Extended Events (sqlserver.error_reported filtered on Error 4132) or the SQL Server Error Log on Windows Server 2025.
  • Locate the OPTIMIZE FOR clause in the query and note the variable name referenced in the %.*ls placeholder.
  • Cross-reference the variable’s DECLARE statement earlier in the batch or stored procedure to confirm its declared data type (e.g., DECLARE @CustomerID INT).

Step 2: Validate Data Type Compatibility

  • Compare the literal value in OPTIMIZE FOR (@CustomerID = 'ABC123') against the declared type; a string literal against an INT variable will trigger Error 4132.
  • Check for mismatched precision/scale on DECIMAL or NUMERIC types (e.g., OPTIMIZE FOR (@Amount = 99999.999) against DECIMAL(5,2)).
  • Verify date/time literals conform to the variable’s format if using DATETIME2, DATE, or SMALLDATETIME.

Step 3: Correct the Query Hint or Variable Declaration

  • Edit the OPTIMIZE FOR clause so the literal matches the variable’s type exactly, casting if necessary: OPTIMIZE FOR (@CustomerID = 100).
  • Alternatively, update the DECLARE statement so the variable type matches the intended literal, ensuring downstream logic in the procedure still functions correctly.
  • If the hint was auto-generated by an ORM (Entity Framework, Dapper, etc.), update the parameter mapping configuration in the application’s connection string or model builder to emit the correct SQL type.

Step 4: Recompile and Test the Query

  • Run sp_recompile 'YourProcedureName' in SQL Server Management Studio (SSMS) 21 or Azure Data Studio to clear any cached, broken execution plan.
  • Execute the corrected query in isolation against a test database to confirm successful compilation before deploying to production.

Step 5: Deploy and Monitor

  • Push the corrected stored procedure or query to production using your standard deployment pipeline (DACPAC, Flyway, or manual T-SQL script).
  • Monitor the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for 24 hours to confirm Error 4132 no longer appears.

Alternative or Verification Steps

  • Verify the fix by re-running the query with SET STATISTICS XML ON and confirming an execution plan is generated without compilation errors.
  • If the error persists under dynamic SQL scenarios, remove the OPTIMIZE FOR hint entirely and rely on OPTIMIZE FOR UNKNOWN as a temporary workaround while auditing all variable declarations in the batch.

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

Why This Error Happens

Error 4131 occurs when a query hint contains an OPTIMIZE FOR clause that specifies the same variable name with a literal value more than once. SQL Server’s query optimizer cannot resolve which literal value to use for cardinality estimation when a duplicate variable binding exists within the same hint block. This is almost always caused by a syntax error introduced during manual query authoring, dynamic SQL string concatenation, or a copy-paste mistake in stored procedures/parameterized queries.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Use SQL Server Management Studio (SSMS) or Azure Data Studio to identify the exact statement referenced in the error, using the variable name provided in the error message (e.g., @CustomerID).
  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the timestamp and session ID tied to the failure.
  • If the query originates from an application, enable SQL Profiler or Extended Events to capture the exact T-SQL text being sent to the server.

Step 2: Inspect the OPTIMIZE FOR Clause Syntax

  • Review the query hint block, which typically looks like:
OPTION (OPTIMIZE FOR (@CustomerID = 1001, @CustomerID = 2002))
  • Confirm whether the same variable (@CustomerID in this example) appears twice with two different literal values — this duplication is the direct trigger for Error 4131.
  • Cross-check any dynamic SQL generation logic (in application code, ORM templates, or stored procedures) that programmatically builds the OPTIMIZE FOR string, as loops or string concatenation bugs often insert duplicate entries.

Step 3: Correct the Duplicate Variable Assignment

  • Remove the redundant assignment so each variable appears only once in the clause:
OPTION (OPTIMIZE FOR (@CustomerID = 1001))
  • If you intended to test multiple scenarios, use OPTIMIZE FOR UNKNOWN instead, which lets SQL Server use statistics-based estimates rather than a hardcoded literal:
OPTION (OPTIMIZE FOR (@CustomerID UNKNOWN))
  • Save the corrected query and redeploy it to the stored procedure, view, or application codebase.

Step 4: Clear the Plan Cache and Re-Test

  • Run DBCC FREEPROCCACHE (in a non-production environment first) to ensure SQL Server isn’t reusing a cached execution plan tied to the old faulty syntax.
  • Re-execute the corrected query directly in SSMS to confirm it compiles and runs without throwing Error 4131.

Alternative or Verification Steps

  • Run the query again with SET SHOWPLAN_TEXT ON to confirm the execution plan compiles successfully without hitting the duplicate-variable compile error.
  • If the issue persists in a CI/CD-deployed stored procedure, check source control history (Git blame) on the .sql file to confirm whether a merge conflict accidentally duplicated an OPTIMIZE FOR entry.

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

Troubleshooting Guide: SQL Server Error 4130 – Duplicate Hint Specified for BULK Rowset

Why This Error Happens

This error occurs when an OPENROWSET(BULK...) statement contains the same hint (such as FORMATFILE, SINGLE_BLOB, SINGLE_CLOB, or CODEPAGE) specified more than once within the same query. SQL Server’s parser rejects the query because each hint is only allowed to appear a single time per BULK rowset definition. This is typically caused by manually written or auto-generated T-SQL scripts (often from legacy migration tools or copy-pasted templates) that inadvertently duplicate a hint clause, rather than being related to permissions or server configuration.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Open the query that triggered Error 4130 in SQL Server Management Studio (SSMS) on your Windows Server 2025 or Windows 11 workstation.
  • Check the SQL Server Error Log (via EXEC sp_readerrorlog; or SSMS > Management > SQL Server Logs) to confirm the exact batch and session that raised Error 4130.

Step 2: Inspect the OPENROWSET(BULK…) Syntax

  • Carefully review the WITH clause of your OPENROWSET(BULK 'filepath', ...) statement.
  • Look specifically for repeated hints, for example:
  SELECT * FROM OPENROWSET(BULK 'C:\Data\import.csv', 
      SINGLE_CLOB, 
      CODEPAGE = '65001',
      CODEPAGE = '1252') AS Data;  -- Duplicate CODEPAGE hint
  • Identify which hint (FORMATFILE, CODEPAGE, ERRORFILE, ROWS_PER_BATCH, SINGLE_BLOB, SINGLE_CLOB, SINGLE_NCLOB) is listed twice.

Step 3: Remove the Duplicate Hint

  • Delete the redundant hint entry, keeping only one instance of each valid hint.
  • Corrected example:
  SELECT * FROM OPENROWSET(BULK 'C:\Data\import.csv', 
      SINGLE_CLOB, 
      CODEPAGE = '65001') AS Data;
  • If the query was generated by an ETL tool (SSIS, Azure Data Factory, or a custom script), check the template or mapping configuration that produced the duplicate hint and correct the source generator logic.

Step 4: Validate File Path and Format File References

  • Ensure the FORMATFILE path (if used) points to a single valid .xml or .fmt file and is not referenced twice under different hint names.
  • Confirm the SQL Server service account has read access to the file path, e.g., C:\ImportFiles\, via Properties > Security in Windows Explorer.

Step 5: Re-run and Monitor the Query

  • Execute the corrected query in SSMS or via sqlcmd on Windows Server 2025.
  • Monitor the SQL Server Error Log again to confirm Error 4130 no longer appears.

Alternative or Verification Steps

  • Run the corrected OPENROWSET(BULK...) query in a test database first and confirm it returns results without throwing Error 4130.
  • If the error persists, use sys.dm_exec_requests and sys.dm_exec_sql_text to capture the exact live query text being executed by an application layer (e.g., SSIS package or .NET app) to rule out a hidden duplicate hint injected at runtime.

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

Troubleshooting Guide: SQL Server Error 4129

Why This Error Happens

This error occurs because SQL Server inline table-valued functions (TVFs) do not support the use of full-text search operators (such as CONTAINS, FREETEXT, CONTAINSTABLE, or FREETEXTTABLE) when the function also relies on correlated parameters or subqueries. The SQL Server query optimizer cannot inline a function definition that mixes these two constructs because full-text predicates require a fixed, non-correlated execution plan to interface with the Full-Text Engine. This is a design limitation of the T-SQL language and query processor, not a configuration or permissions issue, meaning the function code itself must be refactored.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Definition

  • Open SQL Server Management Studio (SSMS) and locate the exact inline function named in the error message (the %.*ls placeholder will show the actual object name in your error log).
  • Run the following query to pull the function definition for review:
SELECT OBJECT_DEFINITION(OBJECT_ID('YourSchema.YourFunctionName'));
  • Check the function body specifically for CONTAINS, FREETEXT, CONTAINSTABLE, or FREETEXTTABLE combined with a parameter passed from an outer query (a correlated parameter).

Step 2: Convert the Inline Function to a Multi-Statement Table-Valued Function (MSTVF)

  • Rewrite the function using the BEGIN...END block syntax with a declared RETURNS @ReturnTable TABLE (...) structure instead of a single RETURN (SELECT ...) statement.
  • Example conversion syntax:
CREATE FUNCTION dbo.YourFunctionName (@SearchTerm NVARCHAR(100))
RETURNS @Results TABLE (ID INT, Description NVARCHAR(255))
AS
BEGIN
    INSERT INTO @Results
    SELECT ID, Description 
    FROM YourTable
    WHERE CONTAINS(Description, @SearchTerm);
    RETURN;
END
  • This decouples the full-text operator execution from the inline expansion logic that the optimizer rejects.

Step 3: Isolate the Full-Text Predicate into a Separate Object

  • If performance is a concern (since MSTVFs can sometimes be slower than inline TVFs), move the full-text search logic into a dedicated Stored Procedure instead of a function.
  • Have the calling application or script execute the stored procedure directly rather than attempting to join it inline within a larger SELECT statement.

Step 4: Restart the Full-Text Filter Daemon Launcher Service

  • Open Services.msc on your Windows Server 2025 instance.
  • Locate SQL Full-text Filter Daemon Launcher (MSSQLSERVER).
  • Restart the service to ensure the Full-Text Engine component is communicating correctly with the Database Engine after your code changes.

Alternative or Verification Steps

  • Verify the Fix: Execute the newly converted Multi-Statement Function or Stored Procedure using a sample correlated value (e.g., SELECT * FROM dbo.YourFunctionName('TestValue')) to confirm the query returns results without throwing Error 4129.
  • Alternative Workaround: If refactoring the function is not immediately feasible, modify the outer query to pass the search term as a local variable first (declare and set the variable before the WHERE clause) rather than passing the column value directly, as this sometimes allows the optimizer to treat the parameter as a constant rather than a correlated input.

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

Troubleshooting Guide: Error 4128 — Internal Error During Remote Query Execution

Why This Error Happens

Error 4128 typically occurs when SQL Server 2025 encounters a breakdown in communication between the local instance and a linked server during distributed query execution. This is most commonly caused by outdated or mismatched OLE DB providers, corrupted linked server metadata, or insufficient permissions on the remote data source. It can also surface when the remote query optimizer receives malformed or incompatible T-SQL syntax that the remote provider cannot translate correctly.

Step-by-Step Resolution Guide

Step 1: Verify Linked Server Configuration

  • Open SQL Server Management Studio (SSMS) and navigate to Server Objects > Linked Servers.
  • Right-click the linked server and select Properties to confirm the provider, data source, and security context are correct.
  • Run the following to test connectivity:
  EXEC sp_testlinkedserver 'YourLinkedServerName';

Step 2: Update or Reinstall the OLE DB Provider

  • Navigate to C:\Program Files\Microsoft SQL Server\160\Shared (or the relevant version path) and confirm the provider DLL (e.g., msoledbsql.dll) is not corrupted.
  • Download and reinstall the latest Microsoft OLE DB Driver for SQL Server from the official Microsoft Download Center.
  • Restart the SQL Server service via Services.msc or run:
  Restart-Service -Name 'MSSQLSERVER'

Step 3: Check Permissions and Security Context

  • Ensure the login used for the remote connection has appropriate db_datareader and db_datawriter roles on the target database.
  • Validate the “Be made using this security context” setting under linked server properties includes a valid remote login and password.
  • Confirm firewall rules on both Windows Server 2025 instances allow traffic on port 1433 (or your custom SQL port).

Step 4: Rebuild Linked Server Metadata

  • Drop and recreate the linked server definition using:
  EXEC sp_dropserver 'YourLinkedServerName', 'droplogins';
  EXEC sp_addlinkedserver 'YourLinkedServerName', 'SQL Server';
  • Reapply any necessary login mappings using sp_addlinkedsrvlogin.

Alternative or Verification Steps

  • Run a simple test query such as SELECT * FROM [YourLinkedServerName].[DatabaseName].[dbo].[TableName] to confirm the error no longer appears.
  • If the issue persists, enable SQL Server Profiler or Extended Events to capture the exact failing remote query and check the SQL Server Error Log for additional context codes accompanying Error 4128.

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

Troubleshooting Guide: SQL Server Error 4127 — COALESCE NULL Constant Error

Why This Error Happens

This error occurs when every argument passed into a COALESCE function evaluates to the literal NULL constant, leaving SQL Server unable to determine a valid data type for the expression. It is almost always caused by poorly validated dynamic SQL, a stored procedure parameter that defaults to NULL without a typed fallback, or a view/computed column definition where all referenced columns resolve to NULL during compilation. This is a query-authoring issue rather than a server configuration or permissions problem, so it typically surfaces during query compilation on SQL Server 2025 instances running on Windows Server 2025 or Windows 11 development environments.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) and check the Messages tab for the exact line number reported alongside Error 4127.
  • Use SELECT * FROM sys.messages WHERE message_id = 4127; to confirm the exact error text and severity level.
  • If the error originates from a stored procedure, run sp_helptext 'YourProcedureName'; to extract the full definition and locate the COALESCE call.

Step 2: Inspect and Correct the COALESCE Expression

  • Locate every argument inside the COALESCE(...) call and confirm at least one is a typed column, variable, or literal (e.g., COALESCE(ColumnName, 0) instead of COALESCE(NULL, NULL)).
  • If the query builds expressions dynamically (common in reporting tools or ORM-generated SQL), add a validation check before execution, such as:
  • IF @Param1 IS NULL AND @Param2 IS NULL SET @Param2 = '';
  • Replace ambiguous NULL placeholders with explicitly cast values, e.g., COALESCE(@Variable, CAST(NULL AS VARCHAR(50))) only if at least one other argument is non-NULL.

Step 3: Rebuild and Recompile Affected Objects

  • On Windows Server 2025/Windows 11 hosting SQL Server 2025, open SSMS and navigate to Database > Programmability > Stored Procedures.
  • Right-click the affected procedure, select Modify, apply the corrected COALESCE logic, and execute ALTER PROCEDURE to save changes.
  • Run EXEC sp_recompile 'YourProcedureName'; from a query window to clear any cached execution plans referencing the old definition.

Step 4: Test in Isolation

  • Extract just the COALESCE statement into a standalone query window in SSMS.
  • Execute it independently with sample literal values to confirm the corrected syntax compiles without triggering Error 4127.

Alternative or Verification Steps

  • Re-run the original stored procedure or application call that originally triggered Error 4127 and confirm it now returns data instead of failing at compile time.
  • If the error persists in dynamically generated SQL (e.g., from an ORM or reporting layer), enable SQL Server Profiler or Extended Events on the Windows Server 2025 instance to capture the exact generated COALESCE statement for further inspection.

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

Troubleshooting Guide: SQL Server Error 4126 – “No full-text indexed columns were found”

Why This Error Happens

This error occurs when you attempt to create or alter a full-text index on a table where no columns have been designated as eligible for full-text indexing, typically due to unsupported data types (such as image, rowversion, or incompatible computed columns) or because all previously indexed columns were removed. It can also happen if the column list passed to CREATE FULLTEXT INDEX is empty or references columns that no longer exist in the schema. In some cases, corrupted metadata in the full-text catalog from an improper upgrade to SQL Server 2025 can cause the engine to lose track of valid column mappings.

Step-by-Step Resolution Guide

Step 1: Verify Column Data Types and Table Schema

  • Run sp_help 'YourTableName' to inspect the data types of all columns.
  • Confirm that at least one column uses a full-text-compatible type: char, varchar, nvarchar, text, ntext, xml, varbinary, or image (with a associated type column).
  • Remove any references to deprecated or dropped columns from your index creation script.

Step 2: Rebuild the Full-Text Index Definition

  • Drop the existing broken full-text index using:
  DROP FULLTEXT INDEX ON YourTableName;
  • Recreate it explicitly, specifying valid columns and a unique key index:
  CREATE FULLTEXT INDEX ON YourTableName(ColumnName LANGUAGE 1033)
  KEY INDEX PK_YourTableName
  ON YourFullTextCatalog;
  • Ensure PK_YourTableName references an existing unique, single-column, non-nullable index.

Step 3: Validate Full-Text Catalog Integrity

  • Open SQL Server Management Studio (SSMS) and navigate to Database > Storage > Full Text Catalogs.
  • Right-click the catalog and select Rebuild if metadata corruption is suspected.
  • On Windows Server 2025, confirm the SQL Full-text Filter Daemon Launcher service is running via services.msc.

Step 4: Check for Column-Level Permissions and Filegroup Issues

  • Verify the SQL Server service account has CONTROL permission on the target table.
  • Confirm the filegroup hosting the full-text catalog is online and not set to read-only:
  SELECT name, is_read_only FROM sys.filegroups;

Alternative or Verification Steps

  • After recreating the index, run SELECT * FROM sys.fulltext_index_columns WHERE object_id = OBJECT_ID('YourTableName'); to confirm columns are now registered.
  • If the error persists, drop and recreate the entire full-text catalog, then reapply indexes one table at a time to isolate the problematic column or schema element.

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

Troubleshooting Guide: Error 4125 – “The function ‘%.*ls’ must have an OVER clause”

Why This Error Happens

This error occurs when a T-SQL query attempts to use a window function (such as ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), or certain analytic functions like LAG()/LEAD()) without the mandatory OVER() clause. SQL Server 2025’s query parser strictly enforces ANSI SQL compliance for these ranking and analytic functions, as they are only meaningful within a defined partition or ordering context. This is typically a code-level syntax issue rather than a server configuration problem, often introduced during query migrations, ORM-generated SQL, or copy-pasted code where the OVER() clause was accidentally truncated or omitted.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query text from the error message in SSMS or the application log; the %.*ls placeholder will be replaced with the actual function name (e.g., ROW_NUMBER).
  • Check Extended Events or the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the session ID and query hash tied to the failure.
  • If the query comes from an application, enable SQL Profiler or Query Store (SELECT * FROM sys.query_store_query_text) to trace the exact statement sent to the server.

Step 2: Correct the T-SQL Syntax

  • Locate the window function call in the script and append a valid OVER() clause.
  • At minimum, an empty OVER() is required for aggregate window functions, e.g., SUM(Sales) OVER().
  • For ranking functions, include PARTITION BY and/or ORDER BY, e.g.:
  SELECT ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY HireDate) AS RowNum
  FROM Employees;
  • Save and redeploy the corrected stored procedure, view, or function using SSMS or your CI/CD deployment pipeline.

Step 3: Check for ORM or Application-Generated SQL Issues

  • If the query originates from Entity Framework, Dapper, or a reporting tool, inspect the generated SQL for truncation bugs (some ORM versions strip clauses when exceeding string length limits).
  • Update the ORM/data access library to the latest patched version compatible with SQL Server 2025.
  • Rebuild any dynamic SQL strings in application code to explicitly include the OVER() clause rather than concatenating it conditionally.

Step 4: Validate Compatibility Level Settings

  • Run the following to confirm the database compatibility level isn’t forcing deprecated parsing behavior:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If necessary, set it to the SQL Server 2025 compatibility level (170):
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Re-run the corrected query in SSMS or Azure Data Studio and confirm it executes without Error 4125; check sys.dm_exec_query_stats to verify the query plan compiles successfully.
  • If the error persists in a third-party application, roll back to a previous known-good query version or contact the vendor for a patch, as the issue may be baked into a compiled stored procedure or reporting template.

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

Troubleshooting Guide: SQL Server Error 4124 — “The Parameters Supplied for the Batch Are Not Valid”

Why This Error Happens

Error 4124 typically occurs when SQL Server 2025 receives a parameterized batch request (often via sp_executesql, ODBC, or OLE DB providers) where the parameter definitions do not match the actual data types, lengths, or count expected by the query engine. This mismatch is frequently caused by outdated client drivers, corrupted connection metadata, or application code that dynamically builds parameter arrays incorrectly. In some cases, this is triggered after an in-place upgrade to Windows Server 2025 or Windows 11 where legacy driver versions (such as older ODBC Driver 17) remain cached and conflict with the new TDS protocol version used by SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify and Update the Client Driver

  • Open ODBC Data Source Administrator (64-bit) via odbcad32.exe and check the driver version under the “Drivers” tab.
  • Ensure you are running Microsoft ODBC Driver 18 for SQL Server or later, which fully supports the TDS 8.0 protocol used in SQL Server 2025.
  • Uninstall older drivers via Settings > Apps > Installed Apps to prevent version conflicts.
  • Reinstall the latest driver package from the official Microsoft Download Center.

Step 2: Inspect the Parameterized Query Syntax

  • Open the failing stored procedure or query in SQL Server Management Studio (SSMS) 21.
  • Check for mismatched parameter counts between the sp_executesql call and the @params definition string.
  • Example of a common error:
  EXEC sp_executesql N'SELECT * FROM Orders WHERE OrderID = @ID', N'@ID int', @ID = '12345'
  • Ensure the data type passed (e.g., varchar) matches the data type declared (e.g., int).

Step 3: Clear Cached Execution Plans

  • Corrupted or stale execution plans can cause SQL Server to misinterpret parameter sniffing data.
  • Run the following command in a New Query window to clear the specific plan cache:
  DBCC FREEPROCCACHE;
  • If the issue persists only for a specific database, use ALTER DATABASE [YourDB] SET PARAMETERIZATION SIMPLE; to test if forced parameterization is the root cause.

Step 4: Check Windows Server 2025 Security Policies

  • Navigate to Control Panel > Administrative Tools > Local Security Policy.
  • Verify that the “Network Security: Minimum session security for NTLM SSP based clients” setting hasn’t blocked specific encryption methods required by the new driver handshake.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after any policy changes.

Alternative or Verification Steps

  • Verification: Run the specific failing query directly in SSMS using hardcoded values instead of parameters. If it succeeds, the issue is confirmed to be in the parameter-passing logic of the client application rather than the database engine itself.
  • Alternative Fix: If the error persists only on Windows 11 client machines, temporarily switch the connection string from “Encrypt=Mandatory” to “Encrypt=Optional” to rule out a TLS/SSL handshake issue interfering with the parameter payload.

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

Troubleshooting Guide: SQL Server Error 4123 — “Window element in OVER clause cannot also be specified in WINDOW clause”

Why This Error Happens

This error occurs when a T-SQL query uses the named WINDOW clause (introduced to simplify reuse of window definitions) alongside an OVER clause that redundantly redefines elements such as PARTITION BY, ORDER BY, or the frame specification that are already declared in the named window. SQL Server 2025 enforces strict separation between the two: once a window is defined in a WINDOW clause and referenced by name in OVER(window_name), the OVER clause cannot also carry its own partitioning, ordering, or framing logic. This is not a permissions or configuration issue — it is a query authoring/syntax conflict introduced by duplicate or overlapping window element definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Query

  • Open the query that triggered Error 4123, typically visible in SQL Server Management Studio (SSMS) or Azure Data Studio’s error pane.
  • Locate the specific OVER() clause referenced in the error message and cross-reference it against the WINDOW clause definition in the same SELECT statement.
  • Example conflict pattern:
  SELECT SUM(SalesAmount) OVER (myWindow ORDER BY OrderDate)
  FROM Sales
  WINDOW myWindow AS (PARTITION BY RegionID ORDER BY OrderDate);

Step 2: Remove Duplicate Window Elements from the OVER Clause

  • Strip out any PARTITION BY, ORDER BY, or ROWS/RANGE frame specifications from the OVER clause if that same element already exists in the named WINDOW definition.
  • Corrected syntax should reference the window name alone:
  SELECT SUM(SalesAmount) OVER (myWindow)
  FROM Sales
  WINDOW myWindow AS (PARTITION BY RegionID ORDER BY OrderDate);
  • If you need different ordering or framing for this specific aggregate, do not use the named window reference — instead define the OVER clause fully inline without calling the WINDOW clause.

Step 3: Validate the WINDOW Clause Definition

  • Open the WINDOW clause block and confirm each named window (e.g., myWindow) contains the complete PARTITION BY, ORDER BY, and frame specification needed.
  • Ensure no two OVER clauses in the same query attempt to append conflicting elements to the same window name.
  • Run the query in isolation using SSMS’s “Parse” feature (Ctrl+F5 equivalent / Query > Parse) to catch syntax conflicts before full execution.

Step 4: Rebuild and Test the Query Incrementally

  • Comment out all but one window function call, confirm it executes without Error 4123, then reintroduce additional OVER/WINDOW references one at a time.
  • This isolates which specific OVER clause is causing the duplicate definition conflict in complex multi-window queries.

Alternative or Verification Steps

  • Verify the fix by executing the corrected query directly in SSMS connected to your SQL Server 2025 instance — confirm it returns results without raising Error 4123 in the Messages tab.
  • As an alternative, bypass the WINDOW clause entirely and write the OVER clause fully inline (PARTITION BY, ORDER BY, and frame spec all in one OVER()) for queries with only a single window function, avoiding the named window conflict altogether.

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

Troubleshooting Guide: SQL Server Error 4122 — Remote Table-Valued Function Calls Not Allowed

Why This Error Happens

Error 4122 occurs when a query attempts to invoke a table-valued function (TVF) through a four-part name against a linked server, which SQL Server 2025 does not support regardless of provider. This typically happens because the linked server provider does not support the IDBSchemaRowset interface required to resolve the function’s result set schema remotely, or because the query was auto-generated by an ORM/application expecting cross-server TVF execution. Additionally, this can surface if the linked server’s OLE DB provider options (such as “Allow InProcess” or “Nested Queries”) are misconfigured, causing SQL Server to misinterpret the remote object as a function call rather than a standard table reference.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Linked Server Call

  • Capture the exact query text using SQL Server Profiler or Extended Events, filtering on Error Number = 4122.
  • Confirm the syntax uses a four-part name pattern, such as SELECT * FROM LinkedServerName.DBName.SchemaName.FunctionName(param).
  • Note that this pattern is explicitly unsupported in SQL Server, even in the 2025 release, due to architectural limitations in remote schema resolution.

Step 2: Refactor the Query to Use OPENQUERY

  • Rewrite the remote TVF call using the OPENQUERY pass-through function instead of a direct four-part reference.
  • Example syntax:
  SELECT * FROM OPENQUERY(LinkedServerName, 'SELECT * FROM SchemaName.FunctionName(param_value)')
  • Deploy this change to the stored procedure or application code located typically in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ scripts or source control repository.
  • Test the rewritten query in SQL Server Management Studio (SSMS) 21 to confirm it returns data without throwing Error 4122.

Step 3: Verify Linked Server Provider Configuration

  • Open SSMS, navigate to Server Objects > Linked Servers > [Your Linked Server] > Properties.
  • Check the Provider Options tab and ensure “Nested Queries” and “Allow InProcess” are enabled for the specific OLE DB provider (e.g., MSOLEDBSQL19).
  • Run the following T-SQL to validate provider settings programmatically:
  EXEC master.dbo.sp_linkedsrvlogin @rmtsrvname = 'LinkedServerName';
  EXEC sp_helpserver 'LinkedServerName';
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) after making provider changes.

Step 4: Create a Local Wrapper Stored Procedure

  • As a long-term fix, create a local stored procedure on the calling server that internally uses OPENQUERY to abstract the remote TVF logic.
  • This prevents developers or applications from accidentally reintroducing a four-part TVF call in future code.
  • Grant execute permissions to the wrapper procedure using:
  GRANT EXECUTE ON dbo.usp_GetRemoteFunctionData TO [YourAppRole];

Alternative or Verification Steps

  • Run the refactored OPENQUERY statement directly in SSMS 21 connected to the local instance; a successful result set with no Error 4122 confirms the fix.
  • If OPENQUERY still fails, verify the remote server’s compatibility level and ensure the TVF is marked as SCHEMABINDING and does not rely on dynamic SQL internally, as this can cause pass-through query rejection.

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

Troubleshooting Guide: SQL Server Error 4121

Why This Error Happens

Error 4121 occurs when SQL Server’s query parser cannot resolve a referenced column, user-defined function (UDF), or aggregate within the current execution scope. This typically happens because the object does not exist in the specified schema, the calling context lacks sufficient EXECUTE or SELECT permissions on that object, or the function/column name was misspelled or the schema binding changed after a deployment. In Microsoft SQL Server 2025, this can also surface after an in-place upgrade where compatibility-level settings alter how scalar UDFs are inlined or resolved.

Step-by-Step Resolution Guide

Step 1: Verify Object Existence and Schema Reference

  • Run SELECT * FROM sys.objects WHERE name = 'YourFunctionOrColumnName'; to confirm the object exists in the target database.
  • Check if the object was created under a non-default schema (e.g., dbo vs. a custom schema) and ensure your query explicitly references it, such as SELECT dbo.YourFunction(column1) FROM YourTable;.
  • If the object is missing entirely, redeploy the relevant .sql script from your source control or migration pipeline.

Step 2: Check Permissions on the Database Principal

  • Open SQL Server Management Studio (SSMS) and navigate to Security > Logins for the login experiencing the error.
  • Run the following to confirm grants: SELECT * FROM fn_my_permissions('dbo.YourFunction', 'OBJECT');.
  • If permissions are missing, grant them explicitly: GRANT EXECUTE ON OBJECT::dbo.YourFunction TO [YourUserOrRole];.

Step 3: Validate Compatibility Level and Collation Settings

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to check the current setting.
  • If the database was recently upgraded to run on SQL Server 2025, ensure compatibility level is set correctly using ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;.
  • Confirm that column collations match between joined tables, especially after migrating from older instances, using SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('YourTable');.

Step 4: Rebuild or Refresh Dependent Views and Procedures

  • Execute EXEC sp_refreshsqlmodule 'dbo.YourViewOrProcedure'; to force SQL Server to recompile and re-resolve all referenced columns and functions.
  • Check the Windows Event Viewer (Event Viewer > Applications and Services Logs > MSSQLSERVER) for related schema-binding errors that may have occurred during the last deployment.

Alternative or Verification Steps

  • After applying fixes, re-run the original query that triggered Error 4121 and confirm it returns results without exceptions in SSMS’s Messages tab.
  • If the error persists, use SQL Server Profiler or Extended Events to trace the exact batch text and line number causing the resolution failure, then cross-reference it against the sys.sql_expression_dependencies system view for broken object links.

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

Troubleshooting Guide: Error 4120 – Database Name Prefix Not Allowed for User-Defined Function

Why This Error Happens

This error occurs because SQL Server 2025 does not permit a user-defined function (UDF) call to be qualified with a database name when used in certain contexts, such as computed columns, check constraints, or default constraints. SQL Server restricts cross-database references in these specific contexts for binding and dependency-tracking reasons, since the object must be resolvable within the current database’s schema binding rules. This typically happens when a function is referenced as DatabaseName.SchemaName.FunctionName instead of the permitted SchemaName.FunctionName or dbo.FunctionName format within the same database context.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement

  • Review the error message in SQL Server Management Studio (SSMS) or the application log to locate the exact line number and object (view, constraint, or computed column) causing Error 4120.
  • Run the following query to locate recently modified objects that may reference cross-database functions:
SELECT name, object_id, modify_date 
FROM sys.objects 
WHERE type IN ('V', 'FN', 'TR') 
ORDER BY modify_date DESC;
  • Confirm whether the function call uses a three-part or four-part name (e.g., MyDB.dbo.MyFunction()).

Step 2: Remove the Database Name Prefix

  • Edit the script, view, or constraint definition to remove the leading database name from the function call.
  • Change SELECT MyDB.dbo.fn_CalculateTotal(OrderID) to SELECT dbo.fn_CalculateTotal(OrderID).
  • Ensure the function exists in the same database as the object referencing it; cross-database scalar function calls are not supported in schema-bound contexts.

Step 3: Migrate or Replicate the Function Locally

  • If the function genuinely resides in a different database, create a local copy of the function within the target database instead of referencing it remotely.
  • Use SSMS to script out the function definition: right-click the function → Script Function as → CREATE To → New Query Editor Window.
  • Execute the script against the local database so the dependent object can bind to a function within its own context.

Step 4: Rebuild Dependent Objects

  • After correcting the function reference, drop and recreate any views, computed columns, or constraints that failed to bind.
ALTER TABLE dbo.Orders 
ADD TotalAmount AS (dbo.fn_CalculateTotal(OrderID));
  • Validate that schema binding (if used) compiles without error by running sp_refreshsqlmodule on dependent views.

Step 5: Restart Dependent Services (If Applicable)

  • If the error persists in SSRS, SSIS, or an application connection pool, restart the SQL Server Agent or the application service on Windows Server 2025 to clear cached execution plans.
  • Open Services.msc, locate SQL Server (MSSQLSERVER), and restart the service to flush the plan cache.

Alternative or Verification Steps

  • Run DBCC FREEPROCCACHE and re-execute the original query/object creation script to confirm Error 4120 no longer appears.
  • If the function must remain centralized for multiple databases, consider converting it into a CLR function or replicating it via a scheduled synchronization job instead of relying on cross-database three-part naming.

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

Why This Error Happens

Error 4119 occurs when a column defined with a CLR user-defined type (UDT) attempts to bind a default value to a property that lacks a public, accessible setter in the compiled assembly. SQL Server’s CLR integration engine requires strict adherence to serialization and mutator contracts (IBinarySerialize), and if the assembly was compiled with read-only properties, internal setters, or mismatched attributes, the engine cannot invoke the setter during default value assignment. This is often compounded by an outdated or corrupted CLR assembly registered in the database that no longer matches the metadata SQL Server expects.

Step-by-Step Resolution Guide

Step 1: Verify the CLR Assembly and Property Definitions

  • Open the source project for the CLR UDT and confirm every property intended to hold a default value has a public set; accessor.
  • Check that the class is decorated correctly with [Serializable] and [SqlUserDefinedType(Format.Native)] or Format.UserDefined as appropriate.
  • Rebuild the assembly in Visual Studio targeting the .NET version supported by SQL Server 2025 (typically .NET 8 LTS runtime compatibility mode).

Step 2: Re-register the Assembly in SQL Server

  • Drop the existing assembly reference using:
    DROP TYPE dbo.YourCLRType;
    DROP ASSEMBLY YourAssemblyName;
  • Re-deploy the updated DLL with:
    CREATE ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Recreate the type:
    CREATE TYPE dbo.YourCLRType EXTERNAL NAME YourAssemblyName.[YourClassName];

Step 3: Adjust the Table Definition to Avoid Inline Default Binding

  • Instead of assigning a default directly in the column property setter, apply the default at the table level using a constraint:
    ALTER TABLE dbo.YourTable ADD CONSTRAINT DF_YourColumn DEFAULT (CONVERT(dbo.YourCLRType, '<serialized_value>')) FOR YourColumn;
  • Ensure the serialized string format matches the UDT’s Parse() method output exactly, as SQL Server uses this method to construct the default instance.

Step 4: Enable CLR Integration and Confirm Trust Settings

  • Run EXEC sp_configure 'clr enabled', 1; RECONFIGURE; to ensure CLR execution is active on the instance.
  • On Windows Server 2025 / Windows 11, verify the assembly is signed and trusted, or mark the database as trustworthy with:
    ALTER DATABASE YourDB SET TRUSTWORTHY ON;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to clear cached assembly metadata.

Alternative or Verification Steps

  • Run SELECT * FROM sys.assembly_types WHERE name = 'YourCLRType'; to confirm the type registered correctly without errors, then insert a test row relying on the default value.
  • If the error persists, bypass the CLR default entirely by handling default value logic in application code or via an INSTEAD OF INSERT trigger that explicitly constructs the CLR object before insertion.

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

Troubleshooting Guide: SQL Server Error 4118 — Invalid Expression in FOR UPDATE Clause

Why This Error Happens

Error 4118 occurs when a cursor’s FOR UPDATE clause references a column name that does not exist in the underlying SELECT statement, is misspelled, or references a column from a table not included in the cursor’s result set. This can also happen if the column specified is a computed column, a column from a view that is not updatable, or a column that does not map directly to a single base table (such as one resulting from a JOIN, aggregate function, or expression). Essentially, SQL Server cannot resolve which physical column in which base table should be locked for the update operation.

Step-by-Step Resolution Guide

Step 1: Review and Validate the Cursor Definition

  • Open the stored procedure or script containing the DECLARE CURSOR statement that is throwing Error 4118.
  • Check the exact column names listed after the FOR UPDATE OF clause and compare them character-by-character against the columns in your SELECT list.
  • Example of a broken query: DECLARE cur CURSOR FOR SELECT OrderID, CustName FROM Orders FOR UPDATE OF CustomerName (note the mismatch: CustName vs CustomerName).

Step 2: Ensure Columns Belong to a Single Base Table

  • Confirm that the column referenced in FOR UPDATE OF is not derived from a JOIN, subquery, or calculated expression (e.g., Price * Quantity AS Total).
  • If your SELECT statement pulls from multiple tables, explicitly qualify the column and ensure only one underlying, updatable table is targeted.
  • Rewrite the cursor to select directly from the base table only, isolating the join logic into a separate read-only reference if necessary.

Step 3: Check for Computed or Non-Updatable Columns

  • Query the system catalog to verify if the column is computed: run SELECT name, is_computed FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName'); in SQL Server Management Studio (SSMS).
  • If is_computed returns 1, remove that column from the FOR UPDATE OF clause, as computed columns cannot be locked for updates via a cursor.

Step 4: Rebuild the Cursor with Correct Syntax

  • Modify the T-SQL script to align the FOR UPDATE clause with the exact schema. The correct syntax should look like:
  • DECLARE cur CURSOR FOR SELECT OrderID, Status FROM dbo.Orders FOR UPDATE OF Status;
  • Save the script and redeploy the stored procedure using SSMS or Azure Data Studio connected to your SQL Server 2025 instance.

Alternative or Verification Steps

  • Verify the Fix: Execute the stored procedure manually in a test environment (using EXEC YourProcedureName) and confirm the cursor opens and fetches rows without throwing Error 4118.
  • Alternative Solution: If the issue persists due to complex multi-table logic, refactor the cursor logic to use a MERGE statement or a standard UPDATE...WHERE CURRENT OF pattern instead of a direct FOR UPDATE OF column list, which often resolves ambiguity errors in Windows Server 2025 environments.

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

Troubleshooting Guide: SQL Server Error 4117 – Schema Altered Too Frequently

Why This Error Happens

This error occurs when SQL Server’s query optimizer detects that a table containing a computed column has had its schema modified (via DDL operations) in rapid succession, preventing the engine from generating a stable execution plan. It is frequently triggered by automated scripts, ORM frameworks, or CI/CD pipelines that execute ALTER TABLE statements in tight loops against tables with computed or persisted computed columns. The underlying cause is typically a lack of transaction batching or DDL throttling logic in the calling application, combined with metadata version caching conflicts in tempdb.

Step-by-Step Resolution Guide

Step 1: Identify the Source of Rapid Schema Changes

  • Query the SQL Server Extended Events (XEvents) session or Profiler trace for object_altered events on the affected table.
  • Run the following to check recent DDL activity:
SELECT * FROM sys.fn_trace_gettable('C:\TraceLogs\ddl_trace.trc', default)
WHERE EventClass = 164 AND ObjectName = 'YourTableName';
  • Cross-reference timestamps with application logs (Windows Event Viewer → Applications and Services Logs → MSSQLSERVER) to pinpoint the offending process or job.

Step 2: Refactor or Throttle the DDL Operations

  • Locate the application code, SSIS package, or scheduled job responsible for repeated ALTER TABLE calls.
  • Introduce a delay or batching mechanism (e.g., WAITFOR DELAY '00:00:05') between consecutive schema-altering transactions.
  • If using an ORM (Entity Framework, Hibernate), disable automatic migration-on-startup features that may re-trigger schema validation on every connection.

Step 3: Rebuild the Computed Column Index or Statistics

  • If the issue persists, drop and recreate the computed column to force a metadata refresh:
ALTER TABLE YourTableName DROP COLUMN ComputedColumnName;
ALTER TABLE YourTableName ADD ComputedColumnName AS (Expression) PERSISTED;
  • Update statistics immediately after to stabilize the query plan:
UPDATE STATISTICS YourTableName WITH FULLSCAN;

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

  • On Windows Server 2025, open Services.msc, locate SQL Server (MSSQLSERVER), and restart the service to clear corrupted cached plans.
  • Alternatively, run a targeted cache clear without a full restart:
DBCC FREEPROCCACHE;
DBCC DROPCLEANBUFFERS;

Alternative or Verification Steps

  • Verify the fix by re-running the original query or stored procedure that triggered Error 4117; monitor Extended Events to confirm no DDL events fire during the query window.
  • If the error recurs under load, consider isolating the computed column into a separate indexed view or trigger-based calculation to decouple it from direct ALTER TABLE schema churn.

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

Troubleshooting Guide: Error 4116 – Invalid NTILE Argument in SQL Server 2025

Why This Error Happens

Error 4116 occurs when the NTILE window function receives an argument that is not a positive integer or bigint expression. This typically happens when a variable, column, or calculated expression passed into NTILE() evaluates to zero, a negative number, NULL, or a non-integer data type such as decimal or varchar. SQL Server’s query optimizer strictly validates this parameter at parse time, so even dynamically generated values that could resolve to an invalid number will trigger a compilation failure before the query executes.

Step-by-Step Resolution Guide

Step 1: Locate the NTILE Function Call in the Query

  • Open the query or stored procedure referenced in the error message using SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Identify the exact syntax: NTILE(integer_expression) OVER (ORDER BY column_name).
  • Check whether the argument is a literal number, a variable (e.g., @BucketCount), or a subquery result.

Step 2: Validate the Input Expression

  • Confirm the variable or column feeding NTILE is declared as INT or BIGINT — not DECIMAL, FLOAT, or VARCHAR.
  • Run a diagnostic check: SELECT @BucketCount AS CheckValue; to ensure the value is greater than zero and not NULL.
  • If the value comes from a table column, add a WHERE clause or CASE statement to filter out zero, negative, or NULL entries before the function executes.

Step 3: Correct the Data Type or Default Value

  • Explicitly cast the expression: NTILE(CAST(@BucketCount AS INT)) to force the correct data type.
  • If the source value can legitimately be NULL or zero, use ISNULL(@BucketCount, 4) or a similar fallback to guarantee a positive integer is always passed.
  • Update any application-layer code (e.g., .NET, Python connectors) that dynamically builds this T-SQL string to validate inputs before sending the query to SQL Server 2025.

Step 4: Rebuild and Test the Query

  • Save the corrected script and clear the procedure cache if the object was previously compiled with bad logic: DBCC FREEPROCCACHE; (use cautiously in production environments).
  • Re-execute the query in a test environment on Windows Server 2025 to confirm the compilation error no longer appears.

Alternative or Verification Steps

  • Run SELECT OBJECT_DEFINITION(OBJECT_ID('YourProcName')) to review the compiled definition and confirm the fix was saved correctly to the stored procedure.
  • If the error persists intermittently, enable SQL Server Extended Events to trace the exact runtime value being passed into NTILE, as the issue may stem from upstream ETL jobs feeding bad data rather than the query itself.

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

Troubleshooting Guide: SQL Server Error 4115 — “The reference to column is not allowed in an argument to a TOP”

Why This Error Happens

This error occurs because SQL Server’s query parser does not allow the TOP clause argument to directly reference a column name from the table being queried; TOP expects a constant, variable, or a scalar subquery expression, not a correlated column reference. This typically happens when a developer attempts to dynamically limit result rows based on a per-row column value (e.g., TOP (SomeColumn)), which conflicts with how SQL Server compiles the execution plan before row context is established. It is a query design/syntax issue rather than a server configuration, permissions, or corruption problem.

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 message (check the application log or SQL Server error log for the full statement text).
  • Look specifically for a TOP (column_name) pattern inside a SELECT statement, especially within subqueries, CTEs, or APPLY operators.
  • Confirm the column referenced belongs to the outer or same-level table rather than being a declared variable.

Step 2: Replace the Column Reference with a Variable

  • Declare a local variable and assign the column value to it before using it in the TOP clause.
  • Example fix:
  DECLARE @RowLimit INT;
  SELECT @RowLimit = LimitColumn FROM Config WHERE ID = 1;
  SELECT TOP (@RowLimit) * FROM Orders ORDER BY OrderDate DESC;
  • If the row limit must vary per outer row (correlated), restructure the query using CROSS APPLY with a subquery instead of a direct TOP reference:
  SELECT o.CustomerID, t.*
  FROM Customers o
  CROSS APPLY (
      SELECT TOP (o.MaxOrders) *
      FROM Orders ord
      WHERE ord.CustomerID = o.CustomerID
      ORDER BY ord.OrderDate DESC
  ) t;

Note: even here, o.MaxOrders must resolve to a valid outer reference supported by CROSS APPLY, which is allowed because it is evaluated per outer row — unlike a direct same-level column reference.

Step 3: Validate Query Logic in a Test Environment

  • Run the corrected query against a non-production database or a restored copy on your Windows Server 2025 / Windows 11 SQL Server instance.
  • Use SET STATISTICS IO, TIME ON; to confirm the query compiles and executes without error 4115.
  • Check the Messages tab in SSMS for successful execution with no parser-level exceptions.

Step 4: Update Application or Stored Procedure Code

  • If the faulty query originates from a stored procedure, ALTER the procedure with the corrected syntax:
  ALTER PROCEDURE dbo.GetTopOrders
  AS
  BEGIN
      DECLARE @Limit INT = (SELECT TOP 1 LimitValue FROM Settings);
      SELECT TOP (@Limit) * FROM Orders ORDER BY OrderDate DESC;
  END
  • Redeploy the updated procedure/script to all affected environments (Dev, QA, Production).

Alternative or Verification Steps

  • Re-run the original failing query/report in the application front-end and confirm error 4115 no longer appears in the SQL Server logs (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If the issue persists, enable SQL Server Profiler or Extended Events to capture the exact runtime statement and confirm no other nested TOP (column) patterns exist elsewhere in linked views, functions, or triggers.

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

Troubleshooting Guide: SQL Server Error 4114

Why This Error Happens

Error 4114 occurs when a Transact-SQL statement calls a built-in or user-defined function with an incorrect number of arguments. This is typically caused by a syntax mistake in application code, a recent schema change to a user-defined function that altered its parameter signature, or a mismatch between a deployed stored procedure and the function it references after an update or migration. It can also surface after upgrading to SQL Server 2025 if deprecated function signatures were removed or modified in the new engine version.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Function

  • Check the full error message text, which includes the function name and the exact number of arguments required.
  • Use SQL Server Management Studio (SSMS) or Azure Data Studio to locate the query from the application log, SQL Profiler trace, or Extended Events session.
  • Run the following to capture recent failing queries:
  SELECT TOP 50 * FROM sys.dm_exec_query_stats
  CROSS APPLY sys.dm_exec_sql_text(sql_handle)
  WHERE text LIKE '%FunctionName%'

Step 2: Inspect the Function Definition

  • Open the function definition to confirm its expected parameter list.
  • Run the following command, replacing FunctionName with the actual object:
  EXEC sp_helptext 'dbo.FunctionName'
  • Compare the parameter count and data types against how the function is being called in the application or stored procedure.

Step 3: Correct the Function Call or Update the Function

  • If the application code is passing too few or too many arguments, update the calling query to match the function’s signature exactly.
  • If the function itself was altered incorrectly (for example, during a deployment script or migration to SQL Server 2025), use ALTER FUNCTION to restore the correct parameter definition:
  ALTER FUNCTION dbo.FunctionName (@Param1 INT, @Param2 VARCHAR(50))
  RETURNS INT
  AS
  BEGIN
      -- function body
  END
  • Save and redeploy any associated stored procedures or application DLLs that reference this function.

Step 4: Clear Cached Execution Plans

  • After correcting the function or call, clear any stale cached plans that may still reference the old signature.
  • Run the following on the affected database to force recompilation:
  DBCC FREEPROCCACHE
  • Restart the SQL Server service via Services.msc on Windows Server 2025 / Windows 11 if the issue persists after clearing the cache.

Step 5: Validate Application Compatibility

  • Confirm that any client drivers (ODBC, OLE DB, or ADO.NET) connecting to SQL Server 2025 are updated to the latest version, since older drivers may format function calls incorrectly.
  • Check the application’s connection string and ORM mapping (e.g., Entity Framework, Dapper) for auto-generated queries that might be passing incorrect argument counts.

Alternative or Verification Steps

  • Re-run the original failing query or application transaction and confirm Error 4114 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • If the error persists, use SQL Server Profiler or Extended Events to trace the exact call stack and confirm whether a cached execution plan or a third-party application layer is still sending the malformed function call.

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

Troubleshooting Guide: SQL Server Error 4113 – “The function ‘%.*ls’ is not a valid windowing function”

Why This Error Happens

This error occurs when a T-SQL query attempts to use a standard aggregate or scalar function (such as COUNT, AVG, or a custom scalar function) with an OVER() clause that it does not support, or when the OVER() clause contains invalid components (like ORDER BY on a function that only accepts partitioning). SQL Server 2025 strictly validates windowing syntax against a defined list of ranking, aggregate, and analytic functions, and any mismatch—often caused by a typo, a deprecated function name, or copying syntax from an incompatible database platform—triggers this parsing failure. It can also happen if a user-defined function (UDF) is incorrectly assumed to support windowing semantics.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function in the Query

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact function named in the error message (e.g., %.*ls will be replaced with the actual function name like STRING_AGG or a custom UDF).
  • Check the official Microsoft documentation for SQL Server 2025 to confirm whether this function is on the supported list for OVER() clauses (valid categories include Ranking, Aggregate, and Analytic functions).
  • Run SELECT * FROM sys.all_objects WHERE name = 'YourFunctionName' to confirm if it is a scalar UDF, which generally cannot be used with OVER().

Step 2: Correct the OVER() Clause Syntax

  • If using an aggregate function like SUM(), COUNT(), or AVG(), ensure the syntax follows: FunctionName(column) OVER (PARTITION BY column ORDER BY column).
  • Remove the ORDER BY sub-clause if you are using a function that only supports partitioning (rare, but applies to some legacy functions).
  • If using a Ranking function like ROW_NUMBER(), RANK(), or DENSE_RANK(), verify you have included the mandatory ORDER BY clause, as these functions will fail without it.

Step 3: Replace Unsupported Scalar Functions

  • If a custom Scalar UDF is being used with OVER(), rewrite the logic using a Common Table Expression (CTE) combined with ROW_NUMBER() or APPLY operators instead.
  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to check if the query originated from an automated job or linked server to identify the source application generating the invalid syntax.
  • Update any application code (e.g., in ORM tools like Entity Framework or Dapper) that might be auto-generating this invalid windowing syntax.

Step 4: Validate Compatibility Level

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to check the current database compatibility level.
  • If the database is running on an older compatibility level (e.g., 130 or lower) inside the new SQL Server 2025 engine, some newer windowing functions may not parse correctly; update it using ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;.

Alternative or Verification Steps

  • Verification: Re-run the corrected query in a test environment; if the function executes and returns a result set without throwing Error 4113, the syntax fix was successful.
  • Alternative: If a legacy third-party application is generating this error and you cannot modify the source code, create a Stored Procedure wrapper that sanitizes the input and uses a supported windowing function alias before passing data back to the application.

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

Troubleshooting Guide: SQL Server Error 4111 — “CREATE SCHEMA statement should be followed by a name or authorization keyword”

Why This Error Happens

This error occurs when the T-SQL parser encounters a malformed CREATE SCHEMA statement, typically because the schema name is missing, misplaced, or the statement incorrectly mixes schema creation with other DDL/DML operations in a way the parser does not support. It can also happen when reserved keywords are used without proper bracket delimiters, or when the AUTHORIZATION clause is misspelled or improperly positioned. In some cases, leftover or corrupted script fragments from copy-pasted code introduce invisible characters or syntax breaks that confuse the parser.

Step-by-Step Resolution Guide

Step 1: Review the Exact Syntax of the CREATE SCHEMA Statement

  • Confirm the statement follows the correct pattern: CREATE SCHEMA schema_name [AUTHORIZATION owner_name].
  • Check for a missing schema name immediately after the CREATE SCHEMA keywords.
  • Ensure there are no stray semicolons, line breaks, or comments splitting the statement before the name is declared.

Step 2: Validate Keyword Usage and Case Sensitivity

  • Verify AUTHORIZATION is spelled correctly and not abbreviated or replaced with an invalid keyword.
  • If the schema name matches a reserved keyword (e.g., ORDER, USER), wrap it in square brackets, such as CREATE SCHEMA [Order].
  • Remove any non-printable or special characters by retyping the statement directly in SQL Server Management Studio (SSMS) rather than pasting from an external editor.

Step 3: Isolate the Statement From Other Batch Commands

  • Ensure CREATE SCHEMA is the first statement in its batch; it cannot be combined with other statements unless using the supported schema-scoped object creation pattern (CREATE SCHEMA ... CREATE TABLE ... CREATE VIEW ...).
  • Add a GO statement immediately before the CREATE SCHEMA command to separate it from preceding batches.
  • Re-run the isolated statement in a new query window connected to the correct database context.

Step 4: Check for Script Generation or Migration Tool Issues

  • If the script was auto-generated (e.g., from SSMS “Generate Scripts” wizard or a migration tool), inspect the raw .sql file in a plain text editor for truncated lines or encoding issues (UTF-8 BOM conflicts are common on Windows Server 2025).
  • Regenerate the script with “Script Schema Qualify” options enabled to ensure full statement integrity.

Alternative or Verification Steps

  • After correcting the syntax, execute SELECT * FROM sys.schemas WHERE name = 'your_schema_name'; to confirm the schema was created successfully.
  • If the error persists, use the SSMS IntelliSense “Validate Syntax” feature or run the statement through SET PARSEONLY ON; to catch hidden syntax errors without executing the full command.

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

Troubleshooting Guide: SQL Server Error 4112 — “The function ‘%.*ls’ must have an OVER clause with ORDER BY”

Why This Error Happens

This error occurs when a ranking or analytic window function—such as ROW_NUMBER(), RANK(), DENSE_RANK(), or NTILE()—is called without a mandatory ORDER BY clause inside its OVER() clause. Unlike aggregate window functions (e.g., SUM() OVER()), these specific functions require a defined logical order to calculate sequential values correctly, so SQL Server 2025 rejects the query at the parsing stage. This is typically a T-SQL syntax issue introduced by a code migration, an ORM-generated query, or a copy-pasted script rather than a server configuration or OS-level fault.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact statement referenced in the error using SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Check the Messages tab output or the application’s exception log for the full query text, since %.*ls is a placeholder for the function name (e.g., ROW_NUMBER).
  • If running on a stored procedure, use sp_helptext '<ProcedureName>' to pull the full definition for review.

Step 2: Insert a Valid ORDER BY Clause into OVER()

  • Modify the function call to include an ORDER BY inside the parentheses of OVER().
  • Example of broken syntax: SELECT ROW_NUMBER() OVER() AS RowNum FROM Sales.Orders;
  • Corrected syntax: SELECT ROW_NUMBER() OVER (ORDER BY OrderDate DESC) AS RowNum FROM Sales.Orders;
  • Ensure the column referenced in ORDER BY actually exists in the table/view and is not ambiguous in multi-join queries.

Step 3: Check for Dynamic SQL and ORM Auto-Generated Scripts

  • If the query is generated dynamically (via Entity Framework, Dapper, or a reporting tool), inspect the application’s data access layer on the Windows Server 2025 host.
  • Search configuration files or stored logic (usually under C:\inetpub\wwwroot\<AppName>\ or the app’s installation directory) for template strings building OVER() clauses.
  • Patch the query template to always append a default sort column (e.g., a primary key) if no explicit ORDER BY is provided by the end-user filter.

Step 4: Recompile and Redeploy the Object

  • Once corrected, drop and recreate the stored procedure or view using CREATE OR ALTER PROCEDURE.
  • Clear the plan cache for the specific object to ensure SQL Server 2025 doesn’t attempt to reuse a cached (invalid) execution plan: DBCC FREEPROCCACHE (<plan_handle>);
  • Restart the associated application pool in IIS (if applicable) on the Windows Server 2025 instance to clear any cached connection strings or prepared statements.

Alternative or Verification Steps

  • Verification: Re-run the query directly in SSMS against the production or staging database; a successful execution with no Error 4112 confirms the fix. Additionally, monitor the SQL Server Error Log (via EXEC sp_readerrorlog) for 24 hours to ensure the error does not recur from other calling applications.
  • Alternative: If you cannot determine a logical sort order for the business requirement, use ORDER BY (SELECT NULL) as a syntactically valid placeholder, though this is only recommended for SUM()/COUNT() aggregate window functions and will not work for ROW_NUMBER(), which requires a genuine, deterministic order to function as intended.

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

Troubleshooting Guide: SQL Server Error 4110

Why This Error Happens

Error 4110 occurs when a Transact-SQL statement passes a parameter of an incompatible data type to a built-in function or stored procedure that expects a specific type. This commonly happens after application updates, schema changes, or when implicit conversion rules change between SQL Server compatibility levels. In SQL Server 2025, stricter type-checking in certain T-SQL functions (especially those related to JSON, vector operations, and date/time handling) can surface this error even in queries that worked on older compatibility levels.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Function

  • Capture the full error message, including the function name (%s) and argument position (%d) from SQL Server Management Studio (SSMS) or the application log.
  • Use SQL Server Profiler or Extended Events to trace the exact query executing at the time of failure.
  • Check the Windows Event Viewer under Applications and Services Logs > Microsoft > SQL Server for correlated error entries.

Step 2: Verify Data Types and Explicit Casting

  • Open the query in SSMS and inspect the parameter or column feeding the flagged argument.
  • Use SELECT sys.dm_exec_describe_first_result_set() or sp_describe_first_result_set to confirm expected vs. actual data types.
  • Add explicit CAST() or CONVERT() functions around the argument to match the expected type (e.g., CONVERT(nvarchar(max), @value)).

Step 3: Check Database Compatibility Level

  • Run the following to check current compatibility level:
  • SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the database was recently migrated to SQL Server 2025, temporarily test with a prior compatibility level to confirm if stricter type enforcement is the cause:
  • ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160;
  • If the issue resolves at a lower compatibility level, update the application code rather than permanently downgrading compatibility.

Step 4: Update or Patch the Application Layer

  • Review any ORM frameworks (Entity Framework, Dapper, etc.) or client drivers (ODBC, OLE DB) for outdated type mappings.
  • Update the Microsoft OLE DB Driver or ODBC Driver to the latest version certified for SQL Server 2025 and Windows Server 2025/Windows 11.
  • Restart the SQL Server service after driver updates:
  • Restart-Service -Name 'MSSQLSERVER' (via PowerShell, run as Administrator)

Step 5: Validate Function Signatures Against Documentation

  • Cross-reference the function in question (e.g., JSON_VALUE, DATEADD, VECTOR_DISTANCE) against the official SQL Server 2025 Transact-SQL documentation for updated argument type requirements.
  • Adjust stored procedures or application queries to align with the documented signatures.

Alternative or Verification Steps

  • Re-run the original query or application transaction in SSMS after applying the CAST()/CONVERT() fix and confirm no Error 4110 is thrown in the Messages pane.
  • If the error persists, isolate the issue by executing the function independently with hardcoded literal values of the correct type to confirm whether the root cause lies in the data source rather than the function call itself.

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

Troubleshooting Guide: SQL Server Error 4109

Why This Error Happens

Error 4109 occurs because Transact-SQL does not permit nesting a windowed function (such as ROW_NUMBER(), RANK(), or SUM() OVER()) directly inside another windowed function or aggregate call. This is a T-SQL language syntax restriction rather than a server configuration or permissions issue, meaning the query itself must be restructured. It commonly appears when developers attempt to apply an aggregate like AVG() directly over the result of a ROW_NUMBER() OVER() expression in the same SELECT clause level.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Segment

  • Locate the exact line referenced in the error message within SQL Server Management Studio (SSMS).
  • Look for patterns like SUM(ROW_NUMBER() OVER (ORDER BY ColumnName)) or AVG(RANK() OVER (...)) within the same SELECT statement.
  • Check if two OVER() clauses are being combined without an intermediate step.

Step 2: Refactor Using a Common Table Expression (CTE)

  • Move the inner windowed function into a CTE or a derived subquery so it resolves to a static value first.
  • Example fix:
  WITH RankedData AS (
      SELECT *, ROW_NUMBER() OVER (PARTITION BY DeptID ORDER BY Salary) AS RowNum
      FROM Employees
  )
  SELECT DeptID, AVG(RowNum) AS AvgRowNum
  FROM RankedData
  GROUP BY DeptID;
  • Save the script and re-run it against the Windows Server 2025 instance via SSMS.

Step 3: Validate Query Execution Plan

  • Open Include Actual Execution Plan in SSMS to ensure the query parses successfully without error 4109.
  • Confirm the Query Processor does not flag the Compute Scalar operator with syntax warnings.
  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to confirm no residual parsing errors persist.

Step 4: Apply Table Variable or Temp Table Isolation (If CTE is Insufficient)

  • For complex nested logic, insert the windowed function results into a temporary table (#TempResults) first.
  • Run the aggregate function as a separate query against the #TempResults table.
  • Drop the temporary table after execution using DROP TABLE #TempResults; to maintain tempdb hygiene.

Alternative or Verification Steps

  • Run SELECT @@VERSION; to confirm you are on a supported build of SQL Server 2025, then re-execute the refactored query to ensure it returns results without throwing Error 4109.
  • If the CTE approach fails due to complex grouping logic, use the APPLY operator (CROSS APPLY) to join the windowed function results back to the base table before aggregating.

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

Troubleshooting Guide: SQL Server Error 4108 — “Windowed Functions Can Only Appear in the SELECT or ORDER BY Clauses”

Why This Error Happens

This error occurs because SQL Server’s T-SQL grammar strictly restricts the use of windowed functions (such as ROW_NUMBER(), RANK(), SUM() OVER(), or LAG()/LEAD()) to only the SELECT list or the ORDER BY clause of a query. When a developer attempts to reference a windowed function directly inside a WHERE, GROUP BY, HAVING, or JOIN ON clause, the query parser rejects the statement because the logical processing order of SQL evaluates those clauses before the SELECT list is resolved. Essentially, the database engine cannot filter or group by a value that hasn’t technically been calculated yet in the query’s execution pipeline.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Clause

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact line number referenced in the Error 4108 message.
  • Check if the windowed function (e.g., ROW_NUMBER() OVER (PARTITION BY...)) is sitting inside a WHERE or HAVING clause.
  • Look specifically for attempts to filter results immediately after calculating a rank or running total in the same query block.

Step 2: Restructure the Query Using a CTE or Subquery

  • Wrap the original query (including the windowed function in the SELECT list) inside a Common Table Expression (CTE) or a derived table (subquery).
  • Move the WHERE or HAVING logic to the outer query that selects from the CTE/subquery.
  • Example fix syntax:
  WITH OrderedCTE AS (
      SELECT *, ROW_NUMBER() OVER (ORDER BY SalesDate) AS RowNum
      FROM Sales
  )
  SELECT * FROM OrderedCTE WHERE RowNum = 1;

Step 3: Validate Compatibility Level Settings

  • Ensure the database is running on the correct compatibility level for SQL Server 2025 by checking sys.databases.
  • Run the following command to verify the current level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDBName';
  • If necessary, update it using ALTER DATABASE YourDBName SET COMPATIBILITY_LEVEL = 170; to ensure modern windowing function support is fully enabled.

Step 4: Clear Cached Execution Plans

  • If the query logic is already correct but the error persists intermittently on Windows Server 2025, the Plan Cache might be holding a corrupted or outdated execution plan.
  • Execute DBCC FREEPROCCACHE; to clear the cache (note: use with caution on production servers during peak hours as this forces recompilation).
  • Restart the SQL Server service via services.msc if the issue persists after clearing the cache.

Alternative or Verification Steps

  • Verification: Re-run the query after refactoring; if the syntax check passes and returns a result set without a red syntax error flag in SSMS, the fix was successful.
  • Alternative: If restructuring the CTE is not feasible due to complex legacy code, use the APPLY operator (CROSS APPLY) instead of a WHERE clause to filter rows based on windowed function results in a single pass.

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

Troubleshooting Guide: Error 4107 – Remote Table/View Insert Restriction via BCP/BULK INSERT

Why This Error Happens

Error 4107 occurs because SQL Server 2025 does not permit the BULK INSERT statement or the bcp utility to directly target a remote table or a view that references a remote table through a linked server. This is a design restriction rather than a permissions issue, since bulk operations require a direct, local rowset to optimize the data load path. The error typically surfaces when a view used as the target is built on a four-part name (linked server) reference, or when the destination table itself resides on a different server than the one the bulk client is connected to.

Step-by-Step Resolution Guide

Step 1: Verify the Target Connection Point

  • Confirm whether the destination table/view is local to the SQL Server instance you are connecting to.
  • Run SELECT * FROM sys.servers; to check if the target is registered as a Linked Server.
  • Check the view definition using sp_helptext 'YourViewName'; to see if it references a four-part name (e.g., LinkedServer.Database.Schema.Table).

Step 2: Redirect the BCP/BULK INSERT Command

  • Modify your connection string or bcp command to point directly to the server hosting the physical table.
  • Update the -S flag in your bcp command to the actual remote server’s network name instead of the local instance.
  • Example command: bcp DatabaseName.dbo.TableName in "C:\Data\import.dat" -S RemoteServerName -T -c

Step 3: Implement a Staging Table Workaround

  • If direct remote access to the target server is not possible, create a local staging table in tempdb or a user database on the instance where you are running the command.
  • Use BULK INSERT to load the data into this local staging table first.
  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\ to ensure the local database file has enough space for the staging data.
  • Run a standard INSERT INTO RemoteView SELECT * FROM LocalStagingTable; to move the data from the local stage to the remote view (standard T-SQL INSERT supports linked servers, unlike BULK INSERT).

Step 4: Adjust Linked Server Configuration (If using OPENROWSET)

  • If you are using INSERT ... SELECT * FROM OPENROWSET(BULK...) instead of the standalone BULK INSERT command, ensure the Ad Hoc Distributed Queries advanced configuration option is enabled.
  • Execute the following in SQL Server Management Studio (SSMS):
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
  RECONFIGURE;

Alternative or Verification Steps

  • Verification: Re-run the bcp command using the -S parameter pointed directly at the server name holding the physical table; a successful row copy confirms the redirect worked.
  • Alternative: If the staging table approach is too slow for large datasets, configure SQL Server Integration Services (SSIS) or Azure Data Factory to handle the ETL pipeline, as these tools manage remote bulk loading without the same local-rowset restrictions as the native bcp utility.

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

Troubleshooting Guide: SQL Server Error 4106 — “The function ‘%.*ls’ may not have a window frame”

Why This Error Happens

This error occurs when a T-SQL query attempts to apply an OVER() clause with a window frame specification (such as ROWS BETWEEN or RANGE BETWEEN) to a function that does not support framing, such as RANK(), NTILE(), ROW_NUMBER(), or LAG()/LEAD(). SQL Server’s query parser enforces strict rules about which analytic and ranking functions can be combined with a frame clause, since ranking functions operate on the entire partition rather than a sliding window. This is almost always a T-SQL syntax issue introduced during query authoring, migration from another database platform (like Oracle or PostgreSQL), or an ORM-generated query, rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Call

  • Locate the exact query referenced in the error message or SQL Server error log.
  • Search the query for OVER ( clauses combined with ROWS BETWEEN, RANGE BETWEEN, UNBOUNDED PRECEDING, or CURRENT ROW.
  • Cross-reference the function name against SQL Server’s supported window-frame functions: only aggregate functions (SUM, AVG, COUNT, MIN, MAX) and FIRST_VALUE/LAST_VALUE support framing.

Step 2: Remove or Replace the Invalid Frame Clause

  • If the function is a ranking function (RANK, DENSE_RANK, ROW_NUMBER, NTILE) or an offset function (LAG, LEAD), strip out the ROWS BETWEEN/RANGE BETWEEN clause entirely — these functions only accept PARTITION BY and ORDER BY.
  • Example fix: change RANK() OVER (PARTITION BY DeptID ORDER BY Salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) to RANK() OVER (PARTITION BY DeptID ORDER BY Salary).
  • If framing behavior was actually intended, substitute the ranking function with an appropriate aggregate function like SUM() or COUNT() that does support the frame clause.

Step 3: Validate Query Compatibility After Migration

  • If this query was ported from another RDBMS, check vendor-specific documentation since window-frame support differs significantly between platforms.
  • Open the query in SQL Server Management Studio (SSMS) and use “Parse” (Ctrl+F5) before execution to catch syntax issues without running the full query.
  • Update any ORM or application-layer query builder templates (Entity Framework, Hibernate, etc.) that may be auto-generating the invalid frame clause.

Step 4: Re-test Execution Plan Generation

  • Run SET SHOWPLAN_XML ON or use “Display Estimated Execution Plan” in SSMS to confirm SQL Server can now compile the query without error 4106.
  • Confirm no other analytic functions in the same batch share the same flawed pattern, as the error typically triggers on the first invalid occurrence only.

Alternative or Verification Steps

  • Execute the corrected query directly against a test database and confirm it returns results without raising Error 4106, then re-run it against production once validated.
  • If the application cannot be modified immediately, wrap the ranking function result in a subquery/CTE and apply any needed windowed aggregation in an outer SELECT using a properly supported aggregate function instead.

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

Why This Error Happens

Error 4105 in SQL Server 2025 typically surfaces when a client application (such as Power BI, Excel, or a custom connector) attempts to retrieve data through a scalar or table-valued User-Defined Function (UDF) that is not properly schema-bound. This usually occurs because the UDF references an object that was altered or dropped after the function was created, or because the new Intelligent Query Processing engine in SQL Server 2025 rejects non-deterministic logic inside inline functions. In most cases, this is a metadata corruption or permission-scoping issue rather than a network or connectivity fault.

Step-by-Step Resolution Guide

Step 1: Validate the UDF Schema Binding

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run sp_helptext 'YourFunctionName' to inspect the function definition for WITH SCHEMABINDING.
  • Confirm all referenced tables/columns still exist using sys.sql_expression_dependencies.

Step 2: Refresh and Recompile the Function

  • Execute sp_refreshsqlmodule 'YourFunctionName'; to force SQL Server to update cached metadata.
  • If the function references other objects, drop and recreate it explicitly rather than using ALTER FUNCTION.
  • Clear the plan cache for the database using DBCC FREEPROCCACHE; to eliminate stale execution plans tied to the broken UDF.

Step 3: Check Permissions on the Function and Underlying Objects

  • Run SELECT * FROM fn_my_permissions('YourFunctionName', 'OBJECT'); to confirm the calling user has EXECUTE rights.
  • Grant explicit permissions if needed: GRANT EXECUTE ON OBJECT::YourFunctionName TO [DomainUser];
  • Verify the login mapped in the client tool (Power BI, Excel, ODBC DSN) matches a role with proper data access.

Step 4: Update Client Drivers and Server Configuration

  • On Windows Server 2025/Windows 11, update the Microsoft OLE DB Driver for SQL Server to the latest version (19.x or higher) via the Microsoft Download Center.
  • In the ODBC Data Source Administrator (odbcad32.exe), recreate the DSN pointing to the instance to clear corrupted connection metadata.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to apply changes.

Alternative or Verification Steps

  • Re-run the original “Get Data” query from your client application (Power BI/Excel) and confirm Error 4105 no longer appears in the query log.
  • If the error persists, replace the scalar UDF with an inline table-valued function (iTVF) alternative, as SQL Server 2025’s query optimizer handles iTVFs more reliably under Intelligent Query Processing.

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

Why This Error Happens

This error occurs when SQL Server’s query parser cannot resolve a column reference back to a valid table, view, or alias within the scope of the query. It typically happens due to a misspelled or dropped column name, a table alias that is referenced before it is declared (or not declared at all), or a column reference pointing to a table that isn’t included in the FROM/JOIN clause. In SQL Server 2025, this is also commonly triggered by scoping issues in subqueries, CTEs, or derived tables where the outer query attempts to reference an inner-scope column directly.

Step-by-Step Resolution Guide

Step 1: Review the Exact Query and Identify the Offending Identifier

  • Open the query in SSMS (SQL Server Management Studio) or Azure Data Studio and locate the exact multi-part identifier named in the error message (e.g., dbo.Orders.CustomerID).
  • Confirm whether the referenced table/alias actually exists in the FROM or JOIN clause of that specific query scope.
  • Check for typos in table aliases, especially when multiple tables share similar column names.

Step 2: Validate Table and Column Schema

  • Run sp_help 'dbo.TableName' or query INFORMATION_SCHEMA.COLUMNS to confirm the column still exists and hasn’t been renamed or dropped in a recent schema migration.
  • If using Windows Server 2025 with SQL Server 2025’s updated Intelligent Query Processing features, verify that no automatic view or synonym refactoring altered underlying object names.
  • Update any outdated column references in stored procedures or views accordingly.

Step 3: Correct Scope Issues in Subqueries, CTEs, or Joins

  • Ensure that any alias defined inside a subquery or CTE is not referenced outside its intended scope.
  • Explicitly qualify every column with its correct table alias (e.g., o.CustomerID instead of just CustomerID) to eliminate ambiguity.
  • Rebuild complex joins incrementally, testing each join addition to isolate exactly where the identifier breaks.

Step 4: Refresh Dependent Objects and Recompile

  • If the error surfaces only after a schema change, run sp_refreshview 'dbo.ViewName' for views or sp_recompile 'dbo.ProcedureName' for stored procedures to force SQL Server to rebuild internal metadata.
  • Clear the plan cache for the affected database using DBCC FREEPROCCACHE if stale execution plans are suspected (use cautiously in production).

Alternative or Verification Steps

  • Execute the corrected query in isolation (SELECT only the flagged column with its full qualification) to confirm SQL Server resolves it without error.
  • If the issue persists only in a stored procedure but not in ad-hoc queries, drop and recreate the procedure entirely, as SQL Server 2025 occasionally caches stale binding metadata during in-place upgrades from previous versions.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 4103

Why This Error Happens

Error 4103 occurs when a T-SQL statement attempts to create a view using a temporary object naming convention (prefixed with # or ##), which SQL Server explicitly disallows because views are schema-bound metadata objects and cannot exist as session-scoped or global temporary structures. This typically happens due to a coding mistake where a developer confuses temporary tables with views, or due to a legacy script that was never updated for stricter parser validation in SQL Server 2025. It can also surface when ORM frameworks or migration tools auto-generate DDL scripts using incorrect naming prefixes.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact CREATE VIEW statement referenced in the error message (the %.*ls placeholder will show the object name in the Messages tab).
  • Check for a # or ## prefix in the view name, e.g., CREATE VIEW #MyTempView AS....
  • Search your deployment scripts, stored procedures, or application ORM mappings (Entity Framework, Hibernate, etc.) for similarly malformed CREATE VIEW statements.

Step 2: Correct the Object Definition

  • Rename the object and remove the # or ## prefix if a persistent view was intended:
  CREATE VIEW dbo.MyView AS SELECT * FROM dbo.MyTable;
  • If temporary result-set logic was actually needed, replace the view with a temporary table instead:
  SELECT * INTO #MyTempTable FROM dbo.MyTable;
  • If the intent was a reusable inline query without persistence, use a Common Table Expression (CTE) instead:
  WITH MyCTE AS (SELECT * FROM dbo.MyTable) SELECT * FROM MyCTE;

Step 3: Update Application or Migration Scripts

  • If using an ORM or migration framework, check the code generation templates for incorrect object prefixing logic.
  • On Windows Server 2025, verify any scheduled SQL Agent Jobs (via SQL Server Agent in SSMS) that execute deployment scripts aren’t passing dynamic SQL with # prefixes into CREATE VIEW statements.
  • Redeploy the corrected script using sqlcmd or through your CI/CD pipeline:
  sqlcmd -S localhost -d YourDatabase -i "C:\Scripts\FixedView.sql"

Step 4: Restart Dependent Services (If Applicable)

  • If the view was referenced by a cached execution plan or dependent stored procedure, clear the procedure cache:
  DBCC FREEPROCCACHE;
  • Restart the SQL Server service via services.msc or PowerShell if stale metadata persists:
  Restart-Service -Name 'MSSQLSERVER'

Alternative or Verification Steps

  • Run the corrected script again and confirm it executes without Error 4103, then query sys.views to verify the object was created as a permanent schema-bound view: SELECT * FROM sys.views WHERE name = 'MyView';
  • If the error persists in automated deployment pipelines, add a pre-deployment validation step (regex check) to scan .sql files for CREATE VIEW\s+# patterns before execution.

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

Troubleshooting Guide: SQL Server Error 4101

Why This Error Happens

Error 4101 occurs because SQL Server’s query processor does not allow aggregate functions (such as SUM, COUNT, or AVG) placed on the right-hand side of a CROSS APPLY or OUTER APPLY to reference columns from the left-hand table expression. This is a T-SQL language restriction rooted in how the logical binding order of APPLY operators works—the aggregate’s scope is resolved independently of the left side’s correlated columns during query compilation. It typically surfaces when developers attempt to write inline aggregations inside a derived table or table-valued function call that correlates back to the outer query without proper subquery wrapping.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Pattern

  • Open the query that triggered Error 4101 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate the APPLY clause (CROSS APPLY or OUTER APPLY) and check the right-side expression for aggregate functions like SUM(), COUNT(), MAX(), or AVG().
  • Confirm the aggregate is directly referencing a column from the left table alias (e.g., SUM(a.SalesAmount) where a is the left-side table).

Step 2: Restructure the Query Using a Correlated Subquery

  • Move the aggregate logic into a properly scoped derived table or subquery that explicitly joins or filters using the left-side column inside its own WHERE/JOIN clause, rather than referencing it directly in the SELECT list.
  • Example fix pattern:
  SELECT a.ID, x.TotalAmount
  FROM TableA a
  CROSS APPLY (
      SELECT SUM(b.Amount) AS TotalAmount
      FROM TableB b
      WHERE b.ParentID = a.ID
  ) x;
  • Ensure the correlation (b.ParentID = a.ID) happens inside the APPLY’s subquery body, not in the aggregate function call itself.

Step 3: Validate Compatibility Level and Query Hints

  • Check the database compatibility level under Database Properties > Options > Compatibility Level in SSMS, since SQL Server 2025 introduces stricter binding validation under compatibility level 170.
  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDBName'; to confirm the current setting.
  • If legacy code relied on older permissive parsing, consider refactoring rather than downgrading compatibility level, as this restriction is standard ANSI SQL behavior.

Step 4: Recompile and Test the Query

  • Clear the procedure cache for the affected object using DBCC FREEPROCCACHE (in a test environment only) to force a clean recompilation.
  • Re-execute the corrected query and confirm Error 4101 no longer appears in the Messages pane.

Alternative or Verification Steps

  • Verify the fix by running the query with SET SHOWPLAN_XML ON to confirm the execution plan compiles without binding errors, and check that results return expected row-level aggregates.
  • As an alternative, replace the APPLY construct entirely with a standard LEFT JOIN against a pre-aggregated derived table (GROUP BY subquery) if correlation logic allows, which avoids APPLY-specific binding restrictions altogether.

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

Troubleshooting Guide: Error 4102 – Invalid Use of READPAST Lock Hint

Why This Error Happens

Error 4102 occurs when the READPAST lock hint is applied to a table or view reference in a location where SQL Server’s query parser does not permit it, such as within a subquery, a derived table without an explicit alias, or a table referenced implicitly rather than through a direct FROM clause. This is a T-SQL syntax restriction rather than a permissions or connectivity issue, meaning the query engine is rejecting the statement before execution ever begins. It commonly surfaces after application code migrations, ORM-generated queries, or manual query tuning attempts where READPAST was added to improve concurrency on MERGE, UPDATE, or DELETE statements without following the strict placement rules SQL Server 2025 enforces.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing statement from the application log, SQL Server error log, or Extended Events session.
  • Open the query in SQL Server Management Studio (SSMS) connected to your Windows Server 2025 or Windows 11 instance.
  • Look specifically for READPAST used on a target table in an UPDATE/DELETE without an explicit FROM clause, or inside a JOIN condition rather than directly after the table reference.

Step 2: Correct the Lock Hint Placement

  • Rewrite UPDATE or DELETE statements to include an explicit FROM clause, e.g.:
  UPDATE t
  SET t.Status = 'Processed'
  FROM dbo.Orders AS t WITH (READPAST)
  WHERE t.Status = 'Pending';
  • Ensure READPAST is attached directly to the table alias using the WITH (READPAST) syntax, not placed in a WHERE or JOIN predicate.
  • For MERGE statements, confirm READPAST is only applied to the source or target table reference, never on the MERGE keyword itself.

Step 3: Validate Against SQL Server 2025 Syntax Rules

  • Run the corrected query in a test environment first using SSMS or Azure Data Studio.
  • Cross-check against Microsoft’s official T-SQL table hint documentation for SQL Server 2025, since hint enforcement has tightened compared to SQL Server 2019/2022.
  • If the query originates from an ORM (Entity Framework, Hibernate, etc.), update the raw SQL template or stored procedure rather than relying on auto-generated hints.

Step 4: Update Stored Procedures and Application Code

  • Search all stored procedures, views, and functions in the affected database using:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%READPAST%';
  • Patch each result individually, redeploy via SQL Server Management Studio or your CI/CD pipeline, and recompile execution plans using EXEC sp_recompile 'SchemaName.ObjectName';.

Alternative or Verification Steps

  • Re-run the previously failing transaction or scheduled job and confirm it completes without raising Error 4102 in the SQL Server error log (Log\ERRORLOG under the instance’s data directory).
  • If rewriting the query isn’t immediately feasible, temporarily replace READPAST with NOLOCK or remove the hint entirely as a stopgap, then schedule a proper fix since this alters isolation behavior and may cause dirty reads.