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

Troubleshooting Guide: SQL Server Error 5058 – “Option ‘%.ls’ cannot be set in database ‘%.ls'”

Why This Error Happens

This error typically occurs when attempting to modify a database option while the database is in a state that does not permit changes, such as being in use by other users, in SINGLE_USER mode with an active conflicting session, or involved in a database mirroring/Always On Availability Group configuration that restricts certain SET operations. It can also happen if the option being set is incompatible with the current database compatibility level or if the database is a system database (like master or tempdb) that has restrictions on certain ALTER DATABASE options. Additionally, insufficient permissions or the database being in RESTORING, OFFLINE, or EMERGENCY state can trigger this error.

Step-by-Step Resolution Guide

Step 1: Verify Database State and Active Connections

  • Open SQL Server Management Studio (SSMS) or a query window and run SELECT state_desc, user_access_desc FROM sys.databases WHERE name = 'YourDatabaseName'; to check the current state.
  • Ensure the database is ONLINE and not RESTORING, OFFLINE, or EMERGENCY.
  • If the database shows active connections blocking the change, run SELECT * FROM sys.dm_exec_sessions WHERE database_id = DB_ID('YourDatabaseName'); to identify open sessions.

Step 2: Set Database to Single-User Mode (If Required)

  • Run the following command to force single-user access before applying the option change:
  • ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • This disconnects all other sessions and allows exclusive access for configuration changes.
  • Proceed with your original ALTER DATABASE command (e.g., setting AUTO_CLOSE, READ_COMMITTED_SNAPSHOT, etc.).

Step 3: Check for Availability Group or Mirroring Restrictions

  • If the database is part of an Always On Availability Group, verify that you are connected to the Primary Replica.
  • Run SELECT role_desc FROM sys.dm_hadr_availability_replica_states WHERE is_local = 1; on the node to confirm its role.
  • Some options cannot be changed while mirroring or AG synchronization is active; you may need to temporarily remove the database from the AG/mirroring session before applying the option.

Step 4: Revert to Multi-User Mode and Confirm Compatibility Level

  • Once the option has been successfully applied, return the database to multi-user access:
  • ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Confirm the database compatibility level supports the option using SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; and update if necessary with ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; (adjust value for SQL Server 2025).

Alternative or Verification Steps

  • To verify the fix, re-run the original ALTER DATABASE statement that previously failed; it should now execute without raising Error 5058.
  • If the issue persists, check the SQL Server Error Log (via EXEC sp_readerrorlog; or Event Viewer under Windows Logs > Application) for additional context on blocking sessions or system-level restrictions preventing the change.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 5056

Why This Error Happens

Error 5056 typically occurs when SQL Server cannot add a file, filegroup, or database object due to insufficient disk permissions, a locked resource, or a conflict with existing file paths. This often happens when the SQL Server service account lacks write access to the target directory on Windows Server 2025 or Windows 11, or when the specified file path references a location that is already in use, restricted, or does not exist. Corrupted metadata in system catalogs can also trigger this error when SQL Server attempts to validate the structure before adding new data.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc and confirm the account running “SQL Server (MSSQLSERVER)”.
  • Navigate to the target folder (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA) and check Security tab permissions.
  • Grant Full Control to the SQL Server service account via right-click → Properties → Security → Edit.

Step 2: Check for File Path Conflicts

  • Run SELECT name, physical_name FROM sys.master_files; in SQL Server Management Studio (SSMS) to confirm no duplicate paths exist.
  • Ensure the target drive has sufficient free space (minimum 10% recommended).
  • Avoid using mapped network drives; use local or UNC paths explicitly supported by SQL Server 2025.

Step 3: Restart SQL Server Services and Clear Locks

  • Open PowerShell as Administrator and run:
  • Restart-Service -Name 'MSSQLSERVER' -Force
  • Check for orphaned locks using sp_who2 and terminate blocking sessions with KILL <session_id>.

Step 4: Rebuild or Repair Database Metadata

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to detect corruption.
  • If corruption is found, use DBCC CHECKDB('YourDatabaseName', REPAIR_REBUILD); in single-user mode.

Alternative or Verification Steps

  • After applying fixes, attempt the original “Add” operation again and confirm no Error 5056 appears in the SQL Server Error Log (SQL Server Logs folder) or Windows Event Viewer.
  • If the issue persists, create a new filegroup/file in a fresh directory with default permissions to isolate whether the original path is the root cause.

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

Troubleshooting Guide: SQL Server Error 5054 — Worktable IAM Chain Cleanup Failure

Why This Error Happens

This error occurs when SQL Server attempts to shrink or remove a tempdb data file while active worktables, work files, or internal sort/hash structures are still allocated in tempdb, preventing the engine from cleaning up the Index Allocation Map (IAM) chains. It is typically triggered by concurrent query activity (such as sorts, hash joins, cursors, or temporary table operations) that continues to use tempdb while the shrink or file removal operation is running. Because tempdb is recreated on every SQL Server restart and heavily used by concurrent sessions, this contention is common in high-throughput OLTP or reporting environments.

Step-by-Step Resolution Guide

Step 1: Identify Active Sessions Using tempdb

  • Run the following query to check for active tasks consuming tempdb space:
SELECT session_id, request_id, SUM(internal_objects_alloc_page_count) AS internal_pages,
       SUM(user_objects_alloc_page_count) AS user_pages
FROM sys.dm_db_task_space_usage
GROUP BY session_id, request_id
ORDER BY internal_pages DESC;
  • Look for sessions with high internal_objects_alloc_page_count, indicating heavy worktable/work file usage.
  • Note the session_id values for further investigation with sp_who2 or sys.dm_exec_requests.

Step 2: Pause or Reschedule the Shrink/Remove Operation

  • Avoid running DBCC SHRINKFILE or ALTER DATABASE tempdb REMOVE FILE during peak hours.
  • Schedule the operation during a maintenance window when query activity is minimal.
  • If using SQL Server Agent, create a job step that checks sys.dm_db_task_space_usage for near-zero internal_pages before executing the shrink command.

Step 3: Retry the Shrink Operation with Isolation

  • Temporarily restrict new connections to reduce tempdb contention:
ALTER DATABASE tempdb SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE;
  • Re-run the shrink or file removal command:
DBCC SHRINKFILE (tempdev, 500);
  • Revert access once complete:
ALTER DATABASE tempdb SET MULTI_USER;

Step 4: Restart the SQL Server Service (If Contention Persists)

  • On Windows Server 2025 / Windows 11, open Services.msc (or use PowerShell: Restart-Service MSSQLSERVER).
  • Restarting SQL Server recreates tempdb from scratch, clearing all IAM chains and worktable allocations.
  • After restart, immediately attempt the shrink or file removal operation before other processes begin consuming tempdb again.

Step 5: Adjust tempdb File Configuration (Long-Term Fix)

  • Instead of shrinking tempdb repeatedly, evaluate whether the file growth is due to legitimate workload needs (e.g., large sorts, version store usage, or temp table proliferation).
  • Use SQL Server Management Studio (SSMS) to navigate to Database Properties > Files for tempdb and set appropriate initial size and autogrowth values to reduce the need for frequent shrink operations.

Alternative or Verification Steps

  • Verify the fix by re-running the DBCC SHRINKFILE or file removal command and confirming it completes without Error 5054; also check sys.dm_db_file_space_usage to confirm space was reclaimed.
  • If the issue persists even during low-activity periods, check for orphaned or long-running transactions using DBCC OPENTRAN(tempdb) and consider failing over the instance (if in an Always On Availability Group) to force a clean tempdb rebuild.

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

Troubleshooting Guide: SQL Server Error 5055 – “Cannot Add File”

Why This Error Happens

Error 5055 typically occurs when SQL Server 2025 cannot create or extend a database file because of insufficient NTFS permissions on the target directory, a filegroup that has reached its maximum configured size, or disk-level constraints such as low free space or a read-only volume. It can also surface when the path specified for the new file does not exist or is inaccessible to the SQL Server service account. In clustered or Availability Group configurations, this error may indicate that the path is not valid across all cluster nodes.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc and identify the account running the SQL Server (MSSQLSERVER) service.
  • Navigate to the target folder (e.g., D:\SQLData\) in File Explorer, right-click → Properties → Security tab.
  • Ensure the SQL Server service account has Full Control on the directory.
  • If missing, click Edit → Add, enter the service account name, and grant Full Control, then click Apply.

Step 2: Check Disk Space and File Path Validity

  • Open Disk Management (diskmgmt.msc) or run Get-PSDrive in PowerShell to confirm the target drive has sufficient free space.
  • Confirm the exact path exists by running:
  Test-Path "D:\SQLData\YourDB_Data.ndf"
  • If the path does not exist, create the folder structure manually before retrying the ALTER DATABASE ... ADD FILE command.
  • For clustered instances, verify the path exists identically on all nodes in Failover Cluster Manager.

Step 3: Review Filegroup and Autogrowth Settings

  • In SQL Server Management Studio (SSMS), right-click the database → Properties → Files.
  • Check if Autogrowth/Maxsize is capped and not allowing the file to expand.
  • Run the following T-SQL to inspect current file configuration:
  SELECT name, size, max_size, growth 
  FROM sys.database_files;
  • Adjust MAXSIZE to UNLIMITED or increase growth increments if needed:
  ALTER DATABASE YourDB 
  MODIFY FILE (NAME = YourDB_Data, MAXSIZE = UNLIMITED);

Step 4: Restart SQL Server Service and Re-Attempt

  • Restart the SQL Server (MSSQLSERVER) service via services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Re-run the original ALTER DATABASE or CREATE DATABASE command that triggered Error 5055.

Alternative or Verification Steps

  • Confirm success by querying sys.master_files to validate the new file appears with the correct size and path.
  • If the issue persists, try adding the file to an alternate local drive with known-good permissions to isolate whether the problem is path-specific or a broader SQL Server configuration issue.

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

Troubleshooting Guide: SQL Server Error 5052

“%ls is not permitted while a database is in the %ls state.”

Why This Error Happens

This error occurs when SQL Server rejects an operation because the target database is currently in a state (such as RESTORING, OFFLINE, EMERGENCY, or SINGLE_USER) that does not permit the requested action. This typically happens when a previous restore, backup, or maintenance operation did not complete successfully, leaving the database in a transitional or restricted state. It can also occur if another session is actively holding the database in a non-standard state while a conflicting operation is attempted simultaneously.

Step-by-Step Resolution Guide

Step 1: Identify the Current Database State

  • Open SQL Server Management Studio (SSMS) or connect via sqlcmd on Windows Server 2025.
  • Run the following query to check the current state:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the state is RESTORING, OFFLINE, EMERGENCY, RECOVERY_PENDING, or SUSPECT.

Step 2: Resolve Incomplete Restore or Recovery Operations

  • If the database is stuck in RESTORING, determine if a restore sequence was left incomplete (missing WITH RECOVERY command).
  • Complete the recovery process manually:
  RESTORE DATABASE YourDatabaseName WITH RECOVERY;
  • If the database is SUSPECT, attempt to bring it into EMERGENCY mode for inspection:
  ALTER DATABASE YourDatabaseName SET EMERGENCY;

Step 3: Check Active Sessions and Locks

  • Query sys.dm_exec_sessions and sys.dm_tran_locks to identify any blocking sessions holding the database in a restricted state.
  • Terminate conflicting sessions if safe to do so:
  KILL <session_id>;
  • Ensure no automated jobs (SQL Server Agent) are concurrently triggering backup/restore tasks on the same database.

Step 4: Set the Database to a Usable State

  • Once blocking issues are cleared, transition the database back to ONLINE:
  ALTER DATABASE YourDatabaseName SET ONLINE;
  • If corruption is suspected, run a consistency check:
  DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 5: Restart SQL Server Service (If Needed)

  • On Windows Server 2025/Windows 11, open Services.msc.
  • Locate SQL Server (MSSQLSERVER) or the named instance service.
  • Right-click and select Restart to clear any cached state locks preventing the transition.

Alternative or Verification Steps

  • Re-run the original operation (backup, restore, or query) that triggered Error 5052 and confirm it completes without the state-related rejection message.
  • If the issue persists, detach and re-attach the database using sp_detach_db and CREATE DATABASE ... FOR ATTACH to force SQL Server to re-evaluate the database state from a clean metadata read.

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

Troubleshooting Guide: Error 5051 – “Cannot have a filegroup with the name ‘DEFAULT'”

Why This Error Happens

This error occurs because “DEFAULT” is a reserved keyword in SQL Server’s T-SQL engine and cannot be used as a literal identifier for a filegroup name. It typically happens when a migration script, automated deployment tool, or legacy database creation script attempts to explicitly name a filegroup “DEFAULT” instead of using the ALTER DATABASE ... MODIFY FILEGROUP [name] DEFAULT syntax to mark an existing filegroup as the default. This is frequently seen during database restores or schema migrations from older systems where naming conventions were not validated against SQL Server 2025 reserved keywords.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Command

  • Locate the exact CREATE DATABASE, ALTER DATABASE, or CREATE FILEGROUP statement triggering the error.
  • Check deployment logs, SSMS query history, or CI/CD pipeline logs (e.g., Azure DevOps, Jenkins) for the failing T-SQL batch.
  • Search specifically for lines containing ADD FILEGROUP DEFAULT or FILEGROUP [DEFAULT].

Step 2: Rename the Filegroup to a Valid Identifier

  • Replace the reserved word “DEFAULT” with a descriptive, non-reserved name such as PRIMARYFG, FG_DATA, or UserDataFG.
  • Example corrected syntax:
  ALTER DATABASE [YourDB] ADD FILEGROUP [FG_DATA];
  • If you intended to set this filegroup as the database’s default, use the correct dedicated syntax instead of naming it “DEFAULT”:
  ALTER DATABASE [YourDB] MODIFY FILEGROUP [FG_DATA] DEFAULT;

Step 3: Validate Script Against Reserved Keywords

  • Open SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and run the corrected script in a non-production environment first.
  • Cross-reference your naming conventions against Microsoft’s official Reserved Keywords documentation (sys.dm_server_reserved_physical_memory is unrelated; check Books Online > Reserved Keywords (Transact-SQL)).
  • Update any database provisioning templates (ARM templates, Bicep, Terraform azurerm_mssql scripts, or DACPAC files) to prevent recurrence in future deployments.

Step 4: Re-Run the Deployment or Migration

  • Execute the corrected script via SQLCMD or SSMS:
  sqlcmd -S localhost -i "C:\Scripts\CreateFilegroups.sql"
  • Monitor the Windows Event Viewer (Application Log) and SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for confirmation of success.

Alternative or Verification Steps

  • Verify the fix by querying sys.filegroups to confirm the new filegroup name exists and does not conflict with reserved words:
  SELECT name, is_default FROM sys.filegroups;
  • If the error persists in a third-party migration tool (e.g., SSMA, DMS), check the tool’s mapping configuration file for hardcoded “DEFAULT” filegroup references and override them manually before re-running the import.

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

Troubleshooting Guide: SQL Server Error 5050 — Cannot Change Properties of Empty Filegroup

Why This Error Happens

This error occurs because SQL Server requires every filegroup to contain at least one data file before its properties (such as setting it to READ_ONLY, DEFAULT, or adjusting autogrow settings) can be modified. The filegroup was likely created as a logical container via ALTER DATABASE ... ADD FILEGROUP, but no corresponding data file (.ndf or .mdf) was ever added to it using ADD FILE. SQL Server treats an empty filegroup as an incomplete object and blocks administrative operations on it until it is populated.

Step-by-Step Resolution Guide

Step 1: Identify the Empty Filegroup

  • Connect to the instance using SQL Server Management Studio (SSMS) 21 or sqlcmd on Windows Server 2025 / Windows 11.
  • Run the following query to list filegroups and check file counts:
  SELECT fg.name AS FilegroupName, COUNT(f.file_id) AS FileCount
  FROM sys.filegroups fg
  LEFT JOIN sys.database_files f ON fg.data_space_id = f.data_space_id
  GROUP BY fg.name;
  • Confirm the filegroup in the error message shows a FileCount of 0.

Step 2: Add a Data File to the Filegroup

  • Use ALTER DATABASE to add at least one file to the empty filegroup:
  ALTER DATABASE [YourDatabaseName]
  ADD FILE
  (
      NAME = N'YourFileLogicalName',
      FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\YourFile.ndf',
      SIZE = 64MB,
      FILEGROWTH = 64MB
  )
  TO FILEGROUP [YourFilegroupName];
  • Verify the target path exists and that the SQL Server service account has write permissions on that directory.

Step 3: Retry the Property Change

  • Re-run the original command that triggered Error 5050 (e.g., setting the filegroup to READ_ONLY or DEFAULT):
  ALTER DATABASE [YourDatabaseName]
  MODIFY FILEGROUP [YourFilegroupName] READONLY;
  • Check the SQL Server Error Log (via SSMS Object Explorer > Management > SQL Server Logs) to confirm no further errors were raised.

Step 4: Clean Up Unused Empty Filegroups (Optional)

  • If the filegroup was created by mistake and is not needed, remove it instead of adding a file:
  ALTER DATABASE [YourDatabaseName]
  REMOVE FILEGROUP [YourFilegroupName];
  • This avoids leaving orphaned, unusable filegroups in the database schema.

Alternative or Verification Steps

  • Verify the fix by re-running the filegroup/file count query from Step 1 — the filegroup should now show FileCount >= 1 and the property change command should execute without Error 5050.
  • If the issue persists, check for an open transaction or active session blocking schema changes using sp_who2 or sys.dm_tran_locks, then retry after resolving the blocking session.

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

Why This Error Happens

Error 5048 typically occurs when SQL Server 2025 attempts to add a data file to a FILESTREAM-enabled filegroup, but the target filegroup either lacks the required FILESTREAM attribute or the underlying file path already contains conflicting data. This is commonly triggered by a mismatch between the file type being added (regular vs. FILESTREAM) and the filegroup’s configuration, or by insufficient NTFS permissions on the FILESTREAM data container folder. In Windows Server 2025 environments, this can also surface due to the FILESTREAM feature not being enabled at the SQL Server instance level, even though the filegroup was created with FILESTREAM syntax.

Step-by-Step Resolution Guide

Step 1: Verify FILESTREAM is Enabled at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services → right-click your instance → Properties → FILESTREAM tab.
  • Ensure “Enable FILESTREAM for Transact-SQL access” is checked, and if remote clients need access, also check “Enable FILESTREAM for file I/O streaming access.”
  • Restart the SQL Server service after applying changes.

Step 2: Confirm Filegroup Type Matches the File Being Added

  • Run the following query to inspect filegroup properties:
  SELECT name, type_desc, is_default FROM sys.filegroups;
  • Ensure you are adding a FILESTREAM_DATA file type only to filegroups where type_desc = 'FILESTREAM_DATA_FILEGROUP'.
  • If mismatched, create a new filegroup correctly using:
  ALTER DATABASE YourDB ADD FILEGROUP FS_FileGroup CONTAINS FILESTREAM;

Step 3: Check NTFS Permissions on the Data Container Path

  • Navigate to the intended FILESTREAM directory (e.g., C:\SQLData\FileStreamContainer).
  • Right-click → Properties → Security tab.
  • Confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • Ensure the folder is empty before SQL Server attempts to initialize it as a new container; delete any residual files if a previous attempt failed.

Step 4: Retry Adding the File Using Correct Syntax

  • Use the full ALTER DATABASE statement, matching path and filegroup name exactly:
  ALTER DATABASE YourDB 
  ADD FILE (NAME = FS_Data, FILENAME = 'C:\SQLData\FileStreamContainer') 
  TO FILEGROUP FS_FileGroup;
  • Confirm no trailing backslash or invalid characters exist in the FILENAME path, as Windows Server 2025 FILESTREAM paths are strict about folder naming.

Alternative or Verification Steps

  • Verify the fix by querying sys.database_files to confirm the new file appears with type_desc = 'FILESTREAM' and state_desc = 'ONLINE'.
  • If the error persists, drop and recreate the filegroup from scratch in a test database first, ensuring the container directory does not pre-exist (SQL Server must create it fresh).

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

Troubleshooting Guide: Error 5047 – Cannot Change READONLY Property of PRIMARY Filegroup

Why This Error Happens

This error occurs because SQL Server 2025 does not permit the PRIMARY filegroup to be marked as READONLY while it still contains critical system objects or while the database is involved in certain operations that require write access to PRIMARY. It can also happen if the database is part of an Availability Group or is actively being accessed by other sessions, preventing the exclusive lock needed to change the filegroup state. Additionally, insufficient permissions (lack of ALTER rights on the database) can trigger this same error code.

Step-by-Step Resolution Guide

Step 1: Verify Database and Session State

  • Check for active connections using SELECT * FROM sys.dm_exec_sessions WHERE database_id = DB_ID('YourDatabaseName');
  • Ensure no other transactions are holding locks on PRIMARY by querying sys.dm_tran_locks.
  • Switch the database to single-user mode temporarily using ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Step 2: Confirm Filegroup Contents and Permissions

  • Run sys.database_files to confirm whether system tables or indexes are still bound to PRIMARY.
  • Verify your login has db_owner or sufficient ALTER ANY DATABASE permissions using SELECT * FROM fn_my_permissions(NULL, 'DATABASE');
  • If permissions are missing, grant them via SQL Server Management Studio (SSMS) under Security > Logins > Properties > User Mapping.

Step 3: Apply the READONLY Change Correctly

  • Execute the correct syntax: ALTER DATABASE YourDatabaseName MODIFY FILEGROUP [PRIMARY] READONLY;
  • If the database is part of an Availability Group, remove it from the AG temporarily via SSMS or ALTER AVAILABILITY GROUP before retrying.
  • Restart the SQL Server service via Services.msc on Windows Server 2025 if the lock persists after closing all sessions.

Step 4: Check for Replication or Mirroring Conflicts

  • Query sys.database_mirroring and sys.repl_ publications to confirm the database isn’t engaged in replication, since these configurations block filegroup READONLY changes.
  • Temporarily disable replication using sp_removedbreplication 'YourDatabaseName'; if confirmed as the blocker.

Alternative or Verification Steps

  • After applying changes, verify success by running SELECT name, is_read_only FROM sys.filegroups WHERE name = 'PRIMARY'; — the value should return 1.
  • If the error persists, restore the database to a new instance on Windows 11 or a test server, apply the READONLY change there, and then reattach it to validate the filegroup configuration before reapplying to production.

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

Why This Error Happens

Error 5046 in SQL Server 2025 is typically an informational or configuration-state message indicating that a specific server or database property has been successfully modified, but it surfaces as an error when the property change conflicts with an existing session state, a locked configuration file, or insufficient permissions to persist the setting. This often occurs when multiple administrative sessions attempt to modify the same server property simultaneously, or when the SQL Server service account lacks write access to the configuration store on Windows Server 2025 / Windows 11. Corrupted metadata in the msdb or master database can also cause this message to appear repeatedly during property-set operations.

Step-by-Step Resolution Guide

Step 1: Verify the Property Change Context

  • Open SQL Server Management Studio (SSMS) and check the SQL Server Logs (Management > SQL Server Logs) for the full text surrounding Event ID 5046.
  • Identify which property (%ls) triggered the message — common ones include MaxServerMemory, RemoteAccess, or ClrEnabled.
  • Run EXEC sp_configure 'show advanced options', 1; RECONFIGURE; to confirm current configuration values.

Step 2: Check Permissions on Configuration Files

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and verify the SQL Server service account has Read/Write permissions.
  • Confirm the service account also has access to C:\ProgramData\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\.
  • Use icacls from an elevated PowerShell prompt to reset permissions if needed:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)F"

Step 3: Clear Conflicting Sessions and Reapply the Setting

  • Query sys.dm_exec_sessions to identify any other active sessions attempting to modify the same property.
  • Terminate conflicting sessions using KILL <session_id>;.
  • Reapply the property change using sp_configure or the relevant ALTER SERVER CONFIGURATION / ALTER DATABASE statement, then run RECONFIGURE WITH OVERRIDE;.

Step 4: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart SQL Server (MSSQLSERVER) and SQL Server Agent to flush cached configuration states.
  • Confirm the service starts cleanly without additional errors in the Windows Event Viewer under Application logs.

Alternative or Verification Steps

  • After restarting, re-run sp_configure or query the relevant system view (e.g., sys.configurations) to confirm the property value matches the intended setting and Error 5046 no longer appears in the SQL Server logs.
  • If the error persists, run DBCC CHECKDB against master and msdb to rule out metadata corruption as the underlying cause.

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

Troubleshooting Guide: SQL Server Error 5045

Why This Error Happens

Error 5045 occurs when a script or application attempts to set a property (such as a filegroup, file, or database option) that has already been defined earlier in the same statement or batch. This typically results from duplicate syntax in a CREATE DATABASE, ALTER DATABASE, or CREATE/ALTER TABLE statement, often introduced by poorly generated scripts, copy-paste errors, or third-party migration tools. It can also surface after an in-place upgrade to SQL Server 2025 if legacy T-SQL scripts use deprecated syntax that now conflicts with newer property validation logic.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Script or Statement

  • Open SQL Server Management Studio (SSMS) and locate the exact query that triggered Error 5045 in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Check the Activity Monitor or query history for the specific CREATE/ALTER statement referenced in the error message.
  • Note the specific property name mentioned in the '%ls' placeholder of the error text.

Step 2: Review and Clean the T-SQL Syntax

  • Search the script for duplicate clauses, such as two FILEGROWTH, MAXSIZE, or COLLATE definitions within the same ALTER DATABASE or CREATE TABLE block.
  • Remove the redundant property declaration, keeping only the first (or correct) instance.
  • If using a migration or deployment tool (e.g., SSDT, DACPAC), regenerate the script using the latest SQL Server 2025 compatible tooling to avoid legacy syntax duplication.

Step 3: Validate Database Compatibility Level

  • Run the following command to confirm the database is using a supported compatibility level for SQL Server 2025:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is outdated (e.g., 130 or lower), update it to reduce legacy parser conflicts:
ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 4: Re-run the Corrected Script

  • Execute the cleaned-up script in a non-production environment first.
  • Confirm that no other object-level scripts (triggers, stored procedures) reference the same duplicate property.
  • Check the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for any residual warnings tied to Event ID 5045.

Alternative or Verification Steps

  • Verify the fix by re-executing the original failing script in SSMS and confirming it completes with “Command(s) completed successfully” with no Error 5045 in the output pane.
  • If the error persists, use sp_helpdb 'YourDatabaseName' to inspect current file and filegroup properties for hidden duplicates that may not be visible in the original script.

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

Troubleshooting Guide: SQL Server Error 5044

Why This Error Happens

Error 5044 occurs when SQL Server removes a configuration object, trace flag, or server-level setting because it has been deprecated, superseded, or deemed invalid during startup or runtime reconfiguration. This typically happens after an in-place upgrade to SQL Server 2025 where legacy configuration entries in sys.configurations are no longer supported by the new engine. It can also surface when corrupted or orphaned metadata remains in the msdb or master system databases following an incomplete patch installation.

Step-by-Step Resolution Guide

Step 1: Review the SQL Server Error Log for Context

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Navigate to Management > SQL Server Logs and locate the exact timestamp of Error 5044.
  • Identify the specific %S_MSG value and configuration name referenced in the message text to determine which setting was removed.
  • Alternatively, run EXEC xp_readerrorlog 0, 1, N'5044'; in a query window to filter directly for this event.

Step 2: Validate and Reset Server Configuration Values

  • Run sp_configure with no parameters to list all current advanced and standard options.
  • Compare the output against Microsoft’s official SQL Server 2025 configuration reference to spot deprecated entries.
  • If a legacy option (e.g., an old trace flag or advanced option) is flagged, remove it using:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure '<deprecated_option_name>', 0;
RECONFIGURE WITH OVERRIDE;

Step 3: Rebuild or Repair System Database Metadata

  • Stop the SQL Server service via SQL Server Configuration Manager.
  • Launch a repair using Setup: Setup.exe /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=<YourAdminAccount> (only if master database corruption is confirmed).
  • If rebuilding is not required, instead run DBCC CHECKDB('master') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm system database integrity before restarting the service.

Step 4: Apply the Latest Cumulative Update

  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Run the installer as Administrator on Windows Server 2025 or Windows 11 to ensure patched binaries replace any files affected by the removed configuration.
  • Restart the SQL Server service and monitor the error log for recurrence of Event ID 5044.

Alternative or Verification Steps

  • After applying fixes, restart the SQL Server service and re-check the Error Log for 30 minutes of uptime to confirm Error 5044 does not reappear.
  • If the issue persists, restore the master database from a pre-upgrade backup taken before the SQL Server 2025 migration, then reapply only validated configuration changes.

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

Troubleshooting Guide: SQL Server Error 5043

Why This Error Happens

Error 5043 occurs when SQL Server cannot locate a specified resource—such as a filegroup, partition scheme, partition function, or configuration object—within the referenced database or scope. This typically stems from a mismatched or misspelled object name in a T-SQL command, a filegroup that was dropped or never created, or metadata corruption following an incomplete restore, upgrade, or migration process. It can also surface when scripts written for one database are executed against another database that lacks the referenced object.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Object Name and Scope

  • Run SELECT name FROM sys.filegroups; (or sys.partition_schemes / sys.partition_functions depending on the error context) to confirm the exact name SQL Server expects.
  • Check for case sensitivity or trailing whitespace issues if the instance uses a case-sensitive collation.
  • Confirm you are connected to the correct database using SELECT DB_NAME(); before re-running the failing command.

Step 2: Cross-Check the Script Against the Target Database

  • Open the script that triggered Error 5043 and compare the referenced object name against the output from Step 1.
  • If the script was copied from another environment (e.g., staging to production), update the filegroup/partition names to match the current database’s actual schema.
  • Re-run the corrected statement using SQL Server Management Studio (SSMS) 21 or sqlcmd on Windows Server 2025.

Step 3: Inspect for Metadata Corruption

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption in system catalogs.
  • If corruption is found, review the latest clean backup and restore it to a test instance to confirm object integrity.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for related warnings around the time the object was last modified or dropped.

Step 4: Rebuild or Recreate the Missing Object

  • If the filegroup or partition function was mistakenly dropped, recreate it using ALTER DATABASE YourDB ADD FILEGROUP [FilegroupName];.
  • For partition schemes, re-issue the original CREATE PARTITION FUNCTION and CREATE PARTITION SCHEME statements from your deployment scripts.
  • Ensure the SQL Server Agent service account has appropriate permissions under Services.msc on Windows Server 2025 to execute DDL changes.

Alternative or Verification Steps

  • Re-execute the original failing query or stored procedure and confirm it completes without raising Error 5043 in SSMS or the Windows Event Viewer (Application log, source “MSSQLSERVER”).
  • If the issue persists, restore a known-good backup to a separate instance and compare sys.filegroups and sys.partition_schemes output against production to identify what’s missing.

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

Troubleshooting Guide: SQL Server Error 5042

Why This Error Happens

Error 5042 occurs when an attempt is made to remove a filegroup or database file while it still contains data pages, tables, indexes, or allocated objects. SQL Server enforces this restriction because dropping a non-empty filegroup or file would result in orphaned data and potential corruption. This typically happens when a DBA tries to run ALTER DATABASE ... REMOVE FILE or REMOVE FILEGROUP without first migrating or clearing out the objects residing on that file/filegroup.

Step-by-Step Resolution Guide

Step 1: Identify Objects Residing on the Target File or Filegroup

  • Run the following query to find tables/indexes still allocated to the filegroup in question:
SELECT o.name AS ObjectName, i.name AS IndexName, f.name AS FilegroupName
FROM sys.indexes i
JOIN sys.filegroups f ON i.data_space_id = f.data_space_id
JOIN sys.objects o ON i.object_id = o.object_id
WHERE f.name = 'YourFilegroupName';
  • Note down every object returned — these must be relocated before removal.

Step 2: Move Data to Another Filegroup

  • For each table/index identified, rebuild it onto the PRIMARY filegroup or another valid filegroup:
CREATE CLUSTERED INDEX IX_Temp ON dbo.YourTable(YourColumn) 
WITH (DROP_EXISTING = ON) ON [PRIMARY];
  • For heap tables, use ALTER TABLE ... MOVE TO (available in SQL Server 2025 for enhanced heap management).
  • Repeat this process for all indexes, including non-clustered indexes, until the filegroup shows zero allocated extents.

Step 3: Verify the File/Filegroup is Empty

  • Check allocation status using sys.dm_db_file_space_usage or sp_spaceused:
SELECT * FROM sys.dm_db_file_space_usage 
WHERE database_id = DB_ID('YourDatabase');
  • Confirm unallocated_extent_page_count equals the total pages in the file (i.e., 100% empty).

Step 4: Shrink the File Before Removal

  • Run DBCC SHRINKFILE with the EMPTYFILE option to force SQL Server to migrate any remaining pages automatically:
DBCC SHRINKFILE (YourLogicalFileName, EMPTYFILE);
  • Wait for the command to complete without errors — this guarantees the file is truly empty.

Step 5: Remove the File or Filegroup

  • Once confirmed empty, execute the removal command:
ALTER DATABASE YourDatabase REMOVE FILE YourLogicalFileName;
ALTER DATABASE YourDatabase REMOVE FILEGROUP YourFilegroupName;
  • Validate that no error 5042 is returned.

Alternative or Verification Steps

  • Re-run the sys.dm_db_file_space_usage query post-removal to confirm the file/filegroup no longer appears in sys.database_files or sys.filegroups.
  • If EMPTYFILE fails due to LOB or unmovable data (common with FILESTREAM or forced allocation), restore a backup to a test environment, manually script-transfer the affected objects, and retry the removal sequence there before applying it to production.

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

Troubleshooting Guide: SQL Server Error 5041 – MODIFY FILE Failed

Why This Error Happens

Error 5041 occurs when the ALTER DATABASE ... MODIFY FILE command references a logical file name that does not currently exist in the target database’s system catalog (sys.database_files). This typically happens due to a mismatch between the logical name specified in the T-SQL script and the actual logical name stored in SQL Server 2025, often caused by case sensitivity issues, a typo, or because the database file structure was altered by a previous restore/migration without updating corresponding scripts. It can also occur if the file was already detached, orphaned, or removed from the primary filegroup prior to the execution of the modify command.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Logical File Name

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the following query to list the exact logical names associated with the database: SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Compare the name column output directly against the string used in your MODIFY FILE (NAME = '...') command, checking specifically for trailing spaces or incorrect casing.

Step 2: Correct the T-SQL Syntax

  • Update your script to match the exact logical name retrieved in Step 1.
  • Ensure you are modifying the correct database by checking the active connection context: USE [YourDatabaseName]; GO
  • Re-run the corrected command, for example: ALTER DATABASE [YourDatabaseName] MODIFY FILE (NAME = N'CorrectLogicalName', SIZE = 500MB);

Step 3: Check for Orphaned Files or Recent Restores

  • If the database was recently restored or migrated on the Windows Server 2025 host, the file structure might differ from the backup’s original metadata.
  • Check the SQL Server Error Log (usually located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for any file-related warnings during the last startup.
  • If the file was detached, use sp_attach_db or re-add the file using ADD FILE instead of MODIFY FILE if the intent was to create a new file rather than alter an existing one.

Step 4: Restart the SQL Server Service (If Cache Issue Suspected)

  • In rare cases, the metadata cache on Windows Server 2025 may not have refreshed following a manual file system change.
  • Open Services.msc, locate SQL Server (MSSQLSERVER), right-click, and select Restart.
  • Re-attempt the MODIFY FILE command once the service is back online.

Alternative or Verification Steps

  • Verification: Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; to ensure the database integrity remains consistent after the file names are corrected.
  • Alternative: If the logical file is genuinely missing (not just a typo) and the physical .mdf/.ndf file exists on disk, use CREATE DATABASE... FOR ATTACH to rebuild the metadata entry rather than attempting a MODIFY on a non-existent entry.

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

Troubleshooting Guide: SQL Server Error 5040 – “MODIFY FILE Failed”

Why This Error Happens

Error 5040 occurs when SQL Server cannot alter a database file’s properties (size, name, or path) because the file is currently in use, locked by another process, or the specified path/filegroup is invalid. This commonly happens when attempting to modify a file while active transactions or connections are holding locks on the database, or when the target directory specified in the MODIFY FILE statement does not exist or lacks proper permissions. In some cases, this error also surfaces due to corrupted filegroup metadata or an attempt to shrink/resize a file below its minimum allowable size.

Step-by-Step Resolution Guide

Step 1: Verify Database and File State

  • Check if the database is in a RESTORING, RECOVERY_PENDING, or SUSPECT state using sp_helpdb or querying sys.databases.
  • Run the following to confirm file status:
  SELECT name, physical_name, state_desc FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Ensure no other sessions are actively using the file via sys.dm_exec_sessions or sp_who2.

Step 2: Set Database to Single-User Mode

  • Switching to single-user mode releases unnecessary locks that may block the MODIFY FILE operation.
  • Execute:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Retry the ALTER DATABASE ... MODIFY FILE command after isolating the connection.

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

  • Confirm the target directory (e.g., D:\SQLData\ or E:\SQLLogs\) exists and is accessible.
  • Check that the SQL Server service account (found in SQL Server Configuration Manager) has Full Control permissions on the folder via Properties > Security in Windows Explorer.
  • If moving files to a new path, ensure the physical file is also moved manually using robocopy or File Explorer before executing the MODIFY FILE command.

Step 4: Check for Minimum Size Constraints

  • If resizing a file, ensure the new size is not smaller than the current allocated space used by the database.
  • Run DBCC SQLPERF(LOGSPACE) or check sys.dm_db_file_space_usage to determine current space consumption before attempting a shrink via MODIFY FILE.

Step 5: Restart SQL Server Service and Reapply Changes

  • Set the database back to multi-user mode:
  ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Restart the SQL Server (MSSQLSERVER) service via Services.msc on Windows Server 2025 to clear any residual file handles before reapplying the MODIFY FILE statement.

Alternative or Verification Steps

  • Verify the fix by querying sys.master_files again to confirm the physical_name or size reflects the updated configuration without triggering Error 5040.
  • If the issue persists, use DBCC CHECKDB to rule out underlying corruption in the database’s file structure, or detach/re-attach the database as a last resort (ensure a full backup is taken first).

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

Troubleshooting Guide: Error 5039 – MODIFY FILE Failed in SQL Server 2025

Why This Error Happens

Error 5039 occurs when an ALTER DATABASE ... MODIFY FILE statement attempts to set a data or log file’s size to a value that is smaller than or equal to its current allocated size. SQL Server’s MODIFY FILE command is designed exclusively for growing files or changing file properties (like FILEGROWTH or file path on restart); it cannot be used to shrink a file. This typically happens when an administrator miscalculates the current file size in MB/GB or confuses the MODIFY FILE command with the DBCC SHRINKFILE command, which is the correct tool for reducing file size.

Step-by-Step Resolution Guide

Step 1: Verify the Current File Size

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check the exact current size of the file in megabytes (SQL Server stores size in 8-KB pages internally):
SELECT name AS FileName, size/128.0 AS CurrentSizeMB 
FROM sys.database_files;
  • Compare this output to the value you attempted to use in your MODIFY FILE statement to confirm the conflict.

Step 2: Correct the T-SQL Syntax for Growth

  • If your intention was to increase the size, ensure the new size value is strictly greater than the current size found in Step 1.
  • Execute the corrected command with a valid incremental value:
ALTER DATABASE [YourDatabaseName] 
MODIFY FILE (NAME = N'YourLogicalFileName', SIZE = 20480MB);
  • Ensure there is sufficient disk space on the Windows Server 2025 volume (e.g., D:\SQLData) to accommodate the new size before executing.

Step 3: Use DBCC SHRINKFILE for Reductions

  • If the actual goal was to reduce the file size, do not use MODIFY FILE. Instead, use the DBCC SHRINKFILE command.
  • Run the following command to shrink the file to a specific target size in MB:
USE [YourDatabaseName];
GO
DBCC SHRINKFILE (N'YourLogicalFileName', 15000);
  • Be cautious of fragmentation; shrinking files is generally discouraged in production environments as it can severely impact performance.

Step 4: Check for Instant File Initialization (IFI) Conflicts

  • In rare cases on Windows Server 2025, discrepancies in “size on disk” vs. “logical size” reporting can occur if the Perform Volume Maintenance Tasks policy is misconfigured.
  • Verify the SQL Server service account has this permission via secpol.msc under Local Policies > User Rights Assignment to ensure file operations report accurate size metadata to the Database Engine.

Alternative or Verification Steps

  • Verify the Fix: Re-run the sys.database_files query from Step 1 after executing your command to confirm the size column reflects the new, larger value you intended to set.
  • Alternative: If you need to migrate data to a smaller file structure entirely (rather than shrinking), create a new filegroup, move the data via CREATE INDEX ... WITH (DROP_EXISTING = ON) on the new filegroup, and then remove the old, oversized file once it is empty.

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

Troubleshooting Guide: SQL Server Error 5038 – “MODIFY FILE failed”

Why This Error Happens

Error 5038 occurs when an ALTER DATABASE ... MODIFY FILE statement is executed without specifying at least one modifiable property (such as SIZE, FILEGROWTH, MAXSIZE, or NEWNAME) in the command. This is typically caused by a syntax omission where the FILENAME property alone is provided, or where the file properties clause is empty or malformed. In SQL Server 2025, this validation check has become stricter, causing scripts that previously ran on older versions (via legacy automation or deployment tools) to now fail during execution.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Statement

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and review the exact query that triggered Error 5038.
  • Check SQL Server Error Logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full query context.
  • Look specifically for ALTER DATABASE [YourDB] MODIFY FILE (NAME = 'logical_name') statements missing additional parameters.

Step 2: Correct the T-SQL Syntax

  • Rewrite the statement to include at least one valid property inside the parentheses.
  • Example of broken syntax: ALTER DATABASE MyDB MODIFY FILE (NAME = N'MyDB_log');
  • Example of corrected syntax: ALTER DATABASE MyDB MODIFY FILE (NAME = N'MyDB_log', SIZE = 51200KB);
  • Ensure you specify a valid property such as SIZE, MAXSIZE, FILEGROWTH, or NEWNAME depending on the intended administrative action.

Step 3: Validate File Metadata Before Re-running

  • Run SELECT name, physical_name, size, growth FROM sys.master_files WHERE database_id = DB_ID('MyDB'); to confirm the current state of the file.
  • Cross-reference the logical file name to ensure it matches exactly (case-sensitivity and trailing spaces can cause mismatches).
  • Re-execute the corrected ALTER DATABASE command in a test/staging environment first if this is a production server.

Step 4: Update Automation Scripts or Deployment Tools

  • If the error originates from a third-party backup tool, ORM migration script, or PowerShell deployment module, check for a version update.
  • Navigate to the tool’s configuration directory (e.g., C:\Scripts\DBDeploy\) and inspect any .sql template files for incomplete MODIFY FILE blocks.
  • Patch the template to include a static or dynamically calculated property value before re-deploying.

Alternative or Verification Steps

  • Verify the fix by querying sys.database_files immediately after running the corrected command to confirm the size or growth values were updated as expected.
  • If the error persists despite correct syntax, restart the SQL Server service via services.msc or run sqlcmd -S localhost -Q "SELECT @@VERSION" to rule out a stale metadata cache issue following a recent SQL Server 2025 cumulative update.

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

Troubleshooting Guide: Error 5036 – “MODIFY FILE Failed. Specify Logical Name.”

Why This Error Happens

This error occurs when an ALTER DATABASE ... MODIFY FILE statement references a logical file name that does not exist in the target database, usually due to a typo or mismatch with the actual name stored in system catalogs. It can also happen if the database schema was recently restored, renamed, or migrated from another instance, causing the logical names in sys.master_files to differ from what the administrator expects. In some cases, case sensitivity on a case-sensitive collation instance causes an otherwise “correct-looking” name to fail validation.

Step-by-Step Resolution Guide

Step 1: Verify the Correct Logical File Name

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to list actual logical names for the target database:
SELECT name AS LogicalName, physical_name, type_desc 
FROM sys.master_files 
WHERE database_id = DB_ID('YourDatabaseName');
  • Compare the LogicalName column output against the name used in your MODIFY FILE command.

Step 2: Correct the ALTER DATABASE Statement

  • Update your T-SQL script to reference the exact logical name (case-sensitive if the instance uses a binary or case-sensitive collation).
  • Example corrected syntax:
ALTER DATABASE YourDatabaseName 
MODIFY FILE (NAME = 'YourDatabaseName_Data', SIZE = 500MB);
  • Ensure there are no trailing spaces or hidden characters copied from documentation or scripts.

Step 3: Check for Recent Restore or Attach Operations

  • If the database was recently restored or attached on Windows Server 2025, logical names may differ from the original source server.
  • Run sp_helpfile while connected to the specific database to cross-reference names:
USE YourDatabaseName;
EXEC sp_helpfile;
  • Update any deployment or maintenance scripts to reflect the current logical names post-migration.

Step 4: Validate Permissions and Script Execution Context

  • Confirm the executing account has ALTER permission on the database (db_owner or sysadmin role).
  • Re-run the script as a user with elevated privileges if a permissions-related silent failure is suspected alongside the naming issue.

Alternative or Verification Steps

  • After correcting the logical name, re-run the ALTER DATABASE MODIFY FILE command and confirm it completes without error; then verify the change using sys.master_files again to confirm size/path updates were applied.
  • If the issue persists, generate a fresh scripting of the database file structure via SSMS (Right-click Database → Tasks → Generate Scripts) to ensure your reference script matches the live, current schema exactly.

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

Troubleshooting Guide: Error 5035 – Filegroup Already Exists in Database

Why This Error Happens

This error occurs when a Transact-SQL statement attempts to create a filegroup using a name that is already registered in the sys.filegroups system catalog view for that database. SQL Server enforces unique filegroup names per database, so this typically results from a duplicate entry in a deployment script, a naming collision during a database restore/migration, or a developer re-running a schema creation script without first checking for existing objects. It can also surface during automated CI/CD pipeline deployments where idempotency checks are missing.

Step-by-Step Resolution Guide

Step 1: Verify the Existing Filegroup Name

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio and connect to the target instance.
  • Run the following query to list all current filegroups in the database:
  SELECT name, data_space_id, type_desc, is_default 
  FROM sys.filegroups;
  • Confirm whether the filegroup name in your error message (e.g., FG_SalesData) already exists in the result set.

Step 2: Decide Whether to Reuse, Rename, or Remove

  • If the existing filegroup is empty and not needed, remove it using:
  ALTER DATABASE [YourDatabaseName] REMOVE FILEGROUP [FG_SalesData];
  • If the filegroup contains data files and is still required, rename your new filegroup in the script instead (e.g., change FG_SalesData to FG_SalesData_v2).
  • If you intended to use the existing filegroup rather than create a new one, simply remove the CREATE FILEGROUP statement from your script.

Step 3: Modify and Re-Run the Deployment Script

  • Open the .sql deployment file (commonly located in C:\DeploymentScripts\ or your DACPAC/SSDT project folder).
  • Add a conditional existence check before the CREATE FILEGROUP statement:
  IF NOT EXISTS (SELECT 1 FROM sys.filegroups WHERE name = N'FG_SalesData')
  BEGIN
      ALTER DATABASE [YourDatabaseName] ADD FILEGROUP [FG_SalesData];
  END
  • Save the script and re-execute it against the target instance.

Step 4: Check for Duplicate Entries in Deployment/Migration Tools

  • If using SSDT, EF Core Migrations, or Flyway, inspect the migration history table (e.g., __EFMigrationsHistory or schema_version) for duplicate or out-of-order migration entries.
  • Clear any stale cached build artifacts in bin\ or obj\ folders if using Visual Studio 2022/2025 SSDT projects, then rebuild the project.

Alternative or Verification Steps

  • Re-run the original failing script or deployment pipeline and confirm it completes without throwing Error 5035.
  • As an alternative, use sp_helpfile or query sys.database_files joined with sys.filegroups to cross-verify that the filegroup-to-file mapping is correct and no orphaned references remain before retrying the operation.

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

Troubleshooting Guide: SQL Server Error 5034

Why This Error Happens

Error 5034 occurs when a database file is locked by an internal SQL Server operation—typically an autogrow event, DBCC SHRINKFILE, or another file-modification task—at the exact moment another process attempts to access or modify that same file. This is a concurrency conflict rather than a corruption issue: SQL Server enforces a file-level lock during autogrow/autoshrink operations to maintain data integrity, and overlapping requests (such as a second growth event or a concurrent backup) are rejected until the lock is released. It is often exacerbated by small autogrowth increments, which cause the file to grow frequently and increase the window for collision.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Process

  • Query sys.dm_exec_requests and sys.dm_os_waiting_tasks to check for active DBCC SHRINKFILE, ALTER DATABASE MODIFY FILE, or autogrow operations running against the affected database.
  • Check the SQL Server Error Log (via SSMS > Management > SQL Server Logs, or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for recent “Autogrow” entries timestamped near the error.
  • Run SELECT name, physical_name, growth, is_percent_growth FROM sys.master_files WHERE database_id = DB_ID('YourDB'); to confirm current growth settings.

Step 2: Adjust Autogrowth Settings to Reduce Collision Frequency

  • Open SSMS, right-click the database > Properties > Files, and change autogrowth from a percentage-based value to a fixed MB increment (e.g., 256MB or 512MB) to reduce how often growth events trigger.
  • Alternatively, run: ALTER DATABASE [YourDB] MODIFY FILE (NAME = 'YourDB_Data', FILEGROWTH = 256MB);
  • Pre-size the data and log files to their expected production size using ALTER DATABASE ... MODIFY FILE (SIZE = ...) to minimize future autogrow events entirely.

Step 3: Enable Instant File Initialization (IFI)

  • On Windows Server 2025/Windows 11, grant the SQL Server service account the “Perform Volume Maintenance Tasks” permission via secpol.msc > Local Policies > User Rights Assignment.
  • Restart the SQL Server service (via SQL Server Configuration Manager) for the policy change to take effect.
  • Verify IFI is active by checking the Error Log for the message “Database Instant File Initialization: enabled” after restart; this drastically shortens the autogrow lock window for data files (note: log files cannot use IFI).

Step 4: Retry the Operation and Avoid Overlapping Maintenance Jobs

  • Reschedule any overlapping SQL Agent jobs (backups, index maintenance, shrink operations) so they don’t run concurrently with periods of high transactional growth.
  • Re-run the failed query, backup, or application transaction after confirming no blocking session remains in sys.dm_exec_requests.

Alternative or Verification Steps

  • Verify the fix: Monitor sys.dm_os_performance_counters for the “Auto-Grow” counter or re-check the Error Log over 24–48 hours to confirm autogrow events no longer overlap with failed operations.
  • Alternative: If frequent growth is unavoidable due to workload volatility, manually pre-allocate file sizes during a maintenance window and disable autogrowth entirely (FILEGROWTH = 0), pairing this with proactive disk space monitoring/alerts.

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

Troubleshooting Guide: SQL Server Error 5033 — “The maximum of %ld files per database has been exceeded”

Why This Error Happens

SQL Server 2025 enforces a hard architectural limit of 32,767 files per database (data and log files combined), and this error triggers when a database attempts to exceed that ceiling. This typically occurs due to excessive filegroup fragmentation, automated scripts that repeatedly add files without cleanup, or a corrupted system catalog (sys.database_files) that miscounts existing file entries. In rare cases, replication or Always On Availability Group metadata synchronization issues can cause phantom file entries that count against this limit without being visibly usable.

Step-by-Step Resolution Guide

Step 1: Audit the Current File Count

  • Connect via SQL Server Management Studio (SSMS) or sqlcmd on your Windows Server 2025 instance.
  • Run the following query to inspect existing files:
  SELECT COUNT(*) AS TotalFiles, type_desc 
  FROM sys.database_files 
  GROUP BY type_desc;
  • Cross-reference this against SELECT COUNT(*) FROM sys.master_files WHERE database_id = DB_ID('YourDBName'); to confirm consistency between catalogs.

Step 2: Remove Orphaned or Unused Files

  • Identify empty or unnecessary secondary data files using:
  DBCC SHRINKFILE (N'LogicalFileName', EMPTYFILE);
  • Once confirmed empty, remove the file safely:
  ALTER DATABASE YourDBName REMOVE FILE LogicalFileName;
  • Avoid scripts or ORM migrations that auto-generate new file(s) on every schema deployment — audit any CI/CD pipelines publishing schema changes.

Step 3: Consolidate Filegroups

  • Instead of continuously adding new files, merge underutilized filegroups into fewer, larger files.
  • Use sp_helpfile to list current file allocations and move data using ALTER DATABASE ... MODIFY FILEGROUP to redistribute objects onto consolidated containers.
  • For Windows Server 2025 environments using Storage Spaces Direct (S2D), ensure your volume block size supports larger file growth increments, reducing the need for multiple small files.

Step 4: Rebuild Corrupted System Metadata (If Count Mismatch Persists)

  • Run DBCC CHECKDB (YourDBName) WITH DATA_PURITY; to validate catalog integrity.
  • If mismatches in file metadata persist, restore the database from a known-good backup or use sp_detach_db / sp_attach_db to force SQL Server to rebuild the internal file catalog reference.

Alternative or Verification Steps

  • After remediation, re-run SELECT COUNT(*) FROM sys.database_files; and confirm the total is safely below 32,767 — attempt a test ALTER DATABASE ADD FILE operation to confirm the error no longer triggers.
  • If the issue persists despite a low file count, check for Windows Server 2025 Group Policy restrictions or antivirus/EDR software (e.g., Windows Defender ATP) that may be locking or duplicating .mdf/.ldf handles, causing SQL Server to miscalculate active file entries.

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

Troubleshooting Guide: SQL Server Error 5032

Why This Error Happens

This error occurs when SQL Server 2025 attempts to shrink a database file, but the file contains bulk logged pages that have not yet been backed up. Because the database is operating in Bulk-Logged or Full recovery model, SQL Server must preserve these pages for point-in-time recovery integrity until a transaction log backup is performed. Until that backup occurs, SQL Server cannot reclaim the space occupied by those pages, causing the shrink operation to fail or stop short of the target size.

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 recovery model:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the database is set to FULL or BULK_LOGGED, as this directly explains the presence of bulk logged pages.

Step 2: Perform a Transaction Log Backup

  • Execute a log backup to clear the bulk logged pages and allow space reclamation:
  BACKUP LOG [YourDatabaseName] TO DISK = 'C:\SQLBackups\YourDatabase_Log.trn';
  • Ensure the backup destination folder (e.g., C:\SQLBackups\) exists and has sufficient permissions on Windows Server 2025.
  • If backups have never been taken, confirm this is the first full backup has already been completed; log backups require a preceding full backup.

Step 3: Retry the Shrink Operation

  • After the log backup completes successfully, retry the shrink command:
  DBCC SHRINKFILE (YourLogicalFileName, TargetSizeInMB);
  • Monitor the output to confirm the file has shrunk to the desired size without triggering Error 5032 again.

Step 4: Automate Log Backups to Prevent Recurrence

  • Use SQL Server Agent (via SSMS > SQL Server Agent > Jobs) to schedule regular transaction log backups.
  • Set a recurring schedule (e.g., every 15–30 minutes) depending on your Recovery Point Objective (RPO).
  • This prevents bulk logged pages from accumulating and triggering the same shrink failure in the future.

Alternative or Verification Steps

  • Verify the Fix: Run DBCC SQLPERF(LOGSPACE); to confirm log space usage has decreased, and re-check file size via sp_helpfile to ensure the shrink was successful.
  • Alternative Solution: If shrinking is still blocked, temporarily switch the recovery model to SIMPLE, perform the shrink, then switch back to FULL or BULK_LOGGED — note this will break the log backup chain, so take a full backup immediately afterward.

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

Troubleshooting Guide: Error 5031 – Cannot Remove File from DEFAULT Filegroup

Why This Error Happens

This error occurs because SQL Server 2025 enforces a strict architectural rule: the PRIMARY (DEFAULT) filegroup must always contain at least one data file to host system tables and catalog views. When an administrator attempts to drop the last remaining .mdf or .ndf file associated with the default filegroup, the Database Engine rejects the operation to prevent corruption of system metadata. This typically happens during database shrink operations or manual file cleanup where the administrator miscounted the remaining files in that specific filegroup.

Step-by-Step Resolution Guide

Step 1: Verify the Filegroup File Structure

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check how many files exist in the target filegroup:
  SELECT name, physical_name, type_desc, state_desc 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');
  • Confirm if the file you are trying to drop is indeed the sole resident of the PRIMARY filegroup.

Step 2: Add a New File to the Filegroup (If Deletion is Mandatory)

  • If you must move data off the specific physical file (e.g., due to disk space issues on a specific drive), add a new file to the same filegroup first.
  • Use this syntax to add a placeholder/replacement file:
  ALTER DATABASE YourDatabaseName 
  ADD FILE (NAME = NewPrimaryFile, FILENAME = 'C:\SQLData\NewPrimaryFile.ndf') 
  TO FILEGROUP [PRIMARY];
  • Ensure the path C:\SQLData\ exists and the SQL Server Service Account has write permissions on Windows Server 2025.

Step 3: Empty the Original File

  • Before you can drop the original file, you must empty it so SQL Server migrates the data pages to the newly added file.
  • Execute the EMPTYFILE command to redistribute data:
  DBCC SHRINKFILE (OldFileLogicalName, EMPTYFILE);
  • Wait for the command to complete, as this transfers all extents to other available files in the filegroup.

Step 4: Remove the Original File

  • Once the file is confirmed empty (0 KB of actual data), you can now safely remove it since the filegroup will still contain the new file you added in Step 2.
  • Run the removal command:
  ALTER DATABASE YourDatabaseName REMOVE FILE OldFileLogicalName;

Alternative or Verification Steps

  • Verification: Re-run the sys.master_files query from Step 1 to ensure the old file is gone and the new file is listed with state_desc = ONLINE.
  • Alternative: If the goal was only to relocate the database (not delete data), consider using the OFFLINE, move-file-on-disk, and MODIFY FILE (to update the path) method instead of dropping the file entirely, which avoids the EMPTYFILE migration step.

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

Troubleshooting Guide: SQL Server Error 5030 – “Database could not be exclusively locked”

Why This Error Happens

Error 5030 occurs when SQL Server attempts to acquire an exclusive lock on a database (required for operations like RESTORE, ALTER DATABASE SET OFFLINE, or detaching a database) but cannot do so because one or more active sessions are still connected to it. This is commonly caused by lingering user connections, open transactions, background processes like SQL Server Agent jobs, or monitoring tools (such as SSMS Object Explorer or third-party backup agents) maintaining a live connection to the database. On Windows Server 2025 / Windows 11 hosts, this can also be triggered by antivirus or Windows Defender real-time scanning processes that momentarily lock the underlying .mdf/.ldf files.

Step-by-Step Resolution Guide

Step 1: Identify Active Connections to the Database

  • Run the following query in SQL Server Management Studio (SSMS) to list all sessions connected to the target database:
  • SELECT session_id, login_name, host_name, program_name, status FROM sys.dm_exec_sessions WHERE database_id = DB_ID('YourDatabaseName');
  • Note any session_id values other than your own current session.

Step 2: Terminate Blocking Sessions

  • Kill each identified session using the KILL command, substituting the correct session ID:
  • KILL 55;
  • If the session doesn’t terminate immediately, wait for the rollback to complete before retrying the operation.

Step 3: Set the Database to Single-User Mode

  • Force the database into single-user mode to drop all other connections automatically:
  • ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Immediately proceed with your intended operation (restore, detach, etc.) while in this state.

Step 4: Check for External Process Locks on Windows

  • Open Resource Monitor (resmon.exe) on Windows Server 2025 / Windows 11 and search the “CPU” tab’s associated handles for sqlservr.exe or any backup/antivirus agent locking the .mdf/.ldf files located typically at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Temporarily exclude the SQL Server data directory from Windows Defender real-time scanning via Windows Security > Virus & threat protection > Exclusions.

Step 5: Restart the SQL Server Service (If Needed)

  • If locks persist despite killing sessions, restart the SQL Server service via services.msc or run:
  • net stop MSSQLSERVER && net start MSSQLSERVER
  • This clears all active connections and internal locks tied to the instance.

Alternative or Verification Steps

  • After completing the steps above, verify the fix by re-running your original command (e.g., RESTORE DATABASE or ALTER DATABASE ... SET OFFLINE) and confirming it completes without Error 5030.
  • If the issue persists, revert the database to multi-user mode using ALTER DATABASE YourDatabaseName SET MULTI_USER; and check SQL Server Error Logs (SSMS > Management > SQL Server Logs) for orphaned sessions or lingering replication/mirroring configurations that may be holding a lock.

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

Troubleshooting Guide: SQL Server Error 5029 — Log Rebuild / Broken RESTORE Chain

Why This Error Happens

This error occurs when the transaction log for a database has been forcibly rebuilt, typically through ALTER DATABASE ... REBUILD LOG or an emergency-mode repair (DBCC CHECKDB with REPAIR_ALLOW_DATA_LOSS), which breaks the Log Sequence Number (LSN) chain. Once the log is rebuilt, SQL Server can no longer guarantee transactional consistency because the new log has no knowledge of prior transactions, invalidating any future differential or transaction log restores that depend on the original chain. This commonly happens after severe log corruption, a damaged VLF (Virtual Log File), or an administrator manually intervening to bring a suspect database back online without realizing it breaks the backup lineage.

Step-by-Step Resolution Guide

Step 1: Confirm the Scope of the Break

  • Check SQL Server Error Log and Event Viewer (Windows Logs > Application) for Event ID 5029 timestamps.
  • Run RESTORE HEADERONLY FROM DISK = 'path_to_backup.bak' to confirm the LastLSN and DatabaseBackupLSN no longer align with later differential/log backups.
  • Identify exactly which backup file or operation triggered the rebuild (check msdb.dbo.backupset for is_damaged or chain gaps).

Step 2: Take an Immediate Full Backup

  • Since the log chain is already broken, take a fresh full backup immediately to establish a new recovery baseline:
  • BACKUP DATABASE [YourDB] TO DISK = 'D:\Backups\YourDB_FULL.bak' WITH INIT, COMPRESSION;
  • This becomes your new “Day Zero” for future differential and log backups—older log/diff backups taken before this point are no longer usable for restore chaining.

Step 3: Re-Establish the Backup Chain

  • Switch the database back to FULL recovery model if it was altered during troubleshooting:
  • ALTER DATABASE [YourDB] SET RECOVERY FULL;
  • Immediately follow the full backup with a log backup to start logging transactions cleanly:
  • BACKUP LOG [YourDB] TO DISK = 'D:\Backups\YourDB_LOG1.trn';
  • Update any SQL Agent maintenance plans or scripts (in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\) to reference the new baseline backup.

Step 4: Investigate Root Cause of Log Corruption

  • Run DBCC CHECKDB('YourDB') WITH NO_INFOMSGS, ALL_ERRORMSGS to rule out underlying disk or storage corruption.
  • Check Windows Server 2025 Event Viewer for disk-related errors (Event ID 7, 9, 51) under System logs, which often precede log corruption.
  • Validate storage health using Get-PhysicalDisk | Get-StorageReliabilityCounter in PowerShell if running on physical or virtualized storage.

Alternative or Verification Steps

  • Verify the fix by taking a test differential backup and restoring it with WITH NORECOVERY on a secondary test instance to confirm the chain now holds.
  • If corruption recurs, consider migrating the database files to a different storage volume and enabling CHECKSUM page verification (ALTER DATABASE [YourDB] SET PAGE_VERIFY CHECKSUM;) to catch future I/O-level issues early.

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

Why This Error Happens

Error 5028 occurs when SQL Server cannot activate a sufficient number of database files to perform the log rebuild operation, typically because one or more secondary data files (.ndf) are missing, offline, or inaccessible at startup. This can also result from corrupted file headers, incorrect file paths after a migration, or insufficient permissions on the SQL Server service account preventing access to the physical files. In some cases, the error surfaces when a database was improperly detached or when storage volumes were disconnected before SQL Server could cleanly bring all files online.

Step-by-Step Resolution Guide

Step 1: Verify File Locations and Accessibility

  • Check SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact file path SQL Server expects.
  • Confirm all .mdf, .ndf, and .ldf files physically exist at those paths using File Explorer or dir in Command Prompt.
  • If files were moved, copy them back to their original location or prepare to update the path using ALTER DATABASE.

Step 2: Validate Service Account Permissions

  • Open Services.msc, locate “SQL Server (MSSQLSERVER)”, and confirm the Log On account.
  • Right-click the database folder (e.g., D:\SQLData\) → Properties → Security, and ensure the SQL Server service account has Full Control.
  • Restart the SQL Server service after applying permission changes:
  net stop MSSQLSERVER
  net start MSSQLSERVER

Step 3: Bring the Database Online Using Emergency Mode

  • Open SQL Server Management Studio (SSMS) and run the following to assess damage:
  ALTER DATABASE YourDB SET EMERGENCY;
  DBCC CHECKDB(YourDB);
  • If corruption is confirmed, attempt a controlled repair:
  ALTER DATABASE YourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  DBCC CHECKDB(YourDB, REPAIR_ALLOW_DATA_LOSS);
  ALTER DATABASE YourDB SET MULTI_USER;
  • Use REPAIR_ALLOW_DATA_LOSS only as a last resort, since it may discard unrecoverable pages.

Step 4: Rebuild the Transaction Log (If Files Are Confirmed Present)

  • If all data files are present but the log is still failing to rebuild, detach and reattach the database with the FOR ATTACH_REBUILD_LOG option:
  CREATE DATABASE YourDB ON 
  (FILENAME = 'D:\SQLData\YourDB.mdf') 
  FOR ATTACH_REBUILD_LOG;
  • Ensure you have a full backup before attempting this, as rebuilding the log clears transaction history.

Alternative or Verification Steps

  • Run sp_helpdb YourDB or check Object Explorer in SSMS to confirm the database status shows ONLINE rather than RECOVERY_PENDING or SUSPECT.
  • If the database still won’t activate, restore from the most recent full backup and transaction log backups instead of attempting further repairs, as this guarantees data consistency.

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

Why This Error Happens

Error 5027 typically occurs during SQL Server startup when the Database Engine cannot gain exclusive access to the master database files (master.mdf / mastlog.ldf). This is most commonly caused by another process locking the files, an incorrect file path specified in the service startup parameters, or the SQL Server service account lacking the necessary NTFS permissions on the data directory. In some cases, a prior improper shutdown or a failed Windows Update on Windows Server 2025 can leave the system database files in an inconsistent or inaccessible state.

Step-by-Step Resolution Guide

Step 1: Verify the Service Account Has Proper Permissions

  • Open File Explorer and navigate to the SQL Server data directory, typically: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\
  • Right-click master.mdf and mastlog.ldf, go to Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • If permissions are missing, click Edit > Add, type the service account name, and grant Full Control, then click Apply.

Step 2: Confirm No Other Process Is Locking the Files

  • Open Task Manager or Resource Monitor and check if another instance of sqlservr.exe or a backup/antivirus tool is actively scanning or holding a handle on the DATA folder.
  • Use Sysinternals Handle.exe from an elevated Command Prompt to confirm: handle.exe master.mdf
  • Temporarily disable real-time antivirus scanning on the SQL data directory to rule out file locking conflicts.

Step 3: Validate Startup Parameters in SQL Server Configuration Manager

  • Launch SQL Server Configuration Manager (search for it in Windows 11/Server 2025 Start menu).
  • Select SQL Server Services, right-click your instance, and choose Properties > Startup Parameters.
  • Confirm the -d (master data file), -l (master log file), and -e (error log) paths exactly match the actual file locations on disk — correct any typos or outdated drive letters.

Step 4: Restore or Rebuild System Databases if Files Are Corrupted

  • If the files are missing or corrupted, restore master.mdf and mastlog.ldf from a recent verified backup into the correct DATA directory.
  • If no backup exists, run the SQL Server setup media with the /ACTION=REBUILDDATABASE switch from an elevated Command Prompt to regenerate the system databases:
    Setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=Administrators

Step 5: Restart the SQL Server Service

  • Open Services.msc, locate SQL Server (MSSQLSERVER), and restart it.
  • Monitor the SQL Server Error Log (ERRORLOG file in the LOG folder) for confirmation that the master database loaded without further 5027 errors.

Alternative or Verification Steps

  • Verify the fix by checking the SQL Server Error Log for the message “Recovery is complete” with no accompanying 5027 entries, and confirm the instance appears Running in Configuration Manager.
  • As an alternative, if corruption persists, perform a full repair installation of the SQL Server 2025 instance using the original setup media, selecting Repair from the Maintenance tab in the SQL Server Installation Center.

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

Why This Error Happens

SQL Server Error 5025 occurs when the Database Engine attempts to create a new transaction log file, but a file with the exact same physical name already exists in the target directory. This typically happens during database creation, log file addition (ALTER DATABASE), or database restore operations where a leftover .ldf file from a previous installation, failed detach, or manual copy operation was never cleaned up. SQL Server refuses to overwrite existing files automatically as a safeguard against accidental data loss.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting File Path

  • Open the full error message in SQL Server Management Studio (SSMS) or the SQL Server Error Log to capture the exact file path referenced by %ls.
  • Typical default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Use PowerShell to confirm the file exists:
  Test-Path "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\YourDB_log.ldf"

Step 2: Rename or Remove the Existing File

  • Stop the SQL Server service first via services.msc or by running:
  net stop MSSQLSERVER
  • Navigate to the DATA directory in File Explorer or PowerShell and rename the conflicting file (e.g., append _old to the filename) rather than deleting it outright, in case it contains needed data.
  • If the file is confirmed to be an orphaned/unused artifact, delete it safely:
  Remove-Item "C:\...\DATA\YourDB_log.ldf"

Step 3: Adjust the Database Creation/Restore Script

  • If using CREATE DATABASE or ALTER DATABASE ... ADD LOG FILE, update the FILENAME parameter to point to a unique file name (e.g., YourDB_log2.ldf) to avoid future collisions.
  • For restore operations, use the WITH MOVE clause to explicitly redirect the log file to a new name/location:
  RESTORE DATABASE [YourDB]
  FROM DISK = 'C:\Backup\YourDB.bak'
  WITH MOVE 'YourDB_log' TO 'C:\...\DATA\YourDB_log_new.ldf', REPLACE

Step 4: Restart the SQL Server Service

  • Restart the service after the conflicting file has been removed/renamed:
  net start MSSQLSERVER
  • Re-run the original CREATE DATABASE, ALTER DATABASE, or RESTORE command that triggered Error 5025.

Alternative or Verification Steps

  • Verify the fix by checking SQL Server Error Log or the SSMS Activity Monitor to confirm the database or log file was created successfully without further 5025 errors.
  • If the issue persists, check NTFS permissions on the DATA folder to ensure the SQL Server service account has Full Control, as a locked or permission-restricted file can sometimes present similarly to this error.

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

Troubleshooting Guide: SQL Server Error 5024 — “No Entry Found for the Primary Log File in sysfiles1”

Why This Error Happens

This error occurs when the metadata in the database’s primary file header (specifically the sysfiles1 entry) is corrupted, missing, or cannot locate the associated transaction log (LDF) file during database attach or recovery. It is commonly triggered by an unclean shutdown, a damaged MDF header, or attempting to attach a database using a log file that does not match the database ID stored in the primary data file. In SQL Server 2025 running on Windows Server 2025, this can also surface if the log file path was altered externally or the file was renamed while the SQL Server service account lacked the proper NTFS permissions to validate it.

Step-by-Step Resolution Guide

Step 1: Verify File Paths and Permissions

  • Confirm the physical .mdf and .ldf files exist in their expected directories (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).
  • Check that the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read/Write NTFS permissions on both files.
  • Right-click the LDF file → Properties → Security → confirm the service account is listed.

Step 2: Attempt Database Attach Using T-SQL with Rebuild Option

  • Open SQL Server Management Studio (SSMS) and connect via an account with sysadmin privileges.
  • Run the following command to force SQL Server to rebuild the log:
CREATE DATABASE YourDatabaseName
ON (FILENAME = 'C:\Data\YourDatabaseName.mdf')
FOR ATTACH_REBUILD_LOG;
  • If the above fails, try setting the database to EMERGENCY mode first:
ALTER DATABASE YourDatabaseName SET EMERGENCY;
ALTER DATABASE YourDatabaseName SET SINGLE_USER;
DBCC CHECKDB (YourDatabaseName, REPAIR_ALLOW_DATA_LOSS);

Step 3: Check for Detached or Orphaned Log Files

  • If a stray or outdated .ldf exists in the directory from a previous backup/restore operation, remove or rename it before re-attaching.
  • Ensure no other process (e.g., antivirus or backup agent) has a file lock on the LDF file via Resource Monitor (resmon.exe).

Step 4: Restore From a Known Good Backup

  • If rebuilding the log fails, the safest route is restoring the last full backup plus any available transaction log backups:
RESTORE DATABASE YourDatabaseName
FROM DISK = 'C:\Backups\YourDatabaseName.bak'
WITH NORECOVERY;
  • Apply any subsequent log backups using WITH RECOVERY on the final restore step.

Step 5: Rebuild the Master Database (If System DB is Affected)

  • If this error applies to a system database (e.g., master), boot SQL Server in single-user mode using sqlservr.exe -m from an elevated Command Prompt.
  • Run setup.exe /ACTION=REBUILDDATABASE from the SQL Server 2025 installation media to reconstruct system databases if master itself is corrupted.

Alternative or Verification Steps

  • After attaching or restoring, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm there is no further corruption.
  • If ATTACH_REBUILD_LOG continues to fail, use the spattachdb legacy method as a fallback, or engage a third-party MDF recovery tool only as a last resort when no valid backup exists.

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

Troubleshooting Guide: SQL Server Error 5023 — “The database must be suspect or in emergency mode to rebuild the log”

Why This Error Happens

This error occurs because the ALTER DATABASE ... REBUILD LOG command is a last-resort recovery operation that SQL Server restricts to databases already flagged as SUSPECT or placed into EMERGENCY mode. If the database is currently online, in RESTORING state, or in a normal user state, SQL Server blocks the rebuild to prevent accidental data loss on a database that might still be recoverable through standard means. Essentially, the engine is enforcing a safety gate — it assumes you haven’t exhausted safer recovery options (like restoring from backup) yet.

Step-by-Step Resolution Guide

Step 1: Verify the Current Database State

  • Open SQL Server Management Studio (SSMS) or a query window connected via sqlcmd.
  • Run the following query to check the current status:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the state_desc shows ONLINE, RESTORING, or something other than SUSPECT/EMERGENCY.

Step 2: Force the Database into EMERGENCY Mode

  • This step is mandatory before rebuilding the log; it tells SQL Server you accept the risk of data loss.
  • Execute the following in a query window with sysadmin privileges:
  ALTER DATABASE YourDatabaseName SET EMERGENCY;
  • If the command hangs or fails, ensure no active connections are using the database (check sys.dm_exec_sessions).

Step 3: Set the Database to Single-User Mode

  • SQL Server requires exclusive access to perform log rebuilds safely.
  • Run:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • This kills other sessions and locks the database for your maintenance session only.

Step 4: Rebuild the Transaction Log

  • With the database now in EMERGENCY and SINGLE_USER mode, execute:
  ALTER DATABASE YourDatabaseName REBUILD LOG ON (NAME = YourDatabaseName_Log, FILENAME = 'D:\SQLData\YourDatabaseName_log.ldf');
  • Ensure the FILENAME path matches your actual data directory (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ on Windows Server 2025 default installs).
  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; immediately afterward to assess remaining corruption.

Step 5: Return the Database to Multi-User Mode

  • Once the rebuild completes and DBCC CHECKDB results are reviewed, restore normal access:
  ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Monitor the SQL Server Error Log (Management > SQL Server Logs in SSMS) for any residual warnings.

Alternative or Verification Steps

  • Verify the fix: Re-run SELECT name, state_desc FROM sys.databases to confirm the database shows ONLINE, then test application connectivity and run a full DBCC CHECKDB to confirm no remaining corruption.
  • Alternative solution: If the log rebuild results in unacceptable data loss or further corruption, restore the database from the most recent full backup plus transaction log backups instead — this is strongly preferred whenever a verified backup chain exists.

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

Troubleshooting Guide: SQL Server Error 5022 — “Log file ‘%ls’ for this database is already active”

Why This Error Happens

This error occurs when SQL Server attempts to attach, restore, or bring a database online while one of its transaction log files is already marked as active by another process or another instance. This typically happens due to a duplicate database attach attempt, a stale lock left by an improperly shut down instance, or conflicting file paths where two database configurations point to the same physical log file (.ldf). It can also surface after a failed failover in an Always On Availability Group where the log file was not released cleanly before a secondary attempted to mount it.

Step-by-Step Resolution Guide

Step 1: Verify No Duplicate Instance Is Using the Log File

  • Open SQL Server Configuration Manager and check if multiple instances (e.g., default and named instances) are configured to use the same data/log directory.
  • Run sp_helpdb 'YourDatabaseName' to confirm the exact path of the .ldf file currently registered.
  • Check Windows Task Manager or services.msc for duplicate sqlservr.exe processes that may be holding a handle on the file.

Step 2: Release File Locks Using Handle Tools

  • Download and run Handle.exe (Sysinternals) from an elevated PowerShell prompt:
  • handle.exe -a "YourDatabase_log.ldf"
  • Identify the PID holding the lock and confirm whether it belongs to a legitimate SQL Server process or an orphaned one.
  • If it’s an orphaned process (not the active SQL Server service), terminate it safely:
  • taskkill /PID <ProcessID> /F

Step 3: Take the Database Offline and Re-Attach Cleanly

  • In SSMS, right-click the database, select Tasks > Take Offline.
  • If the database is stuck, force detach via T-SQL:
  • EXEC sp_detach_db 'YourDatabaseName', 'true';
  • Re-attach using CREATE DATABASE ... FOR ATTACH with the correct, unique file path:
  • CREATE DATABASE YourDatabaseName ON (FILENAME = 'D:\SQLData\YourDatabase.mdf'), (FILENAME = 'D:\SQLLogs\YourDatabase_log.ldf') FOR ATTACH;

Step 4: Restart the SQL Server Service to Clear Residual Locks

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart SQL Server (MSSQLSERVER) or the named instance service to flush any residual file handles.
  • Confirm the SQL Server Error Log (via sp_readerrorlog) no longer references Error 5022 on restart.

Step 5: Check for Always On / Log Shipping Conflicts

  • If using Always On Availability Groups, verify the log file isn’t simultaneously mounted on a secondary replica.
  • Run SELECT * FROM sys.dm_hadr_database_replica_states; to confirm replica state consistency before re-attaching on the primary.

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; after re-attaching to confirm the database is consistent and the log file is properly bound.
  • If the error persists, restore the database from a known-good backup to a new location with a distinct log file name to bypass any lingering file-lock conflict.

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

Why This Error Happens

Error 5021 is technically a confirmation message, not a true failure state—it fires whenever SQL Server successfully processes a rename operation (database, filegroup, logical file, or schema object) via commands like ALTER DATABASE MODIFY NAME, sp_renamedb, or ALTER DATABASE MODIFY FILEGROUP NAME. The “issue” typically arises because dependent components (connection strings, linked servers, SSIS packages, replication publications, or Availability Group listeners) still reference the old name, causing cascading failures right after this message appears in the log. In Windows Server 2025 environments, this is often triggered by automated DevOps pipelines or PowerShell DSC scripts that rename objects without updating downstream configuration files.

Step-by-Step Resolution Guide

Step 1: Identify the Renamed Object and Timestamp

  • Open SQL Server Error Log via SSMS (Management > SQL Server Logs) or query directly:
    EXEC sp_readerrorlog 0, 1, '5021';
  • Note the exact old and new names captured in the %.*ls placeholder text.
  • Cross-reference the timestamp against your deployment/change-management logs (Azure DevOps, Octopus, or Task Scheduler history on Windows Server 2025).

Step 2: Update Dependent Connection References

  • Check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\ for any .mdf/.ldf physical file naming mismatches versus the new logical name.
  • Run sp_helpdb 'YourDatabaseName'; to confirm the logical/physical name alignment.
  • Update any hardcoded references in SSIS packages, linked server definitions (sp_linkedservers), or web.config/app.config files on application servers.

Step 3: Validate Filegroup and File Consistency

  • If the rename involved a filegroup, run:
    SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Ensure no orphaned filegroup references exist in partition schemes or indexed views using:
    SELECT * FROM sys.filegroups;

Step 4: Refresh Replication or Always On Metadata (If Applicable)

  • If the database participates in Replication or an Availability Group, re-run:
    sp_helpreplicationdb or Get-ClusterResource (PowerShell on Windows Server 2025) to confirm the listener/resource name matches the SQL Server metadata.
  • Restart the SQL Server Agent service if replication jobs fail to pick up the new name:
    Restart-Service -Name SQLSERVERAGENT

Step 5: Restart Dependent Services

  • Restart the SQL Server service (net stop MSSQLSERVER && net start MSSQLSERVER) to flush cached metadata if applications still throw “database not found” errors post-rename.

Alternative or Verification Steps

  • Verify success by querying sys.databases or sys.filegroups to confirm the new name is active and no legacy references remain in sys.sysaltfiles.
  • If connectivity issues persist, as a fallback, revert the name using the inverse ALTER DATABASE MODIFY NAME command and re-apply the rename during a maintenance window with all dependent services stopped beforehand.

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

Troubleshooting Guide: SQL Server Error 5020 – Cannot Remove Primary Data or Log File

Why This Error Happens

Error 5020 occurs because SQL Server 2025 does not allow the removal of the primary data file (.mdf) or the last remaining log file (.ldf) associated with a database, as these files contain critical system catalog information required for the database to function. This error is also commonly triggered when you attempt to shrink or remove a file that still contains active data pages, or when a filegroup still has dependent objects (tables/indexes) pointing to it. Additionally, insufficient permissions on the file structure in Windows Server 2025 can sometimes mask the underlying architectural restriction.

Step-by-Step Resolution Guide

Step 1: Verify the File Role in the Database

  • Run sp_helpfile in SSMS to confirm if the file you are trying to remove is flagged as the Primary file.
  • Check if the file is the only one existing in its specific filegroup; SQL Server requires at least one file per active filegroup.
  • Note the fileid; if fileid = 1, it is the primary file and cannot be dropped under any circumstance.

Step 2: Empty the File Before Removal (For Secondary Files)

  • If the file is a secondary data file (not Primary), you must empty it first using DBCC SHRINKFILE (N'YourLogicalFileName', EMPTYFILE).
  • This command migrates all data from the target file to other files within the same filegroup.
  • Ensure there is enough free space in the remaining files within the filegroup to accept the migrated data.

Step 3: Drop the File Using T-SQL Syntax

  • Once the file is confirmed empty (not Primary), execute the removal command:
  • ALTER DATABASE [YourDBName] REMOVE FILE YourLogicalFileName;
  • Do not attempt to delete the physical .ndf or .ldf file directly from the Windows Server 2025 file explorer (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) before running this command, as this will corrupt the database metadata.

Step 4: Check for Merge Replication or System Locks

  • Verify that the file isn’t locked by a pending transaction or an open replication job.
  • Run sp_who2 to check for active sessions using the database that might be blocking the file release.
  • Restart the SQL Server (MSSQLSERVER) service via the Services.msc console on Windows Server 2025 if a “ghost” lock persists after closing all connections.

Alternative or Verification Steps

  • Verification: After running the REMOVE FILE command, execute sp_helpfile again to confirm the file no longer appears in the result set and check the Windows directory to ensure the physical file has been deleted automatically by the engine.
  • Alternative: If you need to remove the Primary file itself (e.g., to move the database), do not attempt to drop it. Instead, create a new database with the desired file structure and use the Generate Scripts > Data and Schema wizard in SSMS to migrate the objects, followed by dropping the old database entirely.

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

Troubleshooting Guide: SQL Server Error 5019

Why This Error Happens

Error 5019 occurs when SQL Server cannot locate a reference to a specific database file within the sys.master_files system catalog view. This typically happens when a database file was manually deleted, moved, or renamed outside of SQL Server’s control, or when the metadata in the database’s system catalog has become desynchronized from the actual physical files on disk. It can also surface during restore operations, file removal attempts (ALTER DATABASE... REMOVE FILE), or after an improper database detach/reattach sequence where the file path no longer matches what SQL Server expects.

Step-by-Step Resolution Guide

Step 1: Verify the Current File Inventory

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the affected instance.
  • Run the following query to list all known files for the database:
  SELECT name, physical_name, state_desc, file_id 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');
  • Compare the physical_name paths against what actually exists in File Explorer or via PowerShell (Get-ChildItem "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\").

Step 2: Check for Mismatched or Orphaned File References

  • Identify if the file name referenced in the error message (from the %.*ls placeholder) exists in the sys.master_files output from Step 1.
  • If the file is missing entirely, it suggests the file was removed at the OS level without updating SQL Server metadata.
  • If you were attempting an ALTER DATABASE command, double-check the exact logical file name using sp_helpfile 'YourDatabaseName' rather than assuming the physical file name.

Step 3: Correct the Metadata or Restore the File

  • If the physical file still exists but SQL Server lost track of it, bring the database offline and back online to force a metadata refresh:
  ALTER DATABASE YourDatabaseName SET OFFLINE;
  ALTER DATABASE YourDatabaseName SET ONLINE;
  • If the file was genuinely deleted, restore it from the most recent full backup using RESTORE DATABASE... WITH FILE, or restore just the specific file/filegroup if using a multi-file architecture.
  • For orphaned metadata entries that persist despite the file being gone, use ALTER DATABASE YourDatabaseName REMOVE FILE LogicalFileName to clean up the reference once you’re certain it’s no longer needed.

Step 4: Run Consistency Checks

  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm there are no deeper corruption issues tied to the missing file.
  • Review the SQL Server error log (Get-Content "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG") for any related I/O or file-handling warnings leading up to the 5019 error.

Alternative or Verification Steps

  • Re-run the original query or command that triggered Error 5019 — if it completes without throwing the file lookup error, the metadata is now synced correctly.
  • If the issue persists after these steps, consider restoring the entire database to a point-in-time backup taken before the file discrepancy occurred, especially in cases involving manual file system intervention.

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

Why This Error Happens

This message appears after executing an ALTER DATABASE ... MODIFY FILE statement to change the physical path of a database file in sys.master_files. SQL Server 2025 updates the system catalog immediately, but the actual file move/rename on disk is not performed automatically — the engine simply records the new path and waits for the next database restart or SQL Server service restart to use it. If the physical file isn’t manually relocated to the new path before that restart, or if the service account lacks permissions on the new directory, the database will fail to come back online.

Step-by-Step Resolution Guide

Step 1: Confirm the Catalog Change Was Intentional

  • Run the following to see what SQL Server now expects as the file path:
SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Compare the physical_name column against the actual location of the .mdf/.ndf/.ldf file on disk.
  • If the path shown doesn’t match reality, you know the catalog update hasn’t been matched by a physical file move yet.

Step 2: Take the Database Offline and Move the Physical File

  • In SQL Server Management Studio (SSMS) or via T-SQL, set the database offline:
ALTER DATABASE [YourDatabaseName] SET OFFLINE;
  • Manually move/copy the file (using File Explorer or Move-Item in PowerShell) from its old location to the new path exactly as recorded in sys.master_files.
  • Example PowerShell command:
Move-Item "D:\OldPath\YourDB.mdf" "E:\NewPath\YourDB.mdf"

Step 3: Grant Correct NTFS Permissions on the New Path

  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER or a custom domain service account) has Full Control on the new folder.
  • Use icacls to verify/grant permissions:
icacls "E:\NewPath" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)F"
  • Without this, SQL Server 2025 will throw an access-denied error when trying to reopen the file at startup.

Step 4: Bring the Database Back Online

  • Set the database online again:
ALTER DATABASE [YourDatabaseName] SET ONLINE;
  • Monitor the SQL Server Error Log (via SSMS > Management > SQL Server Logs, or xp_readerrorlog) to confirm the file was found and mounted correctly at the new path.

Step 5: Restart the SQL Server Service (If Needed)

  • If the database still won’t come online, restart the SQL Server service via SQL Server Configuration Manager or:
Restart-Service -Name 'MSSQLSERVER'
  • This forces SQL Server to fully re-read sys.master_files and re-attach using the new physical path.

Alternative or Verification Steps

  • Verify success by querying sys.master_files again and confirming the state_desc column shows ONLINE for all files tied to the database.
  • If the file move was skipped or done incorrectly, you can revert the catalog entry back to the original path (while the DB is offline) using another ALTER DATABASE ... MODIFY FILE command pointing to the old, still-valid location, then retry the move process carefully.

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

Troubleshooting Guide: Error 5017 – AUTOGROW Property Cannot Be Modified on FILESTREAM or MEMORYOPTIMIZEDDATA Filegroup

Why This Error Happens

Error 5017 occurs because SQL Server does not support changing the AUTOGROW_ALL_FILES or AUTOGROW_SINGLE_FILE property on filegroups marked as FILESTREAM or MEMORY_OPTIMIZED_DATA. These specialized filegroups manage file growth internally using container-based storage semantics rather than traditional data file autogrow logic. The ALTER DATABASE statement attempting this modification is syntactically valid for regular filegroups but is explicitly blocked by the SQL Server engine for these two filegroup types, regardless of permissions or server configuration.

Step-by-Step Resolution Guide

Step 1: Identify the Filegroup Type Causing the Conflict

  • Run the following query to confirm the filegroup’s type before attempting any ALTER operation:
  • SELECT name, type_desc, is_autogrow_all_files FROM sys.filegroups;
  • Look for FD (FILESTREAM Data) or FX (Memory-Optimized Data) in the type_desc column.
  • Confirm that the filegroup referenced in your failed ALTER DATABASE ... MODIFY FILEGROUP command matches one of these types.

Step 2: Remove the Unsupported ALTER Statement from Scripts

  • Edit any deployment or migration scripts (e.g., DACPAC, SSDT projects, or manual T-SQL scripts) that include a line similar to:
  • ALTER DATABASE [YourDB] MODIFY FILEGROUP [FileStreamGroup] AUTOGROW_ALL_FILES;
  • Delete or comment out this line specifically for filegroups identified in Step 1.
  • Save the script and re-run deployment to confirm the error no longer triggers during execution.

Step 3: Apply AUTOGROW Settings Only to Eligible Filegroups

  • If your goal was to standardize autogrow behavior across the database, apply AUTOGROW_ALL_FILES only to ROWS (standard data) filegroups.
  • Example corrected command:
  • ALTER DATABASE [YourDB] MODIFY FILEGROUP [PRIMARY] AUTOGROW_ALL_FILES;
  • Leave FILESTREAM and MEMORYOPTIMIZEDDATA filegroups unmanaged by this property, as SQL Server automatically handles their growth via the underlying file system.

Step 4: Validate File Growth Behavior Manually (If Required)

  • For FILESTREAM filegroups, growth is governed by NTFS volume space on Windows Server 2025 rather than SQL Server’s autogrow engine.
  • Check available disk space using File Explorer or Get-PSDrive in PowerShell to ensure the underlying volume has sufficient capacity.
  • For MEMORYOPTIMIZEDDATA filegroups, monitor checkpoint file pair (CFP) growth via sys.dm_db_xtp_checkpoint_files instead of relying on autogrow settings.

Alternative or Verification Steps

  • Re-run SELECT name, type_desc, is_autogrow_all_files FROM sys.filegroups; after deployment to confirm only ROWS type filegroups show is_autogrow_all_files = 1.
  • If the script must remain generic across multiple databases, wrap the ALTER DATABASE statement in a conditional check that filters out FD and FX filegroup types using dynamic SQL before execution.

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

Troubleshooting Guide: SQL Server Error 5016 — Cannot Change the Name of the System Database

Why This Error Happens

Error 5016 occurs because SQL Server explicitly blocks rename operations on system databases (master, model, msdb, tempdb) to protect core engine functionality and internal references that depend on fixed system database names. This is a hard-coded restriction in the SQL Server engine, not a permissions or configuration issue, so no amount of elevated access will bypass it. The error typically surfaces when an administrator attempts to run ALTER DATABASE ... MODIFY NAME or sp_renamedb against one of these protected databases, often during a scripted migration or naming-standardization task.

Step-by-Step Resolution Guide

Step 1: Confirm Which Database Triggered the Error

  • Review the exact error message text, which includes the database name in place of %.*ls (e.g., “Cannot change the name of the system database ‘master'”).
  • Run the following in SQL Server Management Studio (SSMS) or sqlcmd to confirm its system status:
  SELECT name, database_id, is_distributor 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • System databases always have database_id values of 1 through 4 (master, tempdb, model, msdb).

Step 2: Abandon the Rename Attempt on System Databases

  • Do not attempt to force the rename using sp_renamedb, direct metadata edits, or single-user mode tricks — this can corrupt the instance.
  • Cancel any deployment scripts or DevOps pipelines (e.g., Azure DevOps, Flyway, Liquibase) that are programmatically trying to rename master, model, msdb, or tempdb.
  • Check the script or tool logs located typically at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the triggering statement.

Step 3: Redirect the Intended Change to a User Database

  • If the goal was to rename a custom/user database that was mistakenly flagged, verify you are connected to the correct SQL Server instance and not accidentally targeting master due to a connection string default.
  • Run the rename against the correct user database instead:
  ALTER DATABASE [OldUserDbName] MODIFY NAME = [NewUserDbName];
  • Ensure no active connections exist on the target database before renaming by setting it to single-user mode first:
  ALTER DATABASE [OldUserDbName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Step 4: If tempdb Logical File Names Need Changing (Common Workaround)

  • Since tempdb itself cannot be renamed, but its physical/logical file names sometimes need adjustment, use ALTER DATABASE on the files instead:
  ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, FILENAME = 'D:\SQLData\tempdb.mdf');
  ALTER DATABASE tempdb MODIFY FILE (NAME = templog, FILENAME = 'D:\SQLData\templog.ldf');
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell for the file changes to take effect.

Alternative or Verification Steps

  • Verify success by querying sys.databases again to confirm the new name is applied only to the intended user database and that master, model, msdb, and tempdb remain unchanged.
  • If a true “fresh” system database is required (e.g., for disaster recovery rebuild), use the setup.exe /ACTION=REBUILDDATABASE command-line rebuild process instead of attempting an in-place rename.

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

Troubleshooting Guide: SQL Server Error 5015 — “ALTER DATABASE failed. The total size specified must be 1 MB or greater.”

Why This Error Happens

This error occurs when an ALTER DATABASE statement attempts to resize a data or log file (via MODIFY FILE with a SIZE parameter) to a value smaller than the required 1 MB minimum, often due to a miscalculated value passed in KB instead of MB. It can also occur when automated scripts or maintenance jobs reference a stale or incorrect file size variable, or when a file’s FILEGROWTH and SIZE settings conflict after a prior shrink operation. Additionally, corrupted or improperly restored database metadata in sys.master_files can cause SQL Server to misread the current file size, triggering this validation error during the next resize attempt.

Step-by-Step Resolution Guide

Step 1: Review the Exact ALTER DATABASE Statement

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact T-SQL script that triggered the error.
  • Check the SIZE = clause — ensure the value is specified in MB (e.g., SIZE = 50MB, not SIZE = 50KB).
  • Example of a problematic statement:
  ALTER DATABASE SalesDB MODIFY FILE (NAME = SalesDB_log, SIZE = 512KB);
  • Correct it to:
  ALTER DATABASE SalesDB MODIFY FILE (NAME = SalesDB_log, SIZE = 1MB);

Step 2: Check Current File Sizes in sys.master_files

  • Run the following query to inspect current file sizes and growth settings:
  SELECT name, size, growth, is_percent_growth 
  FROM sys.master_files 
  WHERE database_id = DB_ID('SalesDB');
  • Confirm the size column (in 8 KB pages) correctly reflects the actual file size on disk at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • If values appear mismatched or corrupted, note the discrepancy for the next step.

Step 3: Correct the ALTER DATABASE Command with Valid Minimums

  • Re-issue the command ensuring the new size is strictly greater than or equal to 1 MB and greater than the current committed size if growing the file:
  ALTER DATABASE SalesDB 
  MODIFY FILE (NAME = SalesDB_log, SIZE = 5MB, FILEGROWTH = 10%);
  • If resizing a log file after a shrink operation, first run DBCC SQLPERF(LOGSPACE) to confirm actual log usage before setting a new size.

Step 4: Validate Disk Space and File Permissions

  • Confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has write permissions on the target data/log directory.
  • Check available disk space on the volume hosting the .mdf/.ldf files using File Explorer or Get-PSDrive in PowerShell.
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER if permission changes were made.

Alternative or Verification Steps

  • After applying the corrected ALTER DATABASE statement, re-run SELECT name, size FROM sys.master_files WHERE database_id = DB_ID('SalesDB'); to confirm the new size is reflected and no errors are returned.
  • If the error persists despite correct syntax, restore the database from a known-good backup to a test instance and compare file metadata, as this may indicate underlying corruption in the database’s file structure.

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

Troubleshooting Guide: SQL Server Error 5014

Why This Error Happens

Error 5014 occurs when SQL Server attempts to reference a system object, filegroup, log file, or metadata entry (%S_MSG '%.*ls') that does not exist within the specified database context. This is typically caused by a mismatch between the database’s system catalog and its actual physical structure, often resulting from an incomplete restore, a corrupted system table, orphaned metadata left behind after a failed schema change, or a database that was partially detached/reattached without all associated files. In some cases, this also surfaces when a script or application references a database object using a stale cached plan after the object was dropped or renamed.

Step-by-Step Resolution Guide

Step 1: Identify the Missing Object and Database Context

  • Open the SQL Server Error Log via SSMS (Management > SQL Server Logs) or check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • Note the exact database name and the object identifier mentioned in the error message substitution variables.
  • Run the following query to cross-check system catalog consistency:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 2: Validate Database and File Integrity

  • Confirm all data and log files exist in their expected paths (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).
  • Check for orphaned filegroups using:
  SELECT name, physical_name, state_desc FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • If files are missing or marked as RESTORING / OFFLINE, restore the full backup chain (Full + Differential + Log) to a consistent state.

Step 3: Repair or Rebuild System Metadata

  • If DBCC CHECKDB reports catalog corruption, attempt a targeted repair:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  DBCC CHECKDB ('YourDatabaseName', REPAIR_REBUILD);
  ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Avoid REPAIR_ALLOW_DATA_LOSS unless no clean backup is available, as it may purge the referenced object entirely.

Step 4: Clear Stale Execution Plans and Cached Metadata

  • Flush the procedure cache to eliminate references to dropped objects:
  DBCC FREEPROCCACHE;
  DBCC DROPCLEANBUFFERS;
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on Windows Server 2025/Windows 11 to fully reset in-memory metadata caches.

Alternative or Verification Steps

  • Re-run the original query or application call that triggered Error 5014 to confirm the object resolves correctly without exceptions.
  • If the error persists, restore the database from the last known-good backup to a new database name and compare sys.objects and sys.filegroups output against the production database to pinpoint the exact discrepancy.

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

Why This Error Happens

Error 5013 occurs because SQL Server 2025 explicitly blocks ALTER DATABASE ADD FILE operations against the master and model system databases to protect core engine stability. This is typically triggered when a maintenance script, migration tool, or automated job mistakenly targets master/model instead of a user database, or when a template-based deployment process assumes model can be extended with new filegroups. In rare cases, this also surfaces if a corrupted or misconfigured startup script attempts to replicate file structures from a user database onto model during instance initialization.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the ALTER DATABASE Command

  • Check SQL Server Agent Job history and any CI/CD deployment scripts (Azure DevOps, Flyway, Liquibase, etc.) for ALTER DATABASE master or ALTER DATABASE model statements.
  • Run the following query to review recent DDL attempts via the default trace:
SELECT * FROM sys.fn_trace_gettable(
(SELECT TOP 1 path FROM sys.traces WHERE is_default = 1), DEFAULT)
WHERE EventClass = 164;
  • Confirm whether the target database name was hardcoded incorrectly in a script or configuration file.

Step 2: Correct the Script or Deployment Template

  • Open the offending .sql file or deployment template (commonly found under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Install\ or your CI pipeline’s artifact folder).
  • Replace references to master or model with the correct target database name (e.g., USE [YourAppDB] before the ALTER DATABASE block).
  • If the script is meant to create a template database, clone model first using CREATE DATABASE NewDB instead of modifying model directly.

Step 3: Validate System Database Integrity

  • Run DBCC CHECKDB (master) WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption as the underlying trigger.
  • If model was unintentionally altered and is now inconsistent, restore it from the default template backup located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\Templates\model.mdf (requires service restart in single-user mode via sqlservr.exe -m).

Step 4: Restart SQL Server Service and Re-test

  • Restart the SQL Server (MSSQLSERVER) service from services.msc or run:
Restart-Service -Name 'MSSQLSERVER' -Force
  • Re-run your original deployment script against the correctly specified user database to confirm Error 5013 no longer appears.

Alternative or Verification Steps

  • Verify the fix by executing sp_helpdb against master and model to confirm no pending file additions remain queued or in a failed state.
  • If the error persists despite correcting the script, check for third-party monitoring/backup agents (e.g., SCOM, Veeam SQL plugins) that may be issuing automated ALTER DATABASE calls against system databases during health-check routines.

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

Troubleshooting Guide: SQL Server Error 5012 — Cannot Change Primary Filegroup Name

Why This Error Happens

Error 5012 occurs because SQL Server 2025 does not allow the name “PRIMARY” to be reassigned or removed from the primary filegroup, as this filegroup is a reserved system object tied to core database metadata. This typically happens when a user attempts to run ALTER DATABASE ... MODIFY FILEGROUP against the primary filegroup with a new name, or when a migration/deployment script written for a non-primary filegroup is mistakenly executed against the primary one. In some cases, this also surfaces when automated deployment tools or schema comparison utilities (e.g., in SSDT or third-party DevOps pipelines) generate ALTER scripts that incorrectly target the primary filegroup during a rename operation.

Step-by-Step Resolution Guide

Step 1: Confirm the Filegroup Is Actually the Primary Filegroup

  • Run the following query to verify filegroup properties:
  SELECT name, is_default, type_desc 
  FROM sys.filegroups;
  • Look for the row where name = 'PRIMARY' — this filegroup cannot be renamed under any circumstance.
  • If your intended target was a secondary filegroup, correct the filegroup name in your script before re-running it.

Step 2: Review and Correct the ALTER DATABASE Script

  • Open the deployment or migration script that triggered the error (commonly found in .sql files under your project’s /Scripts/Deployment/ folder or in SSDT-generated publish scripts).
  • Check for a line similar to:
  ALTER DATABASE [YourDB] MODIFY FILEGROUP [PRIMARY] NAME = [NewName];
  • Remove or comment out this line, since renaming PRIMARY is not a supported operation in SQL Server 2025.
  • If the goal was to rename a different filegroup, replace [PRIMARY] with the correct filegroup name (e.g., [FG_DATA_02]).

Step 3: Audit Automated Deployment Tools and Schema Compare Settings

  • If using SSDT, Azure Data Studio Schema Compare, or a CI/CD pipeline (e.g., Azure DevOps, GitHub Actions), inspect the generated DACPAC or publish profile under .publish.xml.
  • Disable any “filegroup synchronization” or “ignore filegroup” options that may be forcing a rename attempt on PRIMARY.
  • Re-generate the deployment script and manually validate it before executing against production.

Step 4: Apply the Correct Workaround if Renaming Is Truly Required

  • If your intent was to logically “rename” the primary filegroup, this is not possible — instead, create a new filegroup with the desired name:
  ALTER DATABASE [YourDB] ADD FILEGROUP [NewPrimaryName];
  • Move data files to the new filegroup using ALTER DATABASE ... MODIFY FILE or by rebuilding indexes with the ON [NewPrimaryName] clause.
  • Update application connection strings or scripts that assumed the primary filegroup had a custom name.

Alternative or Verification Steps

  • After correcting the script, re-run ALTER DATABASE and confirm no errors are returned; then verify with SELECT name FROM sys.filegroups WHERE is_default = 1; to ensure PRIMARY remains unchanged.
  • If third-party tools continue generating invalid rename scripts, manually edit the generated .sql deployment file before execution, or exclude filegroup operations entirely from the schema compare/deploy process.

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

Troubleshooting Guide: SQL Server Error 5011 – “User Does Not Have Permission to Alter Database”

Why This Error Happens

This error occurs when the login attempting to execute an ALTER DATABASE statement lacks the required ALTER ANY DATABASE server-level permission or is not a member of the dbcreator/sysadmin fixed server roles. It can also happen if the database owner (DB Owner) mapping is broken—often seen after a database migration or restore where the Windows SID or SQL login SID no longer matches the owner recorded in sys.databases. Additionally, on Windows Server 2025 and Windows 11 hosts, strict User Account Control (UAC) and Credential Guard policies can silently downgrade an Administrator’s token, preventing inherited sysadmin rights from applying correctly within SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the Current Login’s Server Role Membership

  • Open SQL Server Management Studio (SSMS) and connect using an account known to have sysadmin rights (or connect locally via sqlcmd -S localhost -E).
  • Run the following query to check role membership for the affected login:
  SELECT sp.name AS LoginName, sr.name AS RoleName
  FROM sys.server_role_members srm
  JOIN sys.server_principals sp ON srm.member_principal_id = sp.principal_id
  JOIN sys.server_principals sr ON srm.role_principal_id = sr.principal_id
  WHERE sp.name = 'YOUR_LOGIN_HERE';
  • If the login is missing from sysadmin or dbcreator, proceed to Step 2.

Step 2: Grant the Required Server-Level Permission

  • Rather than granting full sysadmin, apply the least-privilege fix by granting ALTER ANY DATABASE directly:
  USE master;
  GRANT ALTER ANY DATABASE TO [DOMAIN\YourUser];
  • If the user needs to manage only a specific database, instead add them as db_owner on that database:
  USE YourDatabaseName;
  ALTER ROLE db_owner ADD MEMBER [DOMAIN\YourUser];

Step 3: Repair Orphaned Database Ownership

  • Check if the database owner SID is invalid or orphaned, which commonly triggers Error 5011 after a restore:
  SELECT name, suser_sname(owner_sid) AS OwnerName
  FROM sys.databases
  WHERE name = 'YourDatabaseName';
  • If OwnerName returns NULL, reassign ownership to a valid sysadmin login:
  ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa;

Step 4: Check Windows-Level UAC and Token Elevation

  • On Windows Server 2025 / Windows 11, open secpol.msc and navigate to Local Policies > Security Options.
  • Confirm “User Account Control: Run all administrators in Admin Approval Mode” is not blocking token elevation for the SQL Server service account.
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after any policy change to force token refresh.

Step 5: Restart SQL Server Service and Re-Test

  • Open PowerShell as Administrator and restart the instance:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Reconnect via SSMS and re-run the original ALTER DATABASE command to confirm the permission error is cleared.

Alternative or Verification Steps

  • Verify the fix by running SELECT IS_SRVROLEMEMBER('sysadmin') or EXECUTE AS LOGIN = 'DOMAIN\YourUser'; SELECT USER_NAME(); to confirm correct role assumption before retrying the ALTER DATABASE statement.
  • If permissions still fail, use the Dedicated Admin Connection (DAC) via sqlcmd -S admin:localhost -E to bypass normal authentication checks and directly correct role memberships at the server level.

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

Troubleshooting Guide: SQL Server Error 5010 – “Log File Name Cannot Be Generated from a Raw Device”

Why This Error Happens

This error occurs when a database attach, restore, or creation operation relies on legacy raw device naming conventions, which SQL Server 2025 no longer supports for automatically generating log file names. SQL Server requires an explicit, fully qualified file name and path for the transaction log (LDF) because it cannot infer one from a raw partition or unformatted device reference. This typically happens during CREATE DATABASE, RESTORE DATABASE, or sp_attach_db operations where the original log file path is missing, malformed, or pointing to a deprecated raw device.

Step-by-Step Resolution Guide

Step 1: Identify the Operation Triggering the Error

  • Check whether the error occurs during CREATE DATABASE, RESTORE DATABASE, ALTER DATABASE, or sp_attach_db.
  • Review the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact command context surrounding Error 5010.
  • Confirm if the command omitted a FOR ATTACH clause with explicit file paths or used a legacy raw partition reference (e.g., \\.\PhysicalDriveX).

Step 2: Explicitly Specify the Log File Name and Path

  • Rewrite the command to include a MOVE clause (for restores) or explicit FILENAME parameter (for creation/attach) pointing to a valid NTFS path.
  • Example for RESTORE DATABASE:
  RESTORE DATABASE [YourDB]
  FROM DISK = 'D:\Backups\YourDB.bak'
  WITH MOVE 'YourDB_Log' TO 'D:\SQLData\YourDB_Log.ldf',
  MOVE 'YourDB_Data' TO 'D:\SQLData\YourDB_Data.mdf';
  • Example for attaching a database:
  CREATE DATABASE [YourDB] ON
  (FILENAME = 'D:\SQLData\YourDB_Data.mdf'),
  (FILENAME = 'D:\SQLData\YourDB_Log.ldf')
  FOR ATTACH;

Step 3: Validate File System Paths and Permissions

  • Confirm the target directory (e.g., D:\SQLData\) exists and is not on a raw/unformatted volume.
  • Verify the SQL Server service account (check via services.msc on Windows Server 2025) has Read/Write permissions on the folder.
  • Run icacls "D:\SQLData" in an elevated Command Prompt to confirm NT SERVICE\MSSQLSERVER has full control.

Step 4: Remove Legacy Raw Device References

  • If the database was originally created on a raw partition (common in pre-2016 SQL versions), export the data using BCP or generate a new backup from a compatible intermediate server.
  • Re-import the data into a new database explicitly created with standard .mdf/.ldf file paths on formatted NTFS volumes.

Alternative or Verification Steps

  • After applying the fix, run RESTORE VERIFYONLY FROM DISK = 'D:\Backups\YourDB.bak' to confirm the backup integrity and path validity before a full restore.
  • If the issue persists, use RESTORE FILELISTONLY FROM DISK = 'YourBackupPath' to list the original logical file names and ensure your MOVE clause matches them exactly.

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

Troubleshooting Guide: SQL Server Error 5009

Why This Error Happens

Error 5009 occurs when SQL Server attempts to attach, restore, or reference a database but cannot locate one or more of the underlying data (.mdf/.ndf) or log (.ldf) files at their expected file path. This is typically caused by files being moved, renamed, or deleted outside of SQL Server’s control, incorrect file paths specified in a CREATE DATABASE or RESTORE statement, or insufficient NTFS permissions for the SQL Server service account to access the directory. In some cases, the file header may also be corrupted, preventing SQL Server from initializing it even though the file physically exists.

Step-by-Step Resolution Guide

Step 1: Verify the Physical File Paths

  • Open File Explorer or PowerShell on the Windows Server 2025 / Windows 11 host and navigate to the expected data directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Confirm that the exact .mdf, .ndf, and .ldf files referenced in the statement actually exist in that location.
  • Run dir "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\*.mdf" in PowerShell to list all files and cross-check names.

Step 2: Check and Correct File Permissions

  • Right-click the DATA folder, go to Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read, Write, and Modify permissions.
  • If permissions are missing, click Edit, add the service account, and grant Full Control to the folder and its contents.
  • Restart the SQL Server service afterward using net stop MSSQLSERVER followed by net start MSSQLSERVER.

Step 3: Correct the Statement or Reattach the Database

  • If running CREATE DATABASE ... FOR ATTACH or RESTORE DATABASE, ensure the FILENAME parameter in the MOVE clause matches the actual current file path.
  • Example corrected syntax:
  RESTORE DATABASE [SalesDB]
  FROM DISK = 'D:\Backups\SalesDB.bak'
  WITH MOVE 'SalesDB' TO 'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\SalesDB.mdf',
  MOVE 'SalesDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\SalesDB_log.ldf';
  • If files were moved to a new drive, update the path in the statement to reflect the new location rather than the original one.

Step 4: Rule Out File Corruption

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORS once the database is online to check for corruption.
  • If the file header is damaged, restore from the most recent known-good backup instead of attempting to reattach the damaged file.

Alternative or Verification Steps

  • After applying fixes, run SELECT name, physical_name, state_desc FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName'); to confirm all files show a state of ONLINE.
  • If the issue persists, use SQL Server Management Studio’s “Attach Database” dialog, which will visually flag any missing files, allowing you to manually browse to and reselect the correct file paths before confirming the attach operation.

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

Troubleshooting Guide: SQL Server Error 5008 – “This ALTER DATABASE Statement Is Not Supported”

Why This Error Happens

This error occurs when the ALTER DATABASE statement contains a clause, option, or syntax structure that is invalid, deprecated, or not supported in SQL Server 2025, often due to combining incompatible options in a single statement. It can also arise when attempting to modify a database that is part of an Availability Group, is in a restricted state (such as SINGLEUSER or RESTRICTEDUSER), or when the target database is a system database that does not permit the requested configuration change. Additionally, certain ALTER DATABASE options cannot be executed within a user transaction or when combined with other options that have conflicting scope (e.g., mixing file-level and database-level options incorrectly).

Step-by-Step Resolution Guide

Step 1: Review and Isolate the ALTER DATABASE Syntax

  • Open the exact T-SQL statement that triggered Error 5008 in SQL Server Management Studio (SSMS).
  • Check Microsoft’s official documentation for SQL Server 2025 to confirm the clause (e.g., MODIFY FILE, SET, COLLATE) is supported and correctly ordered.
  • Split compound statements into separate ALTER DATABASE commands — SQL Server often rejects multiple unrelated options combined in one call.
  • Example fix: Instead of ALTER DATABASE MyDB SET RECOVERY SIMPLE, SET AUTO_CLOSE OFF;, run them as two distinct statements.

Step 2: Check Database State and Transaction Context

  • Verify the database is not in a restricted state by running:
  • SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the statement is not being executed inside an explicit BEGIN TRANSACTION block, since some ALTER DATABASE options must run outside of user transactions.
  • If the database belongs to an Availability Group, temporarily remove it from the group before applying file or state-level changes.

Step 3: Validate Permissions and Server Configuration

  • Confirm your login has ALTER ANY DATABASE or CONTROL SERVER permissions by running:
  • SELECT * FROM fn_my_permissions(NULL, 'SERVER');
  • Check SQL Server error logs located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for additional context tied to Error 5008.
  • If running in a containerized or Server Core environment on Windows Server 2025, confirm the SQL Server service account has the necessary file system permissions on the target .mdf/.ldf paths.

Step 4: Apply Cumulative Updates and Restart Services

  • Open SQL Server Configuration Manager and verify you are running the latest Cumulative Update (CU) for SQL Server 2025, as syntax parser bugs are occasionally patched in CUs.
  • Restart the SQL Server service via PowerShell:
  • Restart-Service -Name 'MSSQLSERVER' -Force
  • Re-run the corrected ALTER DATABASE statement after the service restarts.

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; to confirm no underlying corruption is interfering with metadata changes, then re-attempt the simplified ALTER DATABASE statement.
  • If the error persists, use the SSMS GUI (Database Properties window) to apply the same configuration change — this generates valid, parser-verified T-SQL you can compare against your original script.

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

Troubleshooting Guide: SQL Server Error 5006

Why This Error Happens

Error 5006 occurs when SQL Server 2025 attempts to acquire an exclusive lock on a database file or resource (such as during a RESTORE, ALTER DATABASE, or file shrink operation) but another process is actively holding a handle to that resource. This is frequently caused by lingering connections, a backup agent, or an antivirus/EDR solution on Windows Server 2025 scanning the .mdf/.ldf files in real-time. It can also happen if a previous SQL Server process did not release the file handle cleanly after a crash or improper shutdown.

Step-by-Step Resolution Guide

Step 1: Identify Active Connections and Locks

  • Open SQL Server Management Studio (SSMS) and run sp_who2 or query sys.dm_exec_sessions to find active sessions connected to the target database.
  • Check for open transactions using DBCC OPENTRAN('YourDatabaseName').
  • If stray sessions are found, terminate them using KILL [session_id].

Step 2: Set Database to Single-User Mode

  • Force the database into single-user mode to strip away any lingering background connections (like reporting services or linked server pings):
  • ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Attempt your original operation (e.g., Restore or File Shrink) immediately after this command succeeds.

Step 3: Check for File-Level Locks (OS Level)

  • On Windows Server 2025, use Resource Monitor (resmon.exe) or Process Explorer to search for the specific .mdf or .ldf file path mentioned in the error message.
  • Identify if a non-SQL process (like Windows Defender, a backup agent, or a search indexer) is holding the handle.
  • Add the SQL Server data directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA) to your antivirus exclusion list.

Step 4: Restart the SQL Server Service

  • If the lock persists despite no visible active sessions, the lock might be a “ghost” handle from the SQL Server Engine itself.
  • Restart the specific instance via Windows Services (services.msc) by finding SQL Server (MSSQLSERVER).
  • Alternatively, use PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force.

Step 5: Revert Database to Multi-User Mode

  • Once the operation (restore/alter) is complete, ensure you return the database to its normal operating state to allow user traffic back in.
  • Run: ALTER DATABASE YourDatabaseName SET MULTI_USER;

Alternative or Verification Steps

  • Verification: Re-run the original command that triggered Error 5006 (e.g., the RESTORE DATABASE script). If it completes without hanging or throwing the exclusive lock error, the fix was successful.
  • Alternative: If the error persists only during automated backups, check the SQL Server Agent Job History to ensure no overlapping jobs are scheduled to run against the same database simultaneously.

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

Troubleshooting Guide: Error 5005 – Invalid Recovery Time Specification in SQL Server 2025

Why This Error Happens

Error 5005 occurs when the recovery interval configuration option in SQL Server is set to a value outside the acceptable range (typically 0 to 2,147,483,647 seconds for the advanced setting, or a much smaller practical range in minutes for the basic setting). This usually happens due to a misconfigured sp_configure command, a corrupted or manually edited configuration value in the system catalog, or an automated deployment script that passed a negative or malformed integer. Since SQL Server validates this value during database recovery or startup, an out-of-bounds entry prevents the Database Engine from calculating checkpoint intervals correctly, triggering this error.

Step-by-Step Resolution Guide

Step 1: Verify the Current Recovery Interval Setting

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the affected instance.
  • Run the following query to inspect the current value:
EXEC sp_configure 'recovery interval (min)';
  • Check if the run_value or config_value is negative, null, or exceeds the maximum threshold (2147483647 for advanced settings).

Step 2: Reset the Recovery Interval to a Valid Default

  • Enable advanced options first, since recovery interval may require elevated configuration visibility:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
  • Set the recovery interval back to the SQL Server default (0, which lets SQL Server auto-manage it):
EXEC sp_configure 'recovery interval (min)', 0;
RECONFIGURE WITH OVERRIDE;
  • If a specific custom value is required by your workload, ensure it does not exceed documented limits (generally 0–32767 minutes depending on build).

Step 3: Restart the SQL Server Service

  • On Windows Server 2025 or Windows 11, open SQL Server Configuration Manager.
  • Navigate to SQL Server Services, right-click the instance (e.g., SQL Server (MSSQLSERVER)), and select Restart.
  • Alternatively, use PowerShell with elevated privileges:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Check for Registry or Startup Parameter Overrides

  • Open regedit and navigate to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLServer\Parameters
  • Confirm no startup trace flags or legacy parameters are forcing a deprecated recovery interval value.
  • Remove any suspicious -T trace flag entries related to recovery timing if present, then restart the service again.

Step 5: Review SQL Server Error Logs for Residual Corruption

  • Locate the error log at:
C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG
  • Search for repeated 5005 entries to confirm the timestamp aligns with your configuration change.
  • If corruption in msdb or master system tables is suspected, run DBCC CHECKDB against master to rule out catalog corruption.

Alternative or Verification Steps

  • Confirm the fix by restarting the SQL Server instance and checking the ERRORLOG for successful recovery messages without Error 5005 reappearing.
  • If the issue persists after resetting via sp_configure, rebuild the master database configuration using setup.exe /ACTION=REBUILDDATABASE (only as a last resort, with a full backup beforehand).

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

Why This Error Happens

Error 5004 occurs when SQL Server cannot acquire the exclusive lock required to modify database-level properties (such as file size, collation, or recovery model) because active user connections or system processes are still bound to the database. This typically happens when the database is being accessed by another session, a replication/mirroring process, or when SQL Server Management Studio itself holds an open connection in the target database context. Until all sessions release their locks, ALTER DATABASE commands requiring single-user or exclusive access will fail.

Step-by-Step Resolution Guide

Step 1: Identify Active Connections Blocking the Database

  • Open a new query window connected to the master database (not the target database).
  • Run SELECT session_id, status, host_name, program_name FROM sys.dm_exec_sessions WHERE database_id = DB_ID('YourDatabaseName'); to list all active sessions.
  • Note any session_id values other than your own; these must be terminated before proceeding.

Step 2: Switch the Database to SINGLE_USER Mode

  • From the master context, run:
    ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • This forcibly disconnects all other sessions and rolls back any open transactions, clearing the lock conflict.
  • If this command also fails with Error 5004, confirm you are not currently using the target database in your active query window — switch to master first.

Step 3: Execute the Original ALTER DATABASE Command

  • Once in SINGLE_USER mode, re-run the intended ALTER DATABASE statement (e.g., changing file growth, collation, or recovery model).
  • Example: ALTER DATABASE YourDatabaseName MODIFY FILE (NAME = 'YourDataFile', SIZE = 500MB);

Step 4: Revert the Database to MULTI_USER Mode

  • Run ALTER DATABASE YourDatabaseName SET MULTI_USER; to restore normal access.
  • Confirm no application connection strings were left pointing to a stale session during the SINGLE_USER window.

Step 5: Check for Service-Level Locks (If Issue Persists)

  • Open Services.msc on Windows Server 2025 / Windows 11 and verify no SQL Server Agent jobs or SSIS packages are actively querying the database.
  • Restart the SQL Server (MSSQLSERVER) service only as a last resort, since this disconnects all users system-wide.

Alternative or Verification Steps

  • Verify the fix by running SELECT DATABASEPROPERTYEX('YourDatabaseName', 'UserAccess'); — it should return MULTI_USER after Step 4 completes successfully.
  • If SINGLE_USER mode still fails to apply, check SQL Server Configuration Manager for lingering linked server connections or replication subscribers still bound to the database, and disable them temporarily before retrying.

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

Troubleshooting Guide: SQL Server Error 5003 – Database Mirroring Cannot Be Enabled with Offline Files

Why This Error Happens

Error 5003 occurs when SQL Server detects that one or more files belonging to the database are in an OFFLINE state, which prevents the database from meeting the prerequisites for mirroring setup. Database mirroring requires every data and log file associated with the database to be fully online and accessible, since the mirroring process needs to read the complete file structure to establish the initial synchronization with the mirror instance. This typically happens after a restore operation leaves secondary filegroups offline, a disk/storage failure takes a file offline, or a file was manually set to OFFLINE and never brought back online.

Step-by-Step Resolution Guide

Step 1: Identify the Offline Files

  • Run the following query to check file states for the target database:
  SELECT name, physical_name, state_desc 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');
  • Look for any rows where state_desc returns OFFLINE or RESTORING instead of ONLINE.
  • Note the logical file name and physical path for each offline file.

Step 2: Verify Underlying Storage and File Accessibility

  • Confirm the physical disk or volume hosting the file (e.g., D:\SQLData\YourDB_Secondary.ndf) is mounted and accessible in Windows Server 2025 / Windows 11.
  • Check Windows Disk Management (diskmgmt.msc) to ensure the volume isn’t offline or in a degraded state.
  • If the file was moved or deleted, restore it from the last known good backup to its original path.

Step 3: Bring the File Back Online

  • Execute the following T-SQL command to attempt to bring the file online:
  ALTER DATABASE YourDatabaseName 
  MODIFY FILE (NAME = YourLogicalFileName, OFFLINE = OFF);
  • If the file was offline due to corruption, instead run a targeted file restore:
  RESTORE DATABASE YourDatabaseName 
  FILE = 'YourLogicalFileName' 
  FROM DISK = 'C:\Backups\YourDB.bak' 
  WITH NORECOVERY;
  • Follow up with a transaction log restore and WITH RECOVERY to finalize the file state.

Step 4: Re-Attempt Database Mirroring Setup

  • Open SQL Server Management Studio (SSMS) and navigate to Database Properties > Mirroring.
  • Alternatively, re-run the mirroring T-SQL command:
  ALTER DATABASE YourDatabaseName SET PARTNER = 'TCP://MirrorServer:5022';
  • Confirm no error 5003 is thrown during the configuration process.

Alternative or Verification Steps

  • Re-run the sys.master_files query from Step 1 to confirm all files now show state_desc = ONLINE before retrying mirroring.
  • If files cannot be recovered due to permanent storage loss, consider removing the affected secondary filegroup (if non-critical) or restoring the entire database from a full backup to a healthy storage location before re-enabling mirroring.

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

Troubleshooting Guide: SQL Server Error 5002 – Database Does Not Exist

Why This Error Happens

Error 5002 occurs when SQL Server cannot locate the specified database within the sys.databases system catalog, typically because the database name was misspelled, the database was detached or dropped, or the connection context is pointing to the wrong SQL Server instance. This can also happen if the database exists but is in a suspect, offline, or restoring state, which can cause it to momentarily disappear from accessible catalog views. In some cases, case-sensitivity settings on the server collation cause a correctly-spelled name to fail validation.

Step-by-Step Resolution Guide

Step 1: Verify the Database Name and Instance Context

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the correct instance (e.g., SERVERNAME\INSTANCENAME).
  • Run the query: SELECT name, state_desc FROM sys.databases; to get the exact, case-sensitive name and current status.
  • Check your connection string or application config file (e.g., web.config or appsettings.json) for typos in the Initial Catalog or Database parameter.

Step 2: Check Database State and File Integrity

  • If the database appears in the list but shows SUSPECT or RECOVERY_PENDING, navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ to confirm the .mdf and .ldf files exist and are not zero-byte.
  • Run DBCC CHECKDB('YourDatabaseName') to check for corruption if the database is online but inaccessible.
  • If the files are missing, restore the latest backup using RESTORE DATABASE [YourDB] FROM DISK = 'C:\Backups\YourDB.bak' WITH RECOVERY;.

Step 3: Re-attach or Restore the Database

  • If the database was accidentally detached, use CREATE DATABASE [YourDB] ON (FILENAME = 'C:\Data\YourDB.mdf') FOR ATTACH; to bring it back online.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read/Write permissions on the folder via Windows 11/Server 2025 File Explorer security tab.
  • Restart the SQL Server service using services.msc or net start MSSQLSERVER to refresh the metadata cache.

Alternative or Verification Steps

  • Verify: Re-run the original query or application request; if successful, check sys.databases again to ensure the state_desc column reads ONLINE.
  • Alternative: If the database is permanently lost, restore the full backup chain (Full + Differential + Log) onto a new instance to recover the data and re-point the application connection string.

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

Why This Error Happens

Error 5001 with the message “User must be in the master database” typically occurs when a user attempts to execute a system-level command—such as creating or restoring a database, modifying a filegroup, or running certain DBCC operations—while their current session context is pointed to a different database. SQL Server 2025 enforces strict context validation for operations that touch system catalogs, and these commands will fail immediately if the active database context is not master. This is often triggered by connection strings, stored procedures, or scripts that do not explicitly set the database context before executing administrative T-SQL statements.

Step-by-Step Resolution Guide

Step 1: Verify Your Current Database Context

  • Run SELECT DB_NAME(); in your query window to confirm which database is currently active.
  • If the result is not master, this confirms the root cause of Error 5001.
  • Check the dropdown in SQL Server Management Studio (SSMS) toolbar, as it may be pointing to tempdb, model, or a user database.

Step 2: Explicitly Switch Context to Master

  • Add USE master; as the first line in your script before running the command that triggered the error.
  • Example:
  USE master;
  GO
  CREATE DATABASE MyNewDatabase;
  • If using a connection string (ADO.NET, ODBC, or JDBC), ensure the Initial Catalog or Database parameter is explicitly set to master.

Step 3: Update Default Database for the Login

  • Open SSMS and navigate to Security > Logins, right-click the affected login, and select Properties.
  • Under the General tab, check the Default database field and set it to master if administrative tasks are routinely performed under this account.
  • Alternatively, run the following T-SQL command:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = master;

Step 4: Check Application or Script Connection Settings

  • Review any automated jobs, PowerShell scripts, or application connection pools that execute administrative commands.
  • Ensure the connection string or SQL Agent job step explicitly includes USE master; or specifies master as the target database in the job step properties under Run as and Database fields.

Alternative or Verification Steps

  • To verify the fix, re-run the original command (e.g., CREATE DATABASE, sp_configure, or RESTORE DATABASE) and confirm it completes without throwing Error 5001.
  • If the issue persists, check for custom stored procedures or triggers that may be silently switching context via USE statements mid-execution, and audit them using SQL Server Profiler or Extended Events.

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

Troubleshooting Guide: Error 4999 – Change Tracking Not Supported on Timestamp Primary Key

Why This Error Happens

This error occurs because SQL Server’s Change Tracking feature requires a stable, non-volatile primary key to uniquely identify rows across transactions, and the timestamp (or rowversion) data type is specifically disqualified because its value changes automatically on every row update. Since Change Tracking relies on the primary key value remaining constant to track row-level modifications, allowing a self-mutating key type would corrupt the tracking metadata and break synchronization logic. Consequently, SQL Server 2025 blocks the ALTER TABLE or ENABLE CHANGE_TRACKING operation at the schema validation stage before it ever reaches the storage engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Run the following query to confirm the primary key data type on the affected table:
  SELECT c.name AS ColumnName, t.name AS DataType
  FROM sys.indexes i
  INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
  INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
  INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
  WHERE i.is_primary_key = 1 AND i.object_id = OBJECT_ID('YourSchema.YourTable');
  • Verify if the output shows timestamp or rowversion as the key’s data type.

Step 2: Redesign the Primary Key Constraint

  • Since you cannot track changes using a timestamp column, you must introduce a new INT IDENTITY or BIGINT IDENTITY column to serve as the primary key.
  • Execute the following to add a surrogate key (ensure no NULL values exist first):
  ALTER TABLE YourSchema.YourTable ADD NewPK_ID INT IDENTITY(1,1) NOT NULL;
  • Drop the existing primary key constraint tied to the timestamp column.
  • Create a new primary key constraint using the newly added identity column.

Step 3: Convert the Timestamp Column (If Required)

  • If the application logic still requires the timestamp data for concurrency checks, keep the column in the table but ensure it is no longer part of the primary key constraint.
  • Modify the column definition if necessary to retain it as a standard tracking column rather than a key identifier:
  -- Ensure timestamp column remains for row versioning but is NOT part of PK
  ALTER TABLE YourSchema.YourTable ALTER COLUMN RowVersionCol timestamp;

Step 4: Re-enable Change Tracking

  • Navigate to SQL Server Management Studio (SSMS) or run a T-SQL script to re-attempt enabling the feature on the modified table.
  • Execute the enablement command now that the primary key is compliant:
  ALTER TABLE YourSchema.YourTable ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = ON);

Alternative or Verification Steps

  • Verification: Query the sys.change_tracking_tables system view to confirm the table is listed and the is_track_columns_updated_on flag is set correctly.
  • Alternative: If modifying the primary key is not feasible due to application dependency constraints, consider using Change Data Capture (CDC) instead, as it offers slightly different internal tracking mechanisms, though it is generally recommended to migrate away from timestamp keys regardless of the tracking method used.

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

Troubleshooting Guide: Error 4998 — Change Tracking Not Enabled on Table

Why This Error Happens

This error occurs when a query or application attempts to retrieve change tracking data (via CHANGETABLE or similar functions) for a table that has not had change tracking explicitly enabled at the table level, even if it is enabled at the database level. This commonly happens after a table is recreated, renamed, or restored from backup, since change tracking settings are not always preserved during these operations. It can also occur if a user’s application code references a table name that no longer matches an actively tracked object due to a schema change.

Step-by-Step Resolution Guide

Step 1: Verify Database-Level Change Tracking Status

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to confirm change tracking is active at the database level:
SELECT * FROM sys.change_tracking_databases 
WHERE database_id = DB_ID('YourDatabaseName');
  • If no rows are returned, change tracking is not enabled on the database, and must be enabled first.

Step 2: Enable Change Tracking at the Database Level (If Missing)

  • Execute the following T-SQL command, replacing the database name as needed:
ALTER DATABASE YourDatabaseName
SET CHANGE_TRACKING = ON
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
  • Confirm successful execution with no error messages returned in the Messages pane.

Step 3: Enable Change Tracking on the Specific Table

  • Run the targeted table-level command, substituting your schema and table name:
ALTER TABLE dbo.YourTableName
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);
  • Ensure the table has a defined Primary Key, as change tracking requires one to function correctly.

Step 4: Check for Object Recreation or Schema Drift

  • If the table was recently dropped and recreated, re-run Step 3, as table-level tracking settings do not survive a DROP TABLE command.
  • Check deployment scripts or ORM migrations (e.g., Entity Framework) to ensure they are not inadvertently dropping and recreating the table without re-enabling tracking.

Alternative or Verification Steps

  • Verify the fix by querying sys.change_tracking_tables and confirming your table’s object_id appears in the result set.
  • If the application error persists despite verification, restart the SQL Server service via services.msc on Windows Server 2025 to clear any stale metadata caching related to the Change Tracking feature.

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

Troubleshooting Guide: Error 4997 – Change Tracking Requires a Primary Key

Why This Error Happens

This error occurs because SQL Server’s Change Tracking feature relies on a primary key to uniquely identify and track row-level modifications (inserts, updates, deletes) in a table. When a table lacks a primary key constraint, SQL Server has no reliable mechanism to map tracked changes back to specific rows, so it blocks the operation at the schema level. This is commonly seen on heap tables, staging tables, or tables migrated from systems that don’t enforce primary keys (such as flat-file imports or legacy Access databases).

Step-by-Step Resolution Guide

Step 1: Identify the Table Missing the Primary Key

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to confirm the table lacks a primary key:
  SELECT t.name AS TableName
  FROM sys.tables t
  LEFT JOIN sys.key_constraints k 
      ON t.object_id = k.parent_object_id AND k.type = 'PK'
  WHERE k.object_id IS NULL AND t.name = 'YourTableName';
  • If the query returns a row, this confirms the missing primary key is the root cause.

Step 2: Create a Primary Key on the Table

  • If the table has a column (or combination of columns) that can serve as a unique identifier, add a primary key:
  ALTER TABLE dbo.YourTableName
  ADD CONSTRAINT PK_YourTableName PRIMARY KEY CLUSTERED (YourUniqueColumn);
  • If no suitable unique column exists, add a new identity column first:
  ALTER TABLE dbo.YourTableName
  ADD RowID INT IDENTITY(1,1) NOT NULL;

  ALTER TABLE dbo.YourTableName
  ADD CONSTRAINT PK_YourTableName PRIMARY KEY CLUSTERED (RowID);
  • Ensure the column(s) used are NOT NULL, as primary keys cannot contain nulls.

Step 3: Enable Change Tracking on the Database (If Not Already Enabled)

  • Run the following at the database level before enabling it on the table:
  ALTER DATABASE YourDatabaseName
  SET CHANGE_TRACKING = ON
  (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
  • Confirm this executes without error before proceeding to the table-level command.

Step 4: Enable Change Tracking on the Table

  • Now that the primary key exists, re-run the original command:
  ALTER TABLE dbo.YourTableName
  ENABLE CHANGE_TRACKING
  WITH (TRACK_COLUMNS_UPDATED = ON);
  • The command should complete successfully without raising Error 4997.

Alternative or Verification Steps

  • Verify change tracking is active by querying sys.change_tracking_tables:
  SELECT * FROM sys.change_tracking_tables 
  WHERE object_id = OBJECT_ID('dbo.YourTableName');

A returned row confirms successful activation.

  • If you cannot modify the table schema (e.g., due to third-party application constraints), consider using Change Data Capture (CDC) instead, as it has more flexible tracking requirements, though it still performs best with a primary or unique key defined.

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

Troubleshooting Guide: Error 4996 – Change Tracking Already Enabled

Why This Error Happens

Error 4996 occurs when a ALTER TABLE ... ENABLE CHANGE_TRACKING statement is executed against a table that already has change tracking enabled at the database level. This is typically caused by a script or deployment process that does not check for existing change tracking state before attempting to enable it, often due to automated CI/CD pipelines re-running schema migration scripts. It can also occur when multiple administrators or applications independently attempt to configure change tracking on the same table without coordination.

Step-by-Step Resolution Guide

Step 1: Verify Current Change Tracking Status

  • Open SQL Server Management Studio (SSMS) and connect to your Microsoft SQL Server 2025 instance.
  • Run the following query to check which tables already have change tracking enabled:
SELECT t.name AS TableName, ctt.is_track_columns_updated_on
FROM sys.change_tracking_tables ctt
JOIN sys.tables t ON ctt.object_id = t.object_id;
  • Confirm the specific table referenced in the error message appears in the result set.

Step 2: Modify the Deployment Script to Include a Conditional Check

  • Edit your schema deployment script (commonly located in C:\Deployments\SQL\Scripts\ or your source control repository) to include a conditional check before enabling change tracking.
  • Replace the direct ALTER TABLE statement with the following pattern:
IF NOT EXISTS (
    SELECT 1 FROM sys.change_tracking_tables ctt
    JOIN sys.tables t ON ctt.object_id = t.object_id
    WHERE t.name = 'YourTableName'
)
BEGIN
    ALTER TABLE YourTableName
    ENABLE CHANGE_TRACKING
    WITH (TRACK_COLUMNS_UPDATED = ON);
END
  • Save the script and re-run your deployment pipeline to confirm the error no longer triggers.

Step 3: Disable and Re-Enable Change Tracking (If Reconfiguration Is Required)

  • If you need to change tracking settings (e.g., TRACK_COLUMNS_UPDATED), first disable tracking on the table:
ALTER TABLE YourTableName
DISABLE CHANGE_TRACKING;
  • Then re-enable it with the desired configuration:
ALTER TABLE YourTableName
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);
  • Ensure no other active sessions or jobs are simultaneously attempting to modify change tracking on the same table to avoid race conditions.

Step 4: Audit Automated Jobs and Scripts for Duplicate Execution

  • Check SQL Server Agent Jobs under SQL Server Agent > Jobs in SSMS for any duplicate or overlapping jobs that execute schema migration scripts.
  • Review Windows Task Scheduler (on Windows Server 2025 / Windows 11) for any redundant scheduled tasks triggering the same .sql deployment files.
  • Disable or consolidate duplicate jobs to prevent repeated execution of the ENABLE CHANGE_TRACKING statement.

Alternative or Verification Steps

  • Re-run the deployment script after applying the conditional check and confirm no Error 4996 appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • As an alternative, query sys.change_tracking_databases and sys.change_tracking_tables after each deployment cycle to programmatically validate tracking state before any future ALTER TABLE operations run.

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

Troubleshooting Guide: SQL Server Error 4995 – Vardecimal Storage Format Not Available in System Databases

Why This Error Happens

This error occurs because the sp_db_vardecimal_storage_format procedure is being executed against a protected system database such as master, model, msdb, or tempdb. SQL Server intentionally restricts vardecimal storage format changes to user-defined databases, as system databases rely on a fixed, internal storage structure to maintain engine stability. Attempting to enable this legacy storage feature on a system database is blocked at the engine level and is not a permissions or corruption issue, but a hard architectural limitation.

Step-by-Step Resolution Guide

Step 1: Identify the Target Database Context

  • Check the exact database name referenced in the error message (%.*ls) to confirm it is indeed a system database.
  • Run SELECT name, database_id FROM sys.databases; in SQL Server Management Studio (SSMS) to cross-reference system vs. user databases.
  • Confirm you did not accidentally run the script while connected to master instead of your intended user database.

Step 2: Correct the Database Context Before Re-running the Command

  • Open a new query window in SSMS and explicitly switch context using USE [YourUserDatabase]; before executing the procedure.
  • Re-run the command: EXEC sp_db_vardecimal_storage_format 'YourUserDatabase', 'ON';
  • Avoid running maintenance or storage-format scripts inside master, model, msdb, or tempdb entirely.

Step 3: Audit Automation Scripts and Deployment Pipelines

  • Review any PowerShell, DACPAC, or SSDT deployment scripts running on Windows Server 2025 that may loop through sys.databases and apply this setting to all databases, including system ones.
  • Add a filter condition such as WHERE database_id > 4 to exclude system databases (master, tempdb, model, msdb) from the loop logic.
  • Update any scheduled SQL Agent Jobs to explicitly target only intended user databases.

Step 4: Consider Modern Alternatives (Since Vardecimal Is Deprecated)

  • Since SQL Server 2016+ (including SQL Server 2025), Vardecimal storage format is a legacy feature superseded by Row/Page Compression.
  • On your user database, use ALTER TABLE YourTable REBUILD WITH (DATA_COMPRESSION = ROW); instead for better storage efficiency and native engine support.

Alternative or Verification Steps

  • Verify the Fix: Run EXEC sp_db_vardecimal_storage_format 'YourUserDatabase', 'STATUS'; to confirm the setting applies successfully without throwing Error 4995.
  • Alternative Solution: If vardecimal format is not strictly required, skip it entirely and implement DATA_COMPRESSION = PAGE on the specific table, which achieves similar storage savings and is fully supported in Windows Server 2025 environments without the system database restriction.

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

Troubleshooting Guide: SQL Server Error 4994 — Computed Column Cannot Be Persisted

Why This Error Happens

Error 4994 occurs because the computed column expression evaluates to a data type that SQL Server does not permit for persisted (PERSISTED) columns, such as text, ntext, image, sql_variant, CLR non-deterministic types, or results derived from nondeterministic functions. SQL Server requires that persisted computed columns be based on expressions that are both deterministic and precision-safe so the value can be physically stored and indexed. This typically happens after a schema migration or upgrade to SQL Server 2025, where stricter type-checking rules expose previously ignored incompatibilities in computed column definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Expression

  • Run EXEC sp_help 'TableName'; or query sys.computed_columns to locate the exact column and its defining expression.
  • Check the base expression for use of nondeterministic functions like GETDATE(), NEWID(), or RAND().
  • Note the underlying data type referenced in the error message (e.g., ntext, sql_variant, xml).

Step 2: Modify the Computed Column Definition

  • Alter the expression to avoid unsupported types — cast results explicitly using CONVERT() or CAST() to a deterministic, persist-eligible type (e.g., VARCHAR, INT, DECIMAL).
  • Example fix:
  ALTER TABLE dbo.YourTable DROP COLUMN ComputedCol;
  ALTER TABLE dbo.YourTable ADD ComputedCol AS (CAST(Expression AS VARCHAR(100))) PERSISTED;
  • If the function used is inherently nondeterministic, remove the PERSISTED keyword entirely and allow the column to compute at query time instead.

Step 3: Rebuild Dependent Indexes and Constraints

  • Drop and recreate any indexes that referenced the old computed column definition using DROP INDEX and CREATE INDEX in SQL Server Management Studio (SSMS) 21 or via sqlcmd.
  • Validate foreign key or check constraints tied to the column still resolve correctly after the type change.

Step 4: Apply Latest Cumulative Update

  • Navigate to Microsoft’s official download center and install the latest Cumulative Update (CU) for SQL Server 2025, as type-persistence validation logic is frequently patched.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator on Windows Server 2025 / Windows 11).

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM sys.computed_columns WHERE is_persisted = 1; and confirming the column now appears without error during a manual DBCC CHECKDB or table rebuild.
  • If persistence is not strictly required for performance, as an alternative, remove PERSISTED altogether and let SQL Server calculate the column value dynamically at query runtime.

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

Troubleshooting Guide: Error 4993 – ALTER TABLE SWITCH Failure Due to Large Value Types Out Of Row Mismatch

Why This Error Happens

This error occurs when the source and target tables involved in an ALTER TABLE SWITCH operation have mismatched large value types out of row settings, which controls whether large object (LOB) data types like varchar(max), nvarchar(max), varbinary(max), and xml are stored in-row or pushed to separate LOB pages. SQL Server enforces strict schema and storage parity between partitions during a switch operation because the underlying physical storage structure must be identical for the metadata-only switch to succeed. This mismatch typically happens when one table was created or altered with sp_tableoption explicitly set, while the other retained the default setting.

Step-by-Step Resolution Guide

Step 1: Identify the Current Table Settings

  • Open SSMS or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to check the current setting on both tables:
SELECT large_value_types_out_of_row 
FROM sys.tables 
WHERE name IN ('SourceTableName', 'TargetTableName');
  • Note the Boolean value (0 or 1) returned for each table; these must match exactly before proceeding.

Step 2: Align the Table Option Using sp_tableoption

  • Execute sp_tableoption on the table with the mismatched setting to bring it in line with the other.
  • Example command to set the option to match (replace 1 with 0 if needed):
EXEC sp_tableoption 'dbo.SourceTableName', 'large value types out of row', '1';
  • Run this on whichever table (source or target/partition) currently has the incorrect value based on the Step 1 results.

Step 3: Rebuild Affected Indexes

  • After changing the table option, existing LOB data pages are not automatically reorganized, so rebuild all indexes on the modified table to force storage consistency.
  • Run the following for each index, or use ALTER INDEX ALL:
ALTER INDEX ALL ON dbo.SourceTableName REBUILD;
  • This step is mandatory on Windows Server 2025 instances using the latest SQL Server 2025 storage engine updates, as cached LOB pointers can otherwise persist.

Step 4: Re-run the ALTER TABLE SWITCH Command

  • Execute your original ALTER TABLE ... SWITCH statement again now that both tables share identical LOB storage settings.
  • Monitor the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for confirmation that no further 4993 errors are raised.

Alternative or Verification Steps

  • Verify success by re-running the sys.tables query from Step 1 on both tables — the large_value_types_out_of_row column values should now be identical.
  • If the switch still fails, drop and recreate the target partition table from scratch using a SELECT INTO from the source table, which guarantees identical storage options, then retry the switch operation.

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

Troubleshooting Guide: Error 4992 – “Cannot use table option LARGE VALUE TYPES OUT OF ROW on a user table that does not have any of large value types varchar(max)…”

Why This Error Happens

This error occurs because the large value types out of row table option can only be applied to tables that actually contain at least one large object (LOB) data type column, such as varchar(max), nvarchar(max), varbinary(max), or xml. SQL Server 2025 validates the table schema before applying this storage setting, and if no qualifying column exists, the sp_tableoption call is rejected. This commonly happens when a script is reused across tables without verifying column data types, or when a column was previously altered from .max to a fixed-length type.

Step-by-Step Resolution Guide

Step 1: Verify the Table Schema

  • Open SSMS or run a query against INFORMATION_SCHEMA.COLUMNS to confirm column data types:
SELECT COLUMN_NAME, DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'YourTableName';
  • Confirm whether any column is varchar(max), nvarchar(max), varbinary(max), or xml.
  • If none exist, this confirms the root cause of Error 4992.

Step 2: Modify the Table to Include a Qualifying Data Type

  • If the table design requires LOB storage control, alter an existing column to a .max type:
ALTER TABLE YourTableName 
ALTER COLUMN YourColumn VARCHAR(MAX);
  • Ensure this change aligns with your data model and does not break downstream application logic (e.g., fixed-length assumptions in C# or Entity Framework models).

Step 3: Re-run the Table Option Command

  • Once a valid LOB column exists, re-execute the original statement:
EXEC sp_tableoption 'YourTableName', 'large value types out of row', 'ON';
  • Confirm no errors are returned in the Messages pane.

Step 4: Remove the Option If LOB Storage Isn’t Needed

  • If the table was never intended to store LOB data, simply skip applying this option.
  • Remove the line from your deployment script or migration file (e.g., DACPAC, SSDT project, or Flyway script) to prevent future failures during automated deployments.

Alternative or Verification Steps

  • Run sp_help 'YourTableName' after the fix to confirm the table option is now active and the schema includes the correct LOB column.
  • If the error persists in automated CI/CD pipelines (e.g., Azure DevOps or GitHub Actions on Windows Server 2025 runners), check the deployment script for hardcoded table names that may be pointing to the wrong object.

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

Troubleshooting Guide: SQL Server Error 4991 – NOT FOR REPLICATION Attribute Error

Why This Error Happens

This error occurs because the NOT FOR REPLICATION clause is a special attribute that SQL Server only permits on IDENTITY columns and certain constraints (like FOREIGN KEY or CHECK), not on standard data columns. The root cause is typically a migration script, an ORM-generated schema, or a manually written ALTER TABLE statement that incorrectly attempts to apply this flag to a regular integer, varchar, or other non-identity column. Essentially, the SQL engine is rejecting the syntax because the target column lacks the underlying identity property required to support replication-filtering logic.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Script

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance and locate the exact ALTER TABLE statement referenced in the Event ID 4991 log.
  • Run the following query to check the column’s properties and confirm it is not currently set as an identity column:
SELECT name, is_identity FROM sys.columns 
WHERE object_id = OBJECT_ID('YourTableName');
  • Verify if is_identity returns 0 for the column mentioned in the error.

Step 2: Correct the Schema Design

  • If the column was intended to be an auto-incrementing key, you cannot simply add NOT FOR REPLICATION to an existing column; you must recreate the column with the IDENTITY property first.
  • Since you cannot alter an existing column to add the IDENTITY property directly, create a new column with the correct definition:
ALTER TABLE YourTableName ADD NewIDColumn INT IDENTITY(1,1) NOT FOR REPLICATION;
  • Migrate data from the old column to the new one if required, then drop the old column and rename the new one using sp_rename.

Step 3: Fix the Constraint Syntax (If Applicable)

  • If the error relates to a FOREIGN KEY or CHECK constraint rather than a column, ensure the NOT FOR REPLICATION syntax is placed correctly within the constraint definition and not attached to the column name itself.
  • Example of correct constraint syntax:
ALTER TABLE YourTableName 
ADD CONSTRAINT FK_Constraint FOREIGN KEY (ColumnName) 
REFERENCES OtherTable(ID) NOT FOR REPLICATION;
  • Re-run the script to ensure the engine parses the attribute against the constraint logic rather than the raw column type.

Step 4: Update Replication Scripts

  • If this error surfaced during a Transactional Replication setup, check the “Article Properties” in the Publication settings to ensure the schema option for “Copy NOT FOR REPLICATION” isn’t being forced on non-identity columns during snapshot generation.
  • Regenerate the snapshot after fixing the schema to ensure the Distribution Agent picks up the corrected table definition.

Alternative or Verification Steps

  • Verification: Re-run the original ALTER TABLE script. If successful, query sys.identity_columns to confirm the is_not_for_replication flag is now set to 1 for the specific column.
  • Alternative: If modifying the production schema is too risky, use a CHECK constraint with NOT FOR REPLICATION as a workaround to bypass data validation during replication without altering the column’s core identity properties.

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

Troubleshooting Guide: Error 4990 – Cannot Alter FILESTREAM Column Attribute

Why This Error Happens

Error 4990 occurs when SQL Server 2025 attempts to add or remove the FILESTREAM attribute on a column, but the underlying table structure or database configuration prevents the operation. This typically happens because the table already contains data incompatible with FILESTREAM storage requirements, the database lacks a properly configured FILESTREAM filegroup, or the operation is being attempted inside a transaction or replication context that blocks schema changes of this type. Additionally, this error can surface if the column is part of an active index, constraint, or is referenced by a computed column that does not support FILESTREAM conversion.

Step-by-Step Resolution Guide

Step 1: Verify FILESTREAM is Enabled at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services → right-click your instance → Properties → FILESTREAM tab.
  • Ensure “Enable FILESTREAM for Transact-SQL access” is checked.
  • Run the following T-SQL to confirm instance-level configuration:
  EXEC sp_configure 'filestream access level';
  • If the value is 0, update it:
  EXEC sp_configure 'filestream access level', 2;
  RECONFIGURE;

Step 2: Confirm the Database Has a Valid FILESTREAM Filegroup

  • Check existing filegroups with:
  SELECT name, type_desc FROM sys.filegroups;
  • If no FILESTREAM_DATA filegroup exists, create one:
  ALTER DATABASE YourDB ADD FILEGROUP FileStreamGroup CONTAINS FILESTREAM;
  ALTER DATABASE YourDB ADD FILE (NAME = FS_Data, FILENAME = 'C:\SQLData\FileStream') TO FILEGROUP FileStreamGroup;
  • Ensure the path (e.g., C:\SQLData\FileStream) exists and the SQL Server service account has full read/write permissions on that folder.

Step 3: Remove Blocking Constraints or Indexes on the Column

  • Identify any indexes, foreign keys, or check constraints tied to the target column:
  EXEC sp_help 'YourTable';
  • Temporarily drop any conflicting constraints or indexes before altering the column.
  • Re-run the ALTER TABLE statement:
  ALTER TABLE YourTable ALTER COLUMN YourColumn ADD FILESTREAM;

Step 4: Check for Open Transactions or Replication Locks

  • Run sp_who2 or query sys.dm_tran_locks to confirm no active transactions are holding locks on the table.
  • If the table is part of replication, temporarily pause the publication before altering the schema, then resume afterward.

Alternative or Verification Steps

  • After applying the fix, verify success by querying sys.columns and sys.filestream_tombstone_history to confirm the FILESTREAM attribute was applied correctly, or re-run ALTER TABLE to ensure no error 4990 is returned.
  • As an alternative, if the column still fails to alter, drop and recreate the table with the FILESTREAM column defined at creation time, then migrate data using INSERT INTO ... SELECT.

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

Troubleshooting Guide: SQL Server Error 4989 — Cannot Drop ROWGUIDCOL Property

Why This Error Happens

This error occurs when an ALTER TABLE statement attempts to drop the ROWGUIDCOL property from a column that SQL Server does not recognize as the table’s designated ROWGUIDCOL. Each table can only have one ROWGUIDCOL column at a time, and SQL Server tracks this designation internally in the syscolumns/sys.columns metadata via the is_rowguidcol attribute. If the column specified in the script was never explicitly marked as ROWGUIDCOL, was already altered previously, or if there is a mismatch between the script and the actual current schema (often due to replication scripts, migration scripts, or stale deployment artifacts), SQL Server rejects the operation with Error 4989.

Step-by-Step Resolution Guide

Step 1: Verify the Current ROWGUIDCOL Designation

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to identify which column (if any) currently holds the ROWGUIDCOL property:
SELECT c.name AS ColumnName, c.is_rowguidcol
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('YourSchema.YourTableName')
AND c.is_rowguidcol = 1;
  • If no rows are returned, no column in the table is currently marked as ROWGUIDCOL, confirming the root cause.

Step 2: Correct the ALTER TABLE Script

  • Compare the column name referenced in your failing script against the result from Step 1.
  • If the names do not match, update your script to reference the actual ROWGUIDCOL column name returned by the query.
  • If the query returned zero rows, remove the DROP ROWGUIDCOL clause entirely from your script since there is nothing to drop:
ALTER TABLE YourSchema.YourTableName
ALTER COLUMN YourColumnName ADD ROWGUIDCOL;

Step 3: Check for Deployment or Replication Script Drift

  • Inspect any DACPAC, SSDT project files, or migration scripts (Flyway, Liquibase, EF Core migrations) for outdated column metadata definitions.
  • Regenerate the deployment script against the live Windows Server 2025 instance to ensure schema definitions are synchronized:
sqlpackage /Action:Script /SourceFile:"C:\Deployments\YourProject.dacpac" /TargetConnectionString:"Server=localhost;Database=YourDB;Integrated Security=true;" /OutputPath:"C:\Deployments\UpdateScript.sql"
  • Review the generated script manually before execution to confirm it no longer attempts to drop a non-existent ROWGUIDCOL property.

Step 4: Rebuild the ROWGUIDCOL Property if Required

  • If the application logic genuinely requires a ROWGUIDCOL column (commonly used for merge replication), explicitly add it to the correct column instead of attempting to drop a mismatched one:
ALTER TABLE YourSchema.YourTableName
ALTER COLUMN RowGuidColumn ADD ROWGUIDCOL;
  • Ensure only one column per table has this property, as SQL Server 2025 still enforces the single-ROWGUIDCOL-per-table restriction.

Alternative or Verification Steps

  • Re-run the Step 1 query after applying changes; confirm that is_rowguidcol = 1 now appears only on the intended column and nowhere else in the table.
  • If the error persists in automated deployment pipelines, drop the entire table object reference from the DACPAC/migration baseline and re-scaffold it using SqlPackage.exe /Action:Extract against the production schema to eliminate stale metadata drift.

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

Troubleshooting Guide: SQL Server Error 4988 — “Cannot persist computed column” (Ownership Mismatch)

Why This Error Happens

This error occurs when a computed column references a function, view, or other object (via a schema-bound or deterministic expression) that is owned by a different database principal than the table itself. SQL Server requires strict owner-matching between a persisted or indexed computed column and all underlying objects it references to guarantee deterministic behavior and prevent ownership-chaining security issues. This typically happens after a schema migration, a restored database from another environment, or when objects were created by different logins/users without explicit schema alignment.

Step-by-Step Resolution Guide

Step 1: Identify the Ownership Mismatch

  • Run the following query to find the owner of the table in question:
SELECT s.name AS SchemaName, t.name AS TableName, dp.name AS OwnerName
FROM sys.tables t
JOIN sys.schemas s ON t.schema_id = s.schema_id
JOIN sys.database_principals dp ON t.principal_id = dp.principal_id
WHERE t.name = 'YourTableName';
  • Compare this against the owner of the referenced function/object:
SELECT o.name, o.type_desc, dp.name AS OwnerName
FROM sys.objects o
JOIN sys.database_principals dp ON o.principal_id = dp.principal_id
WHERE o.name = 'YourReferencedFunctionOrView';
  • Note any discrepancy in the OwnerName columns — this is the root cause of Error 4988.

Step 2: Align Ownership Using ALTER AUTHORIZATION

  • Use ALTER AUTHORIZATION to reassign the underlying object to match the table’s owner (or vice versa, depending on your security policy).
  • Example command to align a function’s owner with the table’s schema owner:
ALTER AUTHORIZATION ON OBJECT::dbo.YourReferencedFunction TO [dbo];
  • If the table and function live in different schemas, consider moving the object into the same schema instead:
ALTER SCHEMA dbo TRANSFER OtherSchema.YourReferencedFunction;
  • Ensure you have CONTROL or ALTER permission on both the object and the target schema/principal before running this.

Step 3: Drop and Recreate the Computed Column

  • Once ownership is aligned, drop the problematic computed column:
ALTER TABLE YourTableName DROP COLUMN YourComputedColumn;
  • Recreate it with the PERSISTED keyword now that ownership matches:
ALTER TABLE YourTableName
ADD YourComputedColumn AS (dbo.YourReferencedFunction(SomeColumn)) PERSISTED;
  • If the column is part of an index, rebuild the index afterward:
CREATE INDEX IX_YourIndex ON YourTableName(YourComputedColumn);

Step 4: Validate Schema Consistency Server-Wide

  • Run sys.sql_expression_dependencies to check for any other computed columns referencing cross-schema objects with mismatched ownership.
  • Document and standardize schema ownership (e.g., enforce all business objects under dbo) to prevent recurrence after future deployments or restores.

Alternative or Verification Steps

  • Verify the fix by querying sys.computed_columns and confirming the is_persisted flag is set to 1 for the affected column without throwing Error 4988 on ALTER TABLE or INSERT operations.
  • If ALTER AUTHORIZATION is restricted by compliance policy, an alternative is to rewrite the computed column expression using only inline T-SQL logic (avoiding external function calls) so no cross-object ownership dependency exists at all.

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

Troubleshooting Guide: SQL Server Error 4987 – XML Schema Collection Mismatch in ALTER TABLE SWITCH

Why This Error Happens

This error occurs because the ALTER TABLE SWITCH operation requires that any XML-typed columns in both the source and target tables be bound to the exact same XML Schema Collection, not just a schema collection with an identical name or structure. SQL Server validates the internal schema collection ID (not just the typed XML definition), so even logically identical schemas created separately in each table’s context will fail this check. This commonly happens when partitioned tables or staging tables are created independently using CREATE XML SCHEMA COLLECTION scripts run separately, rather than referencing the same collection object used by the source table.

Step-by-Step Resolution Guide

Step 1: Identify the Mismatched XML Schema Collections

  • Run a query against sys.xml_schema_collections joined with sys.columns and sys.types for both the source and target (staging) tables to compare the xml_collection_id values.
  • Use this query to pinpoint the exact column referenced in the error message:
SELECT c.name AS ColumnName, t.name AS TableName, xsc.name AS SchemaCollectionName, xsc.xml_collection_id
FROM sys.columns c
JOIN sys.types ty ON c.user_type_id = ty.user_type_id
JOIN sys.xml_schema_collections xsc ON ty.xml_collection_id = xsc.xml_collection_id
WHERE c.object_id IN (OBJECT_ID('dbo.SourceTable'), OBJECT_ID('dbo.StagingTable'));
  • Confirm that the xml_collection_id differs between the two tables for the flagged column.

Step 2: Rebuild the Staging Table to Reference the Identical Schema Collection

  • Drop the XML column on the staging/target table that currently points to a mismatched or duplicate schema collection.
  • Re-add the column explicitly casting it to the same schema collection object used by the source table (using the fully qualified name, e.g., [dbo].[MySchemaCollection]):
ALTER TABLE dbo.StagingTable
ADD XmlColumn XML(CONTENT [dbo].[MySchemaCollection]);
  • Ensure you do not run a second CREATE XML SCHEMA COLLECTION statement for the target table; always reuse the original object reference.

Step 3: Recreate the Partitioned Table Structure (If Applicable)

  • If the staging table was generated via a script or ORM that inadvertently created a new schema collection with the same name in a different schema, drop that duplicate collection using DROP XML SCHEMA COLLECTION dbo.DuplicateCollectionName.
  • In SQL Server Management Studio (SSMS) 21 on Windows Server 2025, use the “Generate Scripts” wizard on the source table to export the exact XML type definition, ensuring the staging table script inherits the identical binding.
  • Re-run the ALTER TABLE ... SWITCH command once the column definitions match exactly at the schema collection ID level.

Alternative or Verification Steps

  • Verification: Re-run the ALTER TABLE SourceTable SWITCH TO StagingTable command; if successful, confirm data integrity by checking row counts via sys.partitions on both tables.
  • Alternative: If schema collections cannot be unified due to application constraints, bypass the SWITCH operation for that specific table and use a standard INSERT INTO ... SELECT batch process instead, though this will be significantly slower for large partitions.

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

Troubleshooting Guide: Error 4986 — ALTER TABLE SWITCH CLR Type Mismatch

Why This Error Happens

This error occurs when a column defined with a CLR user-defined type (UDT) in the source table does not precisely match the assembly version, type definition, or binary layout of the same-named column in the target table during a partition switch operation. SQL Server 2025 performs strict metadata validation on CLR types during ALTER TABLE...SWITCH, so even a minor discrepancy—such as a different assembly GUID, version mismatch, or a UDT registered from a different assembly build—will trigger this failure. This is commonly caused by one table referencing a CLR assembly that was redeployed, updated, or registered independently of the other, resulting in two logically similar but technically distinct type definitions.

Step-by-Step Resolution Guide

Step 1: Identify the Mismatched Column and CLR Type

  • Run the following query to inspect the offending column’s type on both tables:
  • SELECT c.name, t.name AS type_name, t.system_type_id, t.user_type_id FROM sys.columns c JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE c.object_id = OBJECT_ID('SourceTable') OR c.object_id = OBJECT_ID('TargetTable');
  • Confirm both columns reference the same user_type_id and assembly name.

Step 2: Compare CLR Assembly Versions Between Tables

  • Query sys.assemblies and sys.assembly_types to check the version, culture, and public key token of the assembly backing each UDT:
  • SELECT a.name, a.clr_name, at.name AS type_name FROM sys.assemblies a JOIN sys.assembly_types at ON a.assembly_id = at.assembly_id;
  • If the source and target databases show different clr_name version strings, this confirms the mismatch.

Step 3: Re-register the CLR Assembly Consistently

  • Drop and re-create the UDT and its underlying assembly using the exact same .dll file for both tables:
  • DROP TYPE dbo.YourUDT; DROP ASSEMBLY YourAssemblyName;
  • CREATE ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • CREATE TYPE dbo.YourUDT EXTERNAL NAME YourAssemblyName.[YourUDTClass];
  • Re-apply this identical assembly binary across both the source and target table definitions.

Step 4: Rebuild the Column Using the Corrected Type

  • Alter the column on whichever table has the outdated or mismatched type reference:
  • ALTER TABLE TargetTable ALTER COLUMN YourColumn dbo.YourUDT;
  • Ensure no open transactions or schema locks are blocking the alteration before executing.

Step 5: Retry the Partition Switch Operation

  • Re-run the original command:
  • ALTER TABLE SourceTable SWITCH PARTITION x TO TargetTable PARTITION y;
  • Confirm the operation completes without raising Error 4986.

Alternative or Verification Steps

  • Verify the fix by querying sys.assembly_types on both tables and confirming identical assembly_id and user_type_id values post-fix.
  • If the error persists, drop both UDT columns entirely and recreate them from a single centralized assembly deployment script to guarantee binary-level consistency across environments.

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

Troubleshooting Guide: Error 4985 – ALTER TABLE SWITCH Nullability Mismatch

Why This Error Happens

This error occurs because SQL Server enforces strict schema matching rules when performing partition switching operations, and one or more columns in the source and target tables have mismatched NULL/NOT NULL constraints. The ALTER TABLE SWITCH command requires that both tables share an identical schema definition, including nullability, data types, and collation, since the operation is a metadata-only change rather than a data copy. This mismatch typically arises when tables are created independently over time or when a staging table is generated using a different script than the one used for the partitioned table.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Column

  • Run the following query to compare column nullability between the source and target tables:
  SELECT c.name AS ColumnName, c.is_nullable, t.name AS TableName
  FROM sys.columns c
  JOIN sys.tables t ON c.object_id = t.object_id
  WHERE t.name IN ('SourceTable', 'TargetTable')
  ORDER BY c.name;
  • Note the exact column name referenced in the Error 4985 message, as this is the specific field causing the conflict.

Step 2: Align the Nullability Settings

  • Use ALTER TABLE to modify the staging (source) table so its nullability matches the partitioned (target) table.
  • Example command to make a column NOT NULL to match the target:
  ALTER TABLE SourceTable 
  ALTER COLUMN YourColumnName INT NOT NULL;
  • If the target table allows NULL values, reverse the logic and update the source table to allow NULL instead.

Step 3: Verify Data Integrity Before Re-Running

  • Before altering a column to NOT NULL, check for existing NULL values that might cause the ALTER TABLE command to fail:
  SELECT COUNT(*) FROM SourceTable WHERE YourColumnName IS NULL;
  • If NULL values exist, either update them to a default value or change the target table to allow NULL instead, depending on business logic requirements.

Step 4: Re-attempt the Partition Switch

  • Execute the ALTER TABLE SWITCH statement again once the schemas are aligned:
  ALTER TABLE SourceTable SWITCH TO TargetTable PARTITION 1;
  • Confirm the command completes with a “Command(s) completed successfully” message in SQL Server Management Studio (SSMS).

Alternative or Verification Steps

  • Verify the fix by querying sys.columns for both tables again to ensure is_nullable values match exactly for every column involved in the switch.
  • If schema drift continues to be an issue, consider using a script-based or Database Project (DACPAC) approach to standardize staging table schemas, ensuring they are always generated directly from the production table’s definition.

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

Troubleshooting Guide: Error 4984 – Vardecimal Storage Format Mismatch in ALTER TABLE SWITCH

Why This Error Happens

This error occurs because SQL Server requires the source and target tables in a partition SWITCH operation to have identical physical storage formats, and the “vardecimal storage format” setting is enabled on one table but not the other. This mismatch typically happens when tables are created at different times under different default settings, or when a database-level or table-level configuration was changed after one of the tables was already created. Since SWITCH is a metadata-only operation, SQL Server cannot reconcile differing row storage formats on the fly, so it blocks the operation entirely.

Step-by-Step Resolution Guide

Step 1: Verify Current Vardecimal Storage Settings

  • Open SQL Server Management Studio (SSMS) and connect to the target instance.
  • Run the following query to check the current state on both tables:
  EXEC sp_tableoption 'YourSourceTable', 'vardecimal storage format';
  EXEC sp_tableoption 'YourTargetTable', 'vardecimal storage format';
  • Note which table has the setting enabled (1) and which has it disabled (0).

Step 2: Align the Vardecimal Storage Format on Both Tables

  • Identify the table with the mismatched setting (usually the newly created or newly loaded table).
  • Run the following command to enable or disable the setting to match the other table:
  EXEC sp_tableoption 'YourMismatchedTable', 'vardecimal storage format', '1';
  • Note: If using SQL Server 2025 on Windows Server 2025, ensure the database compatibility level supports this setting, as vardecimal storage format is a legacy feature retained for backward compatibility.

Step 3: Rebuild Indexes to Apply the Format Change

  • After changing the vardecimal storage format option, the change does not take effect until you rebuild the table’s indexes.
  • Run the following command to force the conversion:
  ALTER INDEX ALL ON YourMismatchedTable REBUILD;
  • If the table has no clustered index, you may need to rebuild the heap by creating and dropping a clustered index, or use ALTER TABLE ... REBUILD.

Step 4: Re-run the ALTER TABLE SWITCH Statement

  • Once both tables report the same vardecimal storage format value, re-attempt the original partition switch operation.
  • Example:
  ALTER TABLE YourSourceTable SWITCH TO YourTargetTable PARTITION x;
  • Confirm the operation completes without raising Error 4984.

Alternative or Verification Steps

  • To verify the fix, query sys.tables joined with sys.partitions or re-run sp_tableoption on both tables to confirm the vardecimal storage format values now match (both should return the same 0 or 1 value).
  • As an alternative, if rebuilding indexes on a large table is too costly in production, consider creating a new staging table with matching settings via SELECT INTO or CREATE TABLE AS SELECT, then switching into that table instead of altering the existing one.

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

Troubleshooting Guide: SQL Server Error 4983 — ALTER TABLE SWITCH Failed Due to XML or Spatial Index on Target Table

Why This Error Happens

This error occurs because the target table in an ALTER TABLE...SWITCH operation contains an XML or spatial index, which SQL Server 2025 does not permit. The partition switching mechanism requires the target table to be schema-identical to the source table in terms of these specific index types — only the source table is allowed to carry XML or spatial indexes during the switch. This typically happens when a staging table was created using SELECT INTO or a script that replicated indexes from a table that originally had XML/spatial indexing enabled, or when the target table was repurposed from another schema without stripping these indexes.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Index on the Target Table

  • Run the following query to list all XML and spatial indexes on the target table:
  • SELECT i.name AS IndexName, i.type_desc, t.name AS TableName FROM sys.indexes i JOIN sys.tables t ON i.object_id = t.object_id WHERE t.name = 'YourTargetTableName' AND i.type_desc IN ('XML', 'SPATIAL');
  • Note the exact index name(s) returned, as you will need them in the next step.

Step 2: Drop the XML or Spatial Index from the Target Table

  • Execute a DROP INDEX statement for each identified index:
  • DROP INDEX [IndexName] ON [dbo].[YourTargetTableName];
  • If there are multiple XML or spatial indexes, repeat this command for each one until sys.indexes returns no XML/SPATIAL type rows for that table.
  • Ensure no active transactions or open connections are locking the index before attempting the drop (check via sys.dm_tran_locks if the drop hangs).

Step 3: Re-run the ALTER TABLE SWITCH Statement

  • Once all XML/spatial indexes are removed from the target, re-execute the original switch command:
  • ALTER TABLE [dbo].[SourceTable] SWITCH TO [dbo].[TargetTable];
  • Confirm the command completes without throwing Error 4983.

Step 4: Rebuild Indexes on Target Table (If Needed Post-Switch)

  • If the XML or spatial index was required for application functionality on the target table, recreate it after the switch operation completes successfully.
  • Use CREATE XML INDEX or CREATE SPATIAL INDEX syntax matching your original index definition, referencing the backed-up script from Step 1 if you saved the index DDL beforehand.

Alternative or Verification Steps

  • Verify the fix by querying sys.indexes again on the target table post-switch to confirm no XML/SPATIAL type indexes exist, and validate data integrity with SELECT COUNT(*) FROM TargetTable to ensure partition data switched correctly.
  • If dropping the index is not an option due to application dependencies, consider using a different staging table without XML/spatial indexes as an intermediary, then switch data into your final target table in a separate step after index reconciliation.

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

Troubleshooting Guide: SQL Server Error 4982 – ALTER TABLE SWITCH Partition Mismatch

Why This Error Happens

This error occurs because SQL Server’s partition switching feature requires the source table’s data to be fully validated against the boundary values of the target partition before the metadata switch can occur. Typically, the source table is either missing a CHECK constraint entirely, or the existing constraint logic does not precisely align with the partition function’s boundary range on the target table. Since SQL Server 2025 enforces strict schema validation during switch operations to maintain data integrity, any discrepancy—even a single row outside the defined range—will block the operation entirely.

Step-by-Step Resolution Guide

Step 1: Identify the Partition Boundary Values

  • Open SQL Server Management Studio (SSMS) and connect to your instance.
  • Run a query against sys.partition_range_values and sys.partition_functions to determine the exact boundary values (e.g., LEFT or RIGHT range) for the specific partition number mentioned in the error message.
  • Note the data type and boundary logic (inclusive vs. exclusive) required for the target partition.

Step 2: Audit and Correct the Source Table Constraint

  • Check the existing constraint using sp_helpconstraint 'YourSourceTableName'.
  • Verify if the CHECK constraint matches the boundary values found in Step 1. It must be just as restrictive or more restrictive than the partition range.
  • If the constraint is missing or incorrect, drop the old one and add a new one:
  ALTER TABLE YourSourceTable WITH CHECK 
  ADD CONSTRAINT CK_PartitionRange CHECK (YourColumn >= 'StartValue' AND YourColumn < 'EndValue');

Step 3: Validate Existing Data Against the New Constraint

  • Ensure the constraint is trusted and not just logically present but unenforced.
  • Run the following command to force SQL Server to re-check all existing rows against the constraint:
  ALTER TABLE YourSourceTable WITH CHECK CHECK CONSTRAINT CK_PartitionRange;
  • If this command fails, it will return the specific rows violating the range, allowing you to clean or move that data before retrying the switch.

Step 4: Retry the Partition Switch

  • Navigate back to your original ALTER TABLE ... SWITCH TO ... statement.
  • Execute the command again now that the constraint metadata matches the target partition boundaries.
  • Monitor the “Messages” tab in SSMS for a successful completion status.

Alternative or Verification Steps

  • Verification: Query sys.partitions on the target table immediately after the switch to confirm the rows count has increased in the correct partition number, verifying the metadata update was successful.
  • Alternative: If constraint logic becomes too complex to debug, bypass the check by using ALTER TABLE ... SWITCH ... WITH (TRUNCATE_TARGET = ON) only if you are certain the target partition is intended to be overwritten, though this does not fix underlying data integrity issues for future switches.

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

Troubleshooting Guide: Error 4981 – ALTER TABLE SWITCH Failure Due to Read-Only Filegroup

Why This Error Happens

This error occurs because the table you are attempting to switch contains LOB (Large Object Binary) data—such as VARCHAR(MAX), TEXT, or XML columns—that physically resides on a filegroup currently marked as READ-ONLY. SQL Server’s ALTER TABLE SWITCH operation requires metadata-only updates across all data pages, including LOB pages; if the underlying filegroup cannot be written to, the engine cannot validate or update the partition metadata, causing the switch to fail. This typically happens after a filegroup has been set to read-only for archival purposes, or during a restore operation where file permissions were altered.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic Filegroup

  • Run the following query to locate which filegroup holds the LOB data for the specific table mentioned in the error message:
SELECT fg.name AS FilegroupName, fg.is_read_only 
FROM sys.filegroups fg
JOIN sys.tables t ON t.lob_data_space_id = fg.data_space_id
WHERE t.name = 'YourTableName';
  • Confirm the is_read_only column returns 1 (True) for the identified filegroup.

Step 2: Temporarily Disable Read-Only Mode

  • Ensure no active connections are using the database in Single-User mode if required, though generally this can be done in Multi-User mode for Read-Only toggles.
  • Execute the ALTER DATABASE command to switch the specific filegroup back to Read-Write:
ALTER DATABASE YourDatabaseName 
MODIFY FILEGROUP YourFilegroupName READWRITE;
  • Verify in Windows Server 2025 File Explorer that the underlying .ndf or .mdf file properties are not set to “Read-only” at the OS level, as this can sometimes override SQL settings.

Step 3: Execute the Partition Switch

  • Re-run the original ALTER TABLE ... SWITCH PARTITION command now that the filegroup accepts write operations.
  • Ensure the schema of the source and target tables match exactly (including compression settings) to avoid a secondary error immediately following this fix.

Step 4: Revert Filegroup to Read-Only (Optional)

  • If the filegroup was intentionally read-only for archival/performance reasons, set it back immediately after the switch completes:
ALTER DATABASE YourDatabaseName 
MODIFY FILEGROUP YourFilegroupName READONLY;
  • Document this change in your maintenance plan to prevent the same error during the next scheduled partition maintenance window.

Alternative or Verification Steps

  • Verification: Query sys.partitions and sys.allocation_units to confirm the data has physically moved to the new partition without errors, and check the SQL Server Error Log for the absence of Error 4981 on the next attempt.
  • Alternative: If the filegroup must remain permanently read-only (e.g., compliance requirements), the alternative is to physically move the LOB data to a writable filegroup using a CREATE TABLE operation with a new TEXTIMAGE_ON clause pointing to a read-write filegroup, then repopulate the data before switching.

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

Troubleshooting Guide: Error 4980 — ALTER TABLE SWITCH Failed Due to Read-Only Filegroup (LOB Data)

Why This Error Happens

This error occurs because the ALTER TABLE...SWITCH operation requires full read-write access to every filegroup associated with the partition being switched, including filegroups that store LOB (Large Object) data types such as VARCHAR(MAX), NVARCHAR(MAX), VARBINARY(MAX), or XML. SQL Server 2025 needs to update internal metadata pointers and verify data consistency during the switch, which is impossible if the target filegroup is marked read-only. This typically happens in sliding window partition scenarios where older data has been archived to a read-only filegroup for storage optimization, but a switch operation (in or out) is still being attempted against that partition.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Filegroup and Partition

  • Query the error message to extract the partition number and filegroup name reported in Error 4980.
  • Run the following diagnostic query to map the table to its filegroups:
SELECT 
    ps.partition_number, 
    fg.name AS FilegroupName, 
    fg.is_read_only
FROM sys.partitions p
JOIN sys.allocation_units au ON p.partition_id = au.container_id
JOIN sys.filegroups fg ON au.data_space_id = fg.data_space_id
JOIN sys.partition_schemes ps ON ps.data_space_id = fg.data_space_id
WHERE p.object_id = OBJECT_ID('YourTableName');
  • Confirm whether the flagged filegroup is intentionally read-only (archival) or was mistakenly left in that state.

Step 2: Temporarily Set the Filegroup to Read-Write

  • If the filegroup is not meant to be permanently locked, switch it back to read-write mode to allow the metadata update:
ALTER DATABASE YourDatabaseName 
MODIFY FILEGROUP YourFilegroupName READWRITE;
  • Ensure no other active transactions are locking the filegroup before running this command, as it requires a brief schema modification lock.

Step 3: Execute the ALTER TABLE SWITCH Operation

  • Immediately re-run the original partition switch command while the filegroup is writable:
ALTER TABLE YourTableName SWITCH PARTITION 5 TO YourStagingTable PARTITION 5;
  • Verify the command completes without triggering Error 4980 or related locking timeouts.

Step 4: Revert the Filegroup to Read-Only (If Required)

  • If the filegroup serves as a long-term archive, restore the read-only flag immediately after the switch to maintain your storage tiering strategy and prevent accidental writes:
ALTER DATABASE YourDatabaseName 
MODIFY FILEGROUP YourFilegroupName READONLY;
  • Document this toggle in your maintenance runbooks, as future partition maintenance jobs will require this same two-step toggle.

Alternative or Verification Steps

  • Verify the Fix: Check the filegroup status using SELECT name, is_read_only FROM sys.filegroups; to confirm it returned to the READONLY state successfully (0 or 1) after the maintenance window closed.
  • Alternative Approach: If toggling the filegroup is not feasible due to a maintenance window restriction, consider redesigning the partition function so that LOB data for “hot” partitions resides exclusively on a PRIMARY or dedicated read-write filegroup, isolating it from the archival read-only storage entirely.

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

Troubleshooting Guide: Error 4979 – ALTER TABLE SWITCH Readonly Filegroup Failure

Why This Error Happens

This error occurs because the target or source table involved in the ALTER TABLE SWITCH operation resides in a filegroup that has been marked as READONLY, preventing SQL Server from modifying the metadata pointers required to complete the partition switch. This is common in archival or historical partitions where filegroups are intentionally locked down to prevent data drift, but it blocks maintenance operations that require metadata writes. Additionally, this can happen inadvertently if a database was restored with READ_ONLY options or if a filegroup was set to readonly during an ETL process and never reverted.

Step-by-Step Resolution Guide

Step 1: Identify the Readonly Filegroup

  • Run the following query to identify which filegroup is causing the conflict: SELECT name, is_read_only FROM sys.filegroups;
  • Cross-reference the filegroup name returned in the Error 4979 message with the results to confirm the specific filegroup requiring changes.
  • Check the table’s current partition scheme to verify which filegroup the specific partition resides on using sys.partitions and sys.destination_data_spaces.

Step 2: Temporarily Set the Filegroup to Read/Write

  • Open SQL Server Management Studio (SSMS) or a query window connected to the specific instance.
  • Execute the command to toggle the filegroup status: ALTER DATABASE [YourDatabaseName] MODIFY FILEGROUP [YourFilegroupName] READWRITE;
  • Ensure you have exclusive access or that no other active transactions are blocking this schema modification, as this requires a brief schema stability lock.

Step 3: Execute the Switch Operation

  • Re-run the original partition switch command, for example: ALTER TABLE [Staging_Table] SWITCH PARTITION 5 TO [Main_Table] PARTITION 5;
  • Verify the operation completes instantly, confirming the metadata switch (not data movement) has been processed correctly.

Step 4: Revert the Filegroup to Readonly (Optional)

  • If your data governance policy requires the filegroup to remain locked after the switch, revert the changes immediately.
  • Execute: ALTER DATABASE [YourDatabaseName] MODIFY FILEGROUP [YourFilegroupName] READONLY;
  • Confirm no other scheduled jobs (such as nightly ETL loads) are expected to write to this filegroup before locking it again.

Alternative or Verification Steps

  • Verification: Query sys.partitions post-switch to confirm the partition count and row counts have successfully moved between the staging and production tables.
  • Alternative: If you cannot alter the filegroup due to compliance restrictions, consider staging the switch on a different, writable filegroup first, and then use ALTER TABLE SWITCH once the data lands in a read/write enabled partition before archiving.

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

Troubleshooting Guide: Error 4978 — ALTER TABLE SWITCH Failed on Read-Only Filegroup

Why This Error Happens

This error occurs when SQL Server 2025 attempts to perform a partition switch operation (ALTER TABLE...SWITCH) on a partition that physically resides in a filegroup marked as read-only. Because the SWITCH operation requires metadata updates to the partition structure, SQL Server cannot write these changes if the underlying filegroup does not permit I/O modifications. This commonly happens with sliding window scenarios where older partitions have been intentionally archived to read-only filegroups for performance or compliance reasons, but a SWITCH operation was mistakenly targeted at that partition.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Filegroup and Partition

  • Run the following query to identify which filegroup is tied to the problematic partition:
  • SELECT fg.name AS FilegroupName, fg.is_read_only, p.partition_number FROM sys.filegroups fg JOIN sys.destination_data_spaces dds ON fg.data_space_id = dds.data_space_id JOIN sys.partition_schemes ps ON dds.partition_scheme_id = ps.data_space_id JOIN sys.partitions p ON p.partition_number = dds.destination_id WHERE fg.is_read_only = 1;
  • Confirm the partition number referenced in the Error 4978 message matches the output.

Step 2: Temporarily Set the Filegroup to Read-Write

  • Open SQL Server Management Studio (SSMS) or a sqlcmd session connected to the instance.
  • Execute: ALTER DATABASE [YourDatabaseName] MODIFY FILEGROUP [YourFilegroupName] READWRITE;
  • Ensure no other active transactions or reporting jobs are using the filegroup in read-only mode during this window, as this will temporarily allow writes.

Step 3: Perform the ALTER TABLE SWITCH Operation

  • Re-run the original partition switch command once the filegroup is writable:
  • ALTER TABLE [dbo].[YourTable] SWITCH PARTITION 5 TO [dbo].[YourStagingTable] PARTITION 5;
  • Monitor the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for confirmation of success.

Step 4: Revert the Filegroup to Read-Only

  • Immediately after the switch completes, restore the original read-only state to maintain your archival policy:
  • ALTER DATABASE [YourDatabaseName] MODIFY FILEGROUP [YourFilegroupName] READONLY;
  • Verify no pending transactions are open against that filegroup before reverting, using sys.dm_tran_active_transactions.

Step 5: Validate Partition Function and Scheme Alignment

  • If the error persists, check whether the partition function boundaries were recently split or merged.
  • Use sys.partition_range_values to confirm the target partition boundary matches the intended read-write filegroup mapping before attempting the switch again.

Alternative or Verification Steps

  • Verify the fix by querying sys.filegroups to confirm is_read_only = 0 during the switch window and is_read_only = 1 after reverting.
  • As an alternative, if frequent switching into this partition is required, consider redesigning the partition scheme so that the “swap” partition range always maps to a dedicated read-write filegroup, separate from your long-term read-only archive filegroups.

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

Troubleshooting Guide: Error 4977 – ALTER TABLE SWITCH Failed Due to Check Constraint on CLR Type Column

Why This Error Happens

This error occurs because SQL Server cannot validate a CHECK constraint that references a CLR (Common Language Runtime) user-defined type column during a partition switch operation. The SQL Server query optimizer cannot guarantee the constraint’s logical equivalence between the source and target tables when CLR types are involved, since CLR type comparisons are not natively understood by the relational engine the way standard data types are. As a safeguard against data integrity violations, SQL Server blocks the SWITCH operation entirely rather than risk silently moving non-compliant data into the target partition.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Constraint and Column

  • Run the following query to locate the exact constraint and CLR column causing the conflict:
  SELECT cc.name AS ConstraintName, c.name AS ColumnName, t.name AS TypeName
  FROM sys.check_constraints cc
  JOIN sys.columns c ON cc.parent_object_id = c.object_id
  JOIN sys.types t ON c.user_type_id = t.user_type_id
  WHERE t.is_assembly_type = 1 AND cc.parent_object_id = OBJECT_ID('YourTargetTable');
  • Confirm the column uses a CLR-based type (e.g., a SQLCLR UDT like geography, geometry, or a custom assembly type).

Step 2: Drop the Check Constraint Before the Switch

  • Script out the constraint definition first for safekeeping:
  EXEC sp_helpconstraint 'YourTargetTable';
  • Drop the constraint temporarily:
  ALTER TABLE YourTargetTable DROP CONSTRAINT YourConstraintName;
  • Proceed with the ALTER TABLE ... SWITCH operation as normal.

Step 3: Re-Create the Constraint Post-Switch

  • Immediately after the switch completes, re-add the constraint using WITH CHECK to re-validate data integrity:
  ALTER TABLE YourTargetTable WITH CHECK ADD CONSTRAINT YourConstraintName CHECK (YourCLRColumn.ToString() = 'ExpectedValue');
  • If performance is a concern on large tables, use WITH NOCHECK instead, then run DBCC CHECKCONSTRAINTS separately to validate asynchronously.

Step 4: Refactor the Constraint Logic (Long-Term Fix)

  • Where possible, redesign the CHECK constraint to reference a persisted computed column (a scalar, non-CLR value derived from the CLR type) instead of the CLR column directly.
  • Example: Add a computed column like IsValidRegion AS (RegionData.STIsValid()) and apply the CHECK constraint to that computed column instead, since computed scalar outputs are switch-compatible.

Alternative or Verification Steps

  • Verify the fix by re-running the original ALTER TABLE ... SWITCH statement; it should complete without raising Error 4977, and you can confirm partition metadata moved correctly via sys.partitions.
  • If dropping the constraint isn’t feasible due to compliance/audit requirements, consider using a staging table without the constraint for the switch, then apply the constraint check via a scheduled job after the switch completes.

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

Troubleshooting Guide: Error 4976 — ALTER TABLE SWITCH Failed Due to XML Column Check Constraint

Why This Error Happens

This error occurs because SQL Server 2025 disallows ALTER TABLE...SWITCH operations on tables where a check constraint exists on an XML column, since the constraint relies on XML schema collection validation that cannot be reliably verified during partition switching. The engine blocks the switch to prevent data integrity violations between the source and target partitions. This typically surfaces during partition maintenance operations on tables that use XML schema collections with enforced check constraints (such as sys.xml_schema_collection validated columns).

Step-by-Step Resolution Guide

Step 1: Identify the Offending Constraint

  • Run the following query to locate the exact check constraint referenced in the error message:
SELECT cc.name AS constraint_name, c.name AS column_name, t.name AS table_name
FROM sys.check_constraints cc
JOIN sys.columns c ON cc.parent_object_id = c.object_id AND cc.parent_column_id = c.column_id
JOIN sys.tables t ON cc.parent_object_id = t.object_id
WHERE c.system_type_id = (SELECT system_type_id FROM sys.types WHERE name = 'xml');
  • Confirm the column type is xml and note the schema collection bound to it (if any).

Step 2: Drop the Check Constraint on the Target Table

  • Before executing the SWITCH statement, temporarily drop the constraint:
ALTER TABLE dbo.YourTargetTable
DROP CONSTRAINT CK_YourConstraintName;
  • Ensure you script out the constraint definition first so it can be reapplied later.

Step 3: Perform the Partition Switch Operation

  • Re-run the original ALTER TABLE...SWITCH command once the constraint is removed:
ALTER TABLE dbo.SourceTable SWITCH PARTITION 1 TO dbo.YourTargetTable PARTITION 1;
  • Confirm the operation completes without Error 4976.

Step 4: Recreate the Check Constraint Post-Switch

  • Add the constraint back onto the table after the switch is complete, using WITH NOCHECK if you want to skip immediate re-validation on existing data:
ALTER TABLE dbo.YourTargetTable WITH NOCHECK
ADD CONSTRAINT CK_YourConstraintName CHECK (dbo.YourXmlColumn.exist('/root') = 1);
  • If data integrity is critical, omit NOCHECK to force immediate validation, though this will add processing overhead.

Step 5: Update SQL Server Maintenance Scripts

  • Modify any SQL Agent jobs or partition maintenance scripts (located typically under SQL Server Management Studio > SQL Server Agent > Jobs) to include a pre-switch step that drops XML-column constraints and a post-switch step to recreate them.
  • Store the constraint definitions in a version-controlled script file for repeatability.

Alternative or Verification Steps

  • Verify the fix by querying sys.check_constraints on the target table post-switch to confirm the constraint was successfully recreated and is enabled (is_disabled = 0).
  • As an alternative, consider refactoring the XML validation logic into an INSTEAD OF trigger rather than a check constraint, since triggers are not evaluated during partition switch operations and will not block future ALTER TABLE...SWITCH commands.

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

Troubleshooting Guide: SQL Server Error 5848 — Hot-Added CPU Notification

Why This Error Happens

This message is triggered when the underlying hardware or hypervisor performs a hot-add CPU operation on a system where SQL Server is running, which SQL Server detects and logs via its NUMA-aware scheduler. It is not actually an error condition but rather an informational event (Event ID 5848) confirming that a new physical CPU was dynamically added to a specific NUMA node and mapped to a logical CPU ID. This typically occurs in virtualized environments (Hyper-V, VMware) or on physical servers that support hot-plug CPU hardware, especially when a VM administrator increases vCPU allocation while the guest OS and SQL Server instance remain online.

Step-by-Step Resolution Guide

Step 1: Confirm the Message Is Informational, Not an Error

  • Check the SQL Server Error Log or Windows Event Viewer (Application log, source “MSSQLSERVER”) for Event ID 5848.
  • Verify the full message text includes “This is an informational message only. No user action is required.” — this confirms no corrective action is needed.
  • Cross-reference the timestamp with any recent hardware/VM configuration changes (e.g., vCPU hot-add performed by a hypervisor admin).

Step 2: Validate Hot-Add CPU Was Intentional

  • Open Hyper-V Manager or your virtualization platform’s console and check the VM settings under Processor configuration to confirm whether “Enable Processor compatibility” or hot-add CPU was deliberately enabled.
  • On Windows Server 2025 host, run the following in PowerShell to confirm current vCPU count matches expected allocation:
  Get-VM -Name "<VMName>" | Select ProcessorCount
  • If the hot-add was unauthorized or unexpected, coordinate with your infrastructure/virtualization team to confirm change management records.

Step 3: Verify SQL Server Recognizes the New CPU Correctly

  • Run the following T-SQL query to confirm SQL Server has updated its scheduler count and NUMA node mapping:
  SELECT cpu_id, scheduler_id, parent_node_id, status
  FROM sys.dm_os_schedulers
  WHERE status = 'VISIBLE ONLINE';
  • Compare the output against sys.dm_os_sys_info to ensure cpu_count matches the expected total after the hot-add:
  SELECT cpu_count, hyperthread_ratio, socket_count, numa_node_count
  FROM sys.dm_os_sys_info;

Step 4: Restart SQL Server Only If NUMA Mapping Appears Inconsistent

  • If sys.dm_os_schedulers or sys.dm_os_sys_info shows mismatched or orphaned NUMA node data, schedule a restart of the SQL Server service during a maintenance window:
  net stop MSSQLSERVER
  net start MSSQLSERVER
  • This forces SQL Server to fully re-enumerate all CPUs and NUMA nodes from scratch rather than relying on the dynamic hot-add detection logic.

Alternative or Verification Steps

  • Verify the fix: Re-run SELECT cpu_count, numa_node_count FROM sys.dm_os_sys_info; after any restart and confirm the values match the host’s current vCPU/NUMA configuration reported in Task Manager (Performance tab) or Get-VM output.
  • Alternative: If hot-add CPU events are frequent and generating log noise, consider disabling CPU hot-add in the VM’s hardware configuration (if dynamic scaling isn’t required) to reduce unnecessary Event ID 5848 entries in the SQL Server Error Log.

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

Troubleshooting Guide: SQL Server Error 5846 — CLR Execution Not Supported Under Lightweight Pooling

Why This Error Happens

This error occurs because SQL Server’s “lightweight pooling” feature uses fiber-mode scheduling instead of standard Windows threads, and the Common Language Runtime (CLR) cannot execute reliably within a fiber-mode context. When both the clr enabled and lightweight pooling server configuration options are set to 1 simultaneously, SQL Server detects this incompatibility and raises Error 5846 to prevent instability or crashes. This is a configuration conflict rather than a corruption or permissions issue, and it typically surfaces when a DBA enables CLR integration (for SQLCLR assemblies, custom functions, or triggers) on an instance that was previously tuned for high-concurrency workloads using fiber mode.

Step-by-Step Resolution Guide

Step 1: Confirm the Current Configuration State

  • Open SQL Server Management Studio (SSMS) or a query tool connected to the affected instance on Windows Server 2025 / Windows 11.
  • Run the following T-SQL to check both settings:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'lightweight pooling';
  EXEC sp_configure 'clr enabled';
  • Verify in the run_value column whether both options return 1 (enabled), which confirms the conflict.

Step 2: Disable Lightweight Pooling (Recommended Fix)

  • Since lightweight pooling (fiber mode) offers minimal benefit on modern multi-core hardware and is deprecated in newer SQL Server builds, disable it in favor of keeping CLR functional.
  • Execute:
  EXEC sp_configure 'lightweight pooling', 0;
  RECONFIGURE;
  • Note: This setting requires a full SQL Server service restart to take effect — it cannot be applied dynamically.
  • Restart the service via SQL Server Configuration Manager or by running:
  Restart-Service -Name "MSSQLSERVER" -Force

(replace MSSQLSERVER with your named instance, e.g., MSSQL$INSTANCENAME, if applicable).

Step 3: Alternative — Disable CLR Instead (If Fiber Mode Is Required)

  • If your workload genuinely depends on lightweight pooling for legacy COM+ or specific high-concurrency scenarios, disable CLR instead:
  EXEC sp_configure 'clr enabled', 0;
  RECONFIGURE;
  • This change applies immediately without a service restart, unlike the lightweight pooling setting.
  • Confirm no active SQLCLR objects (assemblies, CLR stored procedures, or CLR triggers) are in use before disabling, as they will fail post-change.

Step 4: Validate SQL Server Error Log

  • After applying either fix and restarting (if required), check the SQL Server Error Log for confirmation messages.
  • Navigate to the default log path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG (adjust version folder for SQL Server 2025).
  • Look for a clean startup with no recurrence of Error 5846 and confirm CLR or fiber-mode status messages align with your intended configuration.

Alternative or Verification Steps

  • Re-run EXEC sp_configure 'lightweight pooling'; and EXEC sp_configure 'clr enabled'; to confirm only one of the two shows run_value = 1.
  • If CLR functionality is critical and you cannot disable lightweight pooling due to a restart restriction in a production environment, schedule the restart during a maintenance window and use sp_configure with WITH OVERRIDE only as a last resort for emergency configuration changes.

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

Troubleshooting Guide: Error 5844 – “User Instances Are Not Supported in This Edition of SQL Server”

Why This Error Happens

This error occurs because the User Instance feature, which allows non-administrator users to spin up their own local SQL Server instance (commonly used with SQL Server Express for development scenarios), is not supported in Standard, Enterprise, or Evaluation editions of SQL Server 2025. The connection string for the application likely contains User Instance=True, a parameter that is only valid when connecting to SQL Server Express Edition. Since User Instances were deprecated starting with SQL Server 2012 and remain unsupported in SQL Server 2025 regardless of edition, any attempt to invoke this legacy feature will trigger Error 5844.

Step-by-Step Resolution Guide

Step 1: Identify the Connection String Source

  • Locate the application’s configuration file (e.g., web.config, app.config, or a .json connection settings file).
  • Search for the connection string parameter containing User Instance=True or User Instance=true.
  • Note the full connection string for editing in the next step.

Step 2: Remove the Deprecated “User Instance” Parameter

  • Edit the connection string to delete User Instance=True; entirely.
  • Example of a corrected connection string:
  Server=localhost\SQLEXPRESS;Database=MyDB;Trusted_Connection=True;
  • If AttachDbFilename is also present for a local .mdf file, ensure it still points to a valid, accessible path since User Instance was often used alongside local file attachment.

Step 3: Verify the SQL Server Edition Installed

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to confirm the edition:
  SELECT SERVERPROPERTY('Edition') AS Edition;
  • If the result returns Standard Edition, Enterprise Edition, or similar (not Express), confirm that your application was mistakenly configured for an Express-only feature.

Step 4: Migrate to a Supported Local Database Approach

  • If the application requires lightweight, per-user local databases, replace User Instance functionality with LocalDB (if using SQL Server Express) or provision a dedicated named instance.
  • Update the connection string to use LocalDB syntax if applicable:
  Server=(localdb)\MSSQLLocalDB;Database=MyDB;Trusted_Connection=True;
  • Restart the application pool (IIS) or application service to apply the new configuration.

Step 5: Restart SQL Server Services and Test the Connection

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart the SQL Server (MSSQLSERVER) or named instance service.
  • Re-launch the application and attempt the database connection again to confirm Error 5844 no longer appears.

Alternative or Verification Steps

  • Verify the Fix: Check the SQL Server Error Log (via SSMS → Management → SQL Server Logs) to confirm no new instances of Error 5844 are logged after the connection string update.
  • Alternative Solution: If per-user isolated databases are a hard requirement, consider installing SQL Server 2025 Express Edition on a separate development machine where User Instance behavior was historically used, or redesign the architecture to use a centrally managed instance with proper role-based permissions instead of per-user instances.

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

Troubleshooting Guide: SQL Server Error 5842 — “Too Few Worker Threads Are Specified”

Why This Error Happens

This error occurs when the max worker threads configuration value in SQL Server is manually set below the minimum threshold required by the engine to handle scheduler, CPU, and network configuration demands. SQL Server 2025 calculates a dynamic minimum based on the number of logical processors and active network protocols, and any value entered below this calculated floor will cause the instance to reject the setting at startup or during reconfiguration. This typically results from a DBA manually editing sp_configure values, a flawed automated deployment script, or a corrupted configuration value inherited during an in-place upgrade to SQL Server 2025 on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the Current Configuration Value

  • Open SQL Server Management Studio (SSMS) or sqlcmd and connect to the instance (if it allows connection) or prepare to use the Dedicated Administrator Connection (DAC) if the service fails to start.
  • Run the following query to check current settings:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max worker threads';
  • Note the config_value and run_value columns; a config_value of anything other than 0 (auto-configure) that is too low is the likely culprit.

Step 2: Reset Max Worker Threads to Auto-Configure (0)

  • If you can connect to the instance, run:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max worker threads', 0;
  RECONFIGURE;
  • Setting this value to 0 allows SQL Server 2025 to dynamically calculate the optimal thread count based on your CPU core count and network configuration, which is the Microsoft-recommended default for most workloads.
  • Restart the SQL Server (MSSQLSERVER) service via the Services console (services.msc) or via PowerShell: Restart-Service -Name MSSQLSERVER -Force.

Step 3: Start SQL Server with a Minimal Configuration (If Service Won’t Start)

  • If the service fails to start due to this error, open Command Prompt as Administrator and start SQL Server with the -f (minimal configuration) startup parameter:
  NET START MSSQLSERVER /f
  • Alternatively, add -f as a startup parameter in SQL Server Configuration Manager under SQL Server Services > Properties > Startup Parameters, then restart the service.
  • Once connected under minimal configuration, repeat Step 2 to reset the max worker threads value to 0, then remove the -f flag from Startup Parameters and restart the service normally.

Step 4: Check for Registry or Script-Based Overrides

  • Inspect any deployment automation (DSC configs, Ansible playbooks, or T-SQL deployment scripts) that may be setting max worker threads as part of post-install configuration.
  • Correct the hardcoded value in the script to either 0 or a value calculated using Microsoft’s formula: minimum threads = 512 (for 64-bit) plus additional threads based on processor count, to prevent recurrence on the next deployment.

Alternative or Verification Steps

  • After restarting the service, confirm the fix by re-running EXEC sp_configure 'max worker threads'; and checking the SQL Server Error Log (via EXEC sp_readerrorlog; or Event Viewer under Windows Logs > Application) to ensure Error 5842 no longer appears during startup.
  • If the issue persists even after setting the value to 0, verify there isn’t a conflicting Resource Governor pool configuration or an outdated registry entry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\<InstanceID>\MSSQLServer that is overriding the sp_configure value.

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

Troubleshooting Guide: SQL Server Error 5841 – Unsupported Default Full-Text Language

Why This Error Happens

Error 5841 occurs when the Language ID (LCID) configured as the default full-text language — either at the server (sp_configure 'default full-text language') or instance level — does not correspond to a language actually registered with the Full-Text Search (FTS) component. This typically happens after a SQL Server upgrade/migration where a legacy LCID is no longer mapped, or when the Full-Text Search feature was installed without its complete set of wordbreaker/language resource files. It can also occur if the sys.fulltext_languages catalog is out of sync with the installed FTS binaries due to a corrupted or incomplete installation.

Step-by-Step Resolution Guide

Step 1: Identify the Currently Configured Language ID

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to check the current server-level default:
  EXEC sp_configure 'default full-text language';
  • Cross-reference the returned LCID against supported values:
  SELECT * FROM sys.fulltext_languages;
  • If the configured LCID does not appear in this list, that confirms the mismatch causing Error 5841.

Step 2: Reset the Default Full-Text Language to a Supported Value

  • Set the default full-text language to a known-good, universally supported LCID (e.g., 1033 for English – US):
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'default full-text language', 1033;
  RECONFIGURE;
  • If the issue is scoped to a specific database or column, check and reset at that level too:
  EXEC sp_fulltext_database 'enable';
  • Validate any CREATE FULLTEXT INDEX or CREATE TABLE scripts referencing LANGUAGE arguments and update hardcoded LCIDs to supported ones.

Step 3: Repair or Reinstall the Full-Text Search Component

  • Open Control Panel > Programs > SQL Server 2025 Installation Center (or use Setup.exe from installation media).
  • Select Maintenance > Repair and choose the affected instance.
  • Ensure the Full-Text and Semantic Extractions for Search feature checkbox is selected during repair.
  • On Windows Server 2025 / Windows 11, confirm the following paths contain the expected language resource files post-repair:
  C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\FTData\
  • Restart the SQL Server (MSSQLSERVER) and SQL Full-text Filter Daemon Launcher services via services.msc.

Step 4: Restart Services and Clear Cached Configuration

  • Restart the SQL Server instance to apply the RECONFIGURE changes:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Restart the SQL Server Full-text Filter Daemon Launcher service as well, since it caches language resource mappings:
  Restart-Service -Name 'MSSQLFDLauncher' -Force
  • Clear any stale Full-Text Catalog if corruption is suspected:
  ALTER FULLTEXT CATALOG ft_catalog REBUILD;

Alternative or Verification Steps

  • Confirm the fix by re-running EXEC sp_configure 'default full-text language'; and verifying the returned LCID matches an entry in sys.fulltext_languages, then attempt to create a test full-text index without errors.
  • If the error persists after repair, consider a clean uninstall/reinstall of the Full-Text and Semantic Extractions for Search feature via the SQL Server Installation Center, ensuring the installation media matches the exact build/version of SQL Server 2025 currently installed.

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

Troubleshooting Guide: Service Broker Error 5840 – Invalid Message Forward Mode

Why This Error Happens

Error 5840 occurs when the Service Broker’s message forwarding configuration contains an invalid or unsupported value, typically caused by corrupted route metadata or an improperly configured FORWARD_MESSAGES setting at the endpoint level. This can also result from a failed SQL Server upgrade process where legacy broker configurations from an older instance did not migrate cleanly into SQL Server 2025. In some cases, manual edits to system catalogs (such as sys.routes or sys.service_broker_endpoints) introduce inconsistent state that the Broker engine cannot interpret correctly.

Step-by-Step Resolution Guide

Step 1: Verify Current Broker Endpoint Configuration

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to inspect current forwarding settings:
  SELECT name, is_message_forwarding_enabled, message_forwarding_size 
  FROM sys.service_broker_endpoints;
  • Confirm whether is_message_forwarding_enabled holds an unexpected or NULL value.

Step 2: Reset the Message Forwarding Mode

  • Disable and reconfigure the forwarding option explicitly rather than leaving it in a default/ambiguous state.
  • Execute the following T-SQL command:
  ALTER ENDPOINT [ServiceBrokerEndpoint]
  FOR SERVICE_BROKER (MESSAGE_FORWARDING = DISABLED);
  • If forwarding is required for your environment, re-enable it with explicit sizing:
  ALTER ENDPOINT [ServiceBrokerEndpoint]
  FOR SERVICE_BROKER (MESSAGE_FORWARDING = ENABLED, MESSAGE_FORWARD_SIZE = 10);

Step 3: Rebuild Corrupted Route Entries

  • Navigate to the affected database and drop any routes referencing invalid forwarding states.
  DROP ROUTE [BrokenRouteName];
  • Recreate the route with correct parameters pointing to the valid broker instance:
  CREATE ROUTE [FixedRoute]
  WITH SERVICE_NAME = '//YourApp/Service',
  ADDRESS = 'TCP://ServerName:4022';

Step 4: Restart the SQL Server Service

  • On Windows Server 2025, open Services.msc.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Right-click and select Restart to clear any cached broker session states tied to the invalid forward mode.

Alternative or Verification Steps

  • To verify the fix, re-run the sys.service_broker_endpoints query from Step 1 and confirm is_message_forwarding_enabled now returns a valid boolean (0 or 1) rather than an inconsistent value; also check the SQL Server Error Log for the absence of further Error 5840 entries after restart.
  • If the error persists, consider dropping and fully recreating the Service Broker endpoint from scratch using CREATE ENDPOINT, as this bypasses any residual corrupted configuration that ALTER commands cannot overwrite.

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

Troubleshooting Guide: SQL Server Error 5839 – Service Broker Message Forward Store Size Cannot Be Set to 0

Why This Error Happens

Error 5839 occurs when Service Broker attempts to configure the message forwarding store with a size value of 0, which SQL Server 2025 treats as an invalid configuration because the forwarding store requires a minimum allocation to buffer in-transit messages. This typically happens due to a misconfigured sp_configure setting, a corrupted msdb or Service Broker system catalog, or an automated deployment script that incorrectly passes a zero value during instance provisioning. It can also surface after an in-place upgrade from an older SQL Server version where legacy Service Broker settings were not properly migrated.

Step-by-Step Resolution Guide

Step 1: Verify Current Service Broker Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run SELECT * FROM sys.databases WHERE is_broker_enabled = 1; to confirm Service Broker status.
  • Check the forwarding store setting using EXEC sp_configure 'Service Broker forward message size';.

Step 2: Correct the Forward Message Store Size Value

  • Run the following T-SQL to reset the value to a supported minimum (never 0):
  • EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
  • EXEC sp_configure 'Service Broker forward message size', 4096; RECONFIGURE;
  • Restart the SQL Server service via services.msc or run NET STOP MSSQLSERVER && NET START MSSQLSERVER in an elevated Command Prompt on Windows Server 2025.

Step 3: Inspect and Repair Deployment or Configuration Scripts

  • Locate any PowerShell or DSC (Desired State Configuration) scripts under C:\SQLConfig\ or your CI/CD pipeline repository that provision the instance.
  • Search for parameters like -BrokerForwardSize 0 or similar JSON/XML config keys and update them to a non-zero value (e.g., 4096 or higher).
  • Redeploy the configuration using Invoke-SqlCmd or your orchestration tool to ensure the corrected value persists.

Step 4: Rebuild the Service Broker GUID (If Corruption Is Suspected)

  • Run ALTER DATABASE [YourDatabase] SET NEW_BROKER; to reset a corrupted broker identifier.
  • Follow with ALTER DATABASE [YourDatabase] SET ENABLE_BROKER; to reactivate messaging.
  • Confirm no orphaned conversation endpoints remain using SELECT * FROM sys.conversation_endpoints;.

Alternative or Verification Steps

  • After applying changes, run SELECT * FROM sys.configurations WHERE name = 'Service Broker forward message size'; and confirm the value_in_use column shows a non-zero number.
  • If the error persists, restore the msdb database from a known-good backup taken prior to the misconfiguration, then reapply Step 2 before bringing the instance back online.

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

Troubleshooting Guide: SQL Server Error 5838 — Invalid Service Broker Connection Authentication Value

Why This Error Happens

This error occurs when the Service Broker endpoint receives a connection authentication value that does not match any of the supported authentication mechanisms (NTLM, Kerberos, or Certificate-based authentication). It is typically caused by a mismatch between the AUTHENTICATION clause defined on the Service Broker endpoint and the actual security context being used by the connecting instance, often introduced after a certificate rotation, domain trust change, or manual endpoint reconfiguration. Corrupted or expired certificates bound to the endpoint, as well as inconsistent Windows authentication protocols between Windows Server 2025 and Windows 11 clients, can also trigger this value mismatch.

Step-by-Step Resolution Guide

Step 1: Verify the Service Broker Endpoint Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run SELECT * FROM sys.service_broker_endpoints; to inspect the current AUTHENTICATION and ENCRYPTION settings.
  • Confirm whether the endpoint is set to WINDOWS NEGOTIATE, WINDOWS KERBEROS, WINDOWS NTLM, or CERTIFICATE, and check if this matches the expected setting on the partner instance.

Step 2: Realign Authentication Settings Between Instances

  • On both the initiator and target instances, run the following to reset authentication to a consistent value:
  ALTER ENDPOINT [ServiceBrokerEndpoint]
  FOR SERVICE_BROKER (AUTHENTICATION = WINDOWS NEGOTIATE, ENCRYPTION = REQUIRED ALGORITHM AES);
  • Ensure both servers are using the same domain trust relationship if using Windows-based authentication.
  • If using certificates, verify they have not expired via SELECT name, expiry_date FROM sys.certificates;.

Step 3: Re-issue or Re-bind Certificates (If Using Certificate Authentication)

  • Navigate to the certificate store via certlm.msc on Windows Server 2025 to confirm the certificate used by Service Broker is present and valid.
  • Drop and recreate the certificate binding using:
  CREATE CERTIFICATE ServiceBrokerCert
  WITH SUBJECT = 'Service Broker Certificate';
  • Re-bind the new certificate to the endpoint and restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 4: Restart the Service Broker and Clear Cached Sessions

  • Run ALTER DATABASE [YourDB] SET NEW_BROKER; only if conversations are non-critical, as this resets the Broker GUID.
  • Alternatively, use ALTER DATABASE [YourDB] SET ENABLE_BROKER; followed by a service restart to clear stale authentication tokens.
  • Check the SQL Server error log (ERRORLOG in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for confirmation that Error 5838 no longer appears.

Alternative or Verification Steps

  • Verify the fix by querying SELECT * FROM sys.conversation_endpoints; to confirm conversations are establishing successfully without authentication failures.
  • If the issue persists, temporarily set the endpoint AUTHENTICATION = WINDOWS without specifying NTLM/Kerberos explicitly, allowing SQL Server to negotiate automatically between Windows Server 2025 and Windows 11 clients.

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

Troubleshooting Guide: SQL Server Error 5837 – Service Broker Listen Port Cannot Be Dynamic

Why This Error Happens

This error occurs when the ALTER DATABASE SET ENABLE_BROKER or CREATE ENDPOINT statement attempts to configure the Service Broker listener using a port value set to 0 or outside the valid TCP port range. SQL Server 2025 strictly requires a static port between 1024 and 32767 for Service Broker communication, as dynamic port allocation (used by protocols like named pipes) is not supported for this endpoint type. This typically happens due to a misconfigured connection string, a leftover default value from a migration script, or manual editing of endpoint metadata that introduced an invalid port number.

Step-by-Step Resolution Guide

Step 1: Identify the Current Broker Endpoint Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the target instance on your Windows Server 2025 host.
  • Run the following query to inspect existing endpoints:
  SELECT name, port, protocol_desc, state_desc 
  FROM sys.tcp_endpoints;
  • Look for any NULL, 0, or out-of-range values in the port column associated with the SERVICE_BROKER protocol.

Step 2: Drop the Invalid Endpoint

  • If an invalid or dynamically-assigned endpoint exists, remove it before recreating it correctly.
  • Execute the following, replacing EndpointName with the actual name retrieved in Step 1:
  DROP ENDPOINT EndpointName;
  • Confirm no errors are returned and that the endpoint no longer appears in sys.tcp_endpoints.

Step 3: Recreate the Endpoint with a Valid Static Port

  • Choose an unused port within the 1024–32767 range (e.g., 4022, a common default for Service Broker).
  • Run the creation script explicitly defining the port:
  CREATE ENDPOINT ServiceBrokerEndpoint
  STATE = STARTED
  AS TCP (LISTENER_PORT = 4022)
  FOR SERVICE_BROKER (AUTHENTICATION = WINDOWS NEGOTIATE, ENCRYPTION = REQUIRED);
  • Ensure this port is not already bound by another application; check using netstat -ano | findstr "4022" in an elevated Command Prompt on Windows Server 2025.

Step 4: Open the Port in Windows Defender Firewall

  • Navigate to Windows Defender Firewall with Advanced Security on the server.
  • Create a new Inbound Rule for the specific TCP port (e.g., 4022) to allow SQL Server Service Broker traffic.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated terminal.

Alternative or Verification Steps

  • Verify the fix by re-running SELECT * FROM sys.tcp_endpoints WHERE protocol = 'TCP'; and confirming the port column shows a static, valid integer (e.g., 4022) rather than NULL or 0.
  • If the error persists, check for duplicate Broker configurations across linked databases using SELECT name, is_broker_enabled FROM sys.databases; and ensure no conflicting GUID mismatches exist between the service_broker_guid values.

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

Troubleshooting Guide: Error 5836 – Lightweight Pooling Not Supported

Why This Error Happens

This error occurs when the lightweight pooling configuration option is enabled via sp_configure, but the running instance of SQL Server 2025 does not support fiber-mode scheduling. Lightweight pooling has been deprecated and is restricted on most modern editions and platforms, meaning the setting is effectively obsolete even though it may still appear as a configurable option. Attempting to apply this value triggers Error 5836 because the SQL Server engine rejects fiber-based scheduling on current Windows Server 2025/Windows 11 architectures.

Step-by-Step Resolution Guide

Step 1: Verify Current Configuration Value

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run EXEC sp_configure 'lightweight pooling'; to check if the value is set to 1.
  • Confirm the run_value column reflects an active (non-zero) setting.

Step 2: Disable Lightweight Pooling

  • Execute the following T-SQL commands:
  • EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
  • EXEC sp_configure 'lightweight pooling', 0;
  • RECONFIGURE;
  • This resets the scheduling mode back to standard thread-based scheduling, which is fully supported.

Step 3: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER) or the named instance service.
  • Right-click and select Restart to apply the configuration change.
  • Alternatively, run net stop MSSQLSERVER && net start MSSQLSERVER from an elevated Command Prompt.

Step 4: Check SQL Server Error Logs

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Confirm no further references to Error 5836 appear after the restart.
  • Look for the startup message confirming standard thread-mode scheduling is active.

Step 5: Audit Deployment Scripts and Legacy Configurations

  • Search any automated deployment or configuration scripts (PowerShell, DSC, or T-SQL baseline scripts) for references to lightweight pooling.
  • Remove or comment out any legacy configuration commands tied to fiber-mode scheduling to prevent recurrence during future deployments.

Alternative or Verification Steps

  • Run SELECT * FROM sys.configurations WHERE name = 'lightweight pooling'; and confirm both value and value_in_use are set to 0.
  • If the error persists after disabling the setting, check for third-party monitoring tools or legacy maintenance plans that may be resetting the configuration value on a schedule.

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

Troubleshooting Guide: SQL Server Error 5835 — “Failed to start CPUs with the mask 0x%lx on the system”

Why This Error Happens

This error occurs when SQL Server 2025 attempts to bind its scheduler threads to specific CPUs during startup based on an affinity mask configuration (via sp_configure or ALTER SERVER CONFIGURATION), but the Windows Server 2025 / Windows 11 kernel reports that those logical processors are unavailable, disabled, or do not exist on the current hardware/VM topology. This commonly happens after a VM is reconfigured with fewer vCPUs, a physical CPU is swapped, a NUMA node is removed, or a BIOS/hypervisor setting restricts the processor group exposed to the OS, leaving a stale affinity mask in the SQL Server configuration that references non-existent CPUs. It can also arise from corrupted or mismatched soft-NUMA configuration files referenced by startup parameters.

Step-by-Step Resolution Guide

Step 1: Identify the Current CPU Topology

  • Open an elevated PowerShell prompt and run Get-WmiObject Win32_Processor | Select-Object NumberOfCores, NumberOfLogicalProcessors.
  • Cross-check this against Task Manager > Performance > CPU to confirm the actual number of logical processors exposed to the OS.
  • Compare this to the CPU affinity mask currently configured in SQL Server.

Step 2: Reset the SQL Server Affinity Mask

  • Start SQL Server in minimal configuration mode by launching it from the command line with the -f flag, e.g., sqlservr.exe -f -c from the C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn directory.
  • Once connected via SQLCMD or SSMS, run EXEC sp_configure 'show advanced options', 1; RECONFIGURE; followed by EXEC sp_configure 'affinity mask', 0; RECONFIGURE; to clear the stale mask.
  • Alternatively, reset affinity via ALTER SERVER CONFIGURATION SET PROCESS AFFINITY CPU = AUTO; to let SQL Server auto-detect available CPUs.

Step 3: Validate Soft-NUMA and Startup Parameters

  • Check the SQL Server error log directory (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log) for any -K or NUMA-related startup trace flags that may reference removed CPU nodes.
  • Open SQL Server Configuration Manager, navigate to SQL Server Services > right-click the instance > Properties > Startup Parameters, and remove any manually added affinity or NUMA startup flags that no longer match hardware.
  • Restart the SQL Server service normally (not in -f mode) via Restart-Service MSSQLSERVER -Force.

Step 4: Update Hypervisor/VM CPU Allocation (If Applicable)

  • If running on Hyper-V or another hypervisor, confirm the VM’s assigned vCPU count matches what SQL Server expects by checking VM Settings > Processor in Hyper-V Manager.
  • Increase vCPU count or re-enable disabled cores if the mask requires more processors than currently assigned.

Alternative or Verification Steps

  • After restarting the service, verify success by checking the SQL Server error log for the message “SQL Server detected X sockets with Y cores per socket” without any accompanying 5835 error.
  • If the issue persists, run DBCC CPU (or query sys.dm_os_schedulers for status = 'VISIBLE ONLINE') to confirm all expected schedulers are active and match the physical/virtual CPU count.

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

Troubleshooting Guide: SQL Server Error 5834 — Affinity Mask Conflict

Why This Error Happens

This error occurs because SQL Server 2025 detects an overlap between the CPUs assigned via affinity mask (or affinity64 mask) and the CPUs assigned via affinity I/O mask. Each CPU core on the host can only be dedicated to one function at a time—either general query processing or dedicated I/O operations—and SQL Server enforces mutual exclusivity between these two pools. This typically happens after a manual edit to sp_configure values or when a server is migrated/reconfigured with a different CPU core count than the original affinity script was written for.

Step-by-Step Resolution Guide

Step 1: Identify the Current Affinity Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a new query window.
  • Run EXEC sp_configure 'show advanced options', 1; RECONFIGURE; to unlock advanced settings.
  • Run EXEC sp_configure 'affinity mask'; and EXEC sp_configure 'affinity I/O mask'; to view the current bitmask values (or check affinity64 mask / affinity64 I/O mask on 64-bit NUMA systems).
  • Cross-reference these decimal/binary values against Task Manager’s Performance > CPU tab on Windows Server 2025 to map which logical processors are currently assigned to which pool.

Step 2: Recalculate Non-Overlapping CPU Masks

  • Convert both masks to binary and manually check for bit overlap (e.g., if CPU 0–3 are in affinity mask, they cannot also appear in affinity I/O mask).
  • Use the GUI method instead of manual bitmasking: open SSMS > Right-click Server > Properties > Processors tab.
  • In the Processors tab, uncheck any CPU under “Automatically set processor affinity mask for all processors” and manually assign distinct checkboxes for “Processor Affinity” vs. “I/O Affinity” columns, ensuring no single CPU row has both boxes checked.

Step 3: Apply Configuration via T-SQL (Alternative to GUI)

  • If the GUI fails to save due to the same conflict, reset both values to 0 first to clear the conflicting state:
  • Run EXEC sp_configure 'affinity mask', 0; RECONFIGURE;
  • Run EXEC sp_configure 'affinity I/O mask', 0; RECONFIGURE;
  • Re-apply the corrected, non-overlapping decimal values calculated in Step 2 for each setting individually, running RECONFIGURE after each command.

Step 4: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025.
  • Locate SQL Server (MSSQLSERVER) or the specific named instance.
  • Right-click and select Restart to apply the new kernel-level affinity bindings, as these changes do not take effect dynamically without a service restart in most configurations.

Alternative or Verification Steps

  • Verify the Fix: After the restart, check the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for the startup message confirming “affinity mask” and “I/O affinity mask” values were loaded without a 5834 error.
  • Alternative Fix: If manual calculation is too complex, reset both affinity mask and affinity I/O mask to 0 via T-SQL and leave “Automatically set processor affinity mask for all processors” checked in the GUI; this allows SQL Server to dynamically manage core allocation without manual mask conflicts.

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

Troubleshooting Guide: SQL Server Error 5833 – Affinity Mask Exceeds Licensed CPU Limit

Why This Error Happens

This error occurs because the ALTER SERVER CONFIGURATION command is attempting to set a CPU affinity mask that includes processor cores beyond what your specific SQL Server 2025 edition is licensed to use. Editions like Standard or Web have hard-coded limits on the number of cores/sockets they can utilize, regardless of how many physical cores exist on the Windows Server 2025 host. This typically happens after a hardware upgrade, a VM resource increase, or a migration where the server now has more logical processors than the SQL Server license tier supports.

Step-by-Step Resolution Guide

Step 1: Verify Your SQL Server Edition and Core Limits

  • Run SELECT SERVERPROPERTY('Edition') in SSMS to confirm your current edition.
  • Cross-reference this with Microsoft’s official “Compute capacity limits by edition” documentation for SQL Server 2025.
  • Note the maximum number of cores/sockets allowed (e.g., Standard Edition is typically capped at the lesser of 4 sockets or 24 cores).

Step 2: Check the Current Affinity Configuration

  • Open a new query window in SQL Server Management Studio (SSMS).
  • Execute EXEC sp_configure 'show advanced options', 1; RECONFIGURE; followed by EXEC sp_configure 'affinity mask'; to view legacy settings.
  • For modern setups, check sys.dm_os_nodes or Server Properties > Processors tab in SSMS to see which CPUs are currently flagged for use.

Step 3: Reset the Affinity Mask to Auto

  • If the mask was manually set incorrectly, reset it to allow SQL Server to auto-manage based on license limits.
  • Run the following T-SQL command to clear the restrictive mask:
  ALTER SERVER CONFIGURATION SET PROCESS AFFINITY MASK = AUTO;
  • Alternatively, right-click the Server instance in SSMS, go to Properties > Processors, and ensure “Automatically set processor affinity mask for all processors” is checked.

Step 4: Manually Align Affinity with Licensed Cores

  • If you need specific cores active (rather than “Auto”), ensure the CPU mask selects a number of cores equal to or less than your license limit.
  • Use the GUI method: In SSMS Server Properties > Processors, manually check boxes only up to your licensed limit (e.g., if licensed for 16 cores, do not check core 17 or higher).
  • Avoid using the deprecated sp_configure 'affinity mask' for systems with more than 32 logical processors, as it uses a bitmask that cannot address higher core counts; use ALTER SERVER CONFIGURATION instead.

Step 5: Restart the SQL Server Service

  • Navigate to SQL Server Configuration Manager.
  • Right-click the SQL Server (MSSQLSERVER) service and select Restart to apply the new affinity configuration.
  • Monitor the SQL Server Error Log immediately following the restart to ensure Error 5833 does not reappear.

Alternative or Verification Steps

  • Verification: After the restart, query SELECT cpu_id, scheduler_id, is_online FROM sys.dm_os_schedulers WHERE status = 'VISIBLE ONLINE'; to confirm the number of active schedulers matches your licensed core count.
  • Alternative Fix: If you require more cores than your current edition allows, you must either upgrade to SQL Server 2025 Enterprise Edition or use Windows Server 2025 Hyper-V to partition the VM/Host to match the exact core count of your SQL license before reapplying the affinity settings.

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

Why This Error Happens

Error 5832 occurs when the affinity mask or affinity64 mask value configured in SQL Server’s startup settings references CPU bits that do not exist on the current hardware or virtual machine configuration. This commonly happens after migrating a database instance to a new host, restoring a configuration from a backup, or reducing the number of vCPUs assigned to a VM without updating SQL Server’s sp_configure settings. Since SQL Server 2025 validates the affinity mask against the actual CPU topology reported by Windows Server 2025 at startup, any mismatch between the configured bitmask and the physical/logical processor count triggers this fatal configuration error.

Step-by-Step Resolution Guide

Step 1: Boot SQL Server in Minimal Configuration Mode

  • Since the affinity mask error can prevent the SQL Server service from starting normally, you must start it in a safe state to regain access.
  • Open an elevated Command Prompt and stop the SQL Server service: NET STOP MSSQLSERVER
  • Start the instance using the -f (minimal configuration) startup parameter: NET START MSSQLSERVER /f

Step 2: Reset the Affinity Mask via SQLCMD

  • Connect to the instance using SQLCMD since SSMS may be unable to initialize advanced options in minimal mode.
  • Run the following commands to reset the affinity values to zero (default, OS-managed scheduling):
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'affinity mask', 0;
EXEC sp_configure 'affinity64 mask', 0;
RECONFIGURE;
  • This clears the manual CPU binding, allowing SQL Server to use all available schedulers detected by the OS.

Step 3: Verify the Current CPU Topology

  • Before re-applying any manual affinity settings, confirm how many logical processors Windows Server 2025 actually exposes to the instance.
  • Run Get-WmiObject Win32_Processor | Select-Object NumberOfLogicalProcessors in PowerShell, or check sys.dm_os_schedulers in SQL Server.
  • If you are running inside a Hyper-V or Azure VM, verify the vCPU count assigned in the VM settings matches what the guest OS reports.

Step 4: Re-apply Affinity Settings Correctly (Optional)

  • If specific CPU affinity is required for licensing or NUMA alignment, use the ALTER SERVER CONFIGURATION command instead of the deprecated bitmask method, as it is less prone to mismatch errors.
  • Example: ALTER SERVER CONFIGURATION SET PROCESS AFFINITY CPU = AUTO;
  • Restart the SQL Server service normally once the correct values are set: NET STOP MSSQLSERVER followed by NET START MSSQLSERVER

Alternative or Verification Steps

  • Verify the fix by checking the SQL Server Error Log (ERRORLOG file in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for successful service startup without Error 5832 reappearing.
  • If the issue persists after resetting the mask, check for Group Policy or BIOS/Hyper-V settings that may be dynamically altering the number of logical processors exposed to the OS during reboot cycles.

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

Troubleshooting Guide: SQL Server Error 5829 – “The Specified User Options Value Is Invalid”

Why This Error Happens

Error 5829 occurs when the sp_configure ‘user options’ value submitted falls outside the valid range (0–32767) or represents an invalid combination of bitmask flags for setting default query processing options. This typically results from an administrator manually calculating an incorrect bitmask sum when attempting to set multiple SET options (such as ANSI_WARNINGS, ARITHABORT, or NOCOUNT) globally at the server level. It can also occur due to corrupted or manually edited registry values associated with the SQL Server instance configuration.

Step-by-Step Resolution Guide

Step 1: Verify the Current User Options Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025 or Windows 11.
  • Run the following query to check the current value:
EXEC sp_configure 'user options';
  • Confirm the run_value and config_value columns to see if an out-of-range number (e.g., anything above 32767) is present.

Step 2: Recalculate the Correct Bitmask Value

  • Reference the official bitmask table for SET options (e.g., DISABLEDEFCNSTCHK = 1, IMPLICITTRANSACTIONS = 2, CURSORCLOSEONCOMMIT = 4, ANSIWARNINGS = 8, etc.).
  • Manually add only the specific decimal values for the options you want active.
  • Ensure the total sum does not exceed 32767, as this is the maximum allowable integer for this configuration.

Step 3: Apply the Corrected Configuration Value

  • Execute the corrected value using the following T-SQL syntax (replace 4096 with your calculated value):
EXEC sp_configure 'user options', 4096;
RECONFIGURE;
  • If the error persists immediately after running this, restart the SQL Server (MSSQLSERVER) service via the Services console (services.msc) or SQL Server Configuration Manager to force the engine to re-read the configuration cache.

Step 4: Check for Registry Corruption (If Error Persists)

  • Navigate to the registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\[Instance_Name]\MSSQLServer.
  • Look for the UserConnect or related configuration keys that might contain a non-numeric or invalid data type.
  • If corruption is found, it is safer to reset the specific configuration value via T-SQL (Step 3) rather than editing the registry directly, as SQL Server 2025 may overwrite manual registry edits upon service restart.

Alternative or Verification Steps

  • Verification: After restarting the service, run EXEC sp_configure 'user options'; again. The run_value should now match the config_value you set, and no error should populate in the SQL Server Error Log (viewable via SSMS Object Explorer > Management > SQL Server Logs).
  • Alternative: If the global server-level setting continues to throw errors, reset it to the default value of 0 and instead manage SET options at the connection string or application level (e.g., via ADO.NET or ODBC connection properties) to avoid overriding server-wide session defaults.

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

Troubleshooting Guide: SQL Server Error 5831

Why This Error Happens

This error occurs when the min server memory configuration value is set higher than the max server memory value in SQL Server’s memory configuration, violating the engine’s internal validation rule. This typically happens due to manual misconfiguration via sp_configure, an automated deployment script applying values in the wrong order, or a failed migration process that left memory settings in an inconsistent state. SQL Server 2025 strictly enforces that minimum memory cannot exceed maximum memory, and will reject the configuration change or fail to start the memory manager correctly until corrected.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Configuration Values

  • Open SQL Server Management Studio (SSMS) or connect via sqlcmd on your Windows Server 2025 / Windows 11 instance.
  • Run the following query to inspect current settings:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'min server memory';
  EXEC sp_configure 'max server memory';
  • Note the current values (config_value and run_value) for both parameters.

Step 2: Correct the Max Server Memory Value First

  • Always set max server memory before adjusting min server memory to avoid the conflict.
  • Run:
  EXEC sp_configure 'max server memory', 8192; -- example: 8 GB in MB
  RECONFIGURE WITH OVERRIDE;
  • Ensure this value is appropriate for your physical RAM, leaving enough headroom for the OS (typically 2-4 GB reserved for Windows Server 2025).

Step 3: Set Min Server Memory to a Valid Value

  • Set min server memory to a value less than or equal to the corrected max server memory.
  • Run:
  EXEC sp_configure 'min server memory', 2048; -- example: 2 GB in MB
  RECONFIGURE WITH OVERRIDE;
  • Confirm the change applied without triggering Error 5831.

Step 4: Restart the SQL Server Service (If Required)

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Right-click and select Restart to ensure the new memory configuration is fully applied at the engine level.

Alternative or Verification Steps

  • Re-run EXEC sp_configure 'min server memory'; and EXEC sp_configure 'max server memory'; to confirm min is now less than or equal to max in both config_value and run_value columns.
  • If the error persists after reconfiguration, check the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for conflicting startup parameters or use sp_configure with explicit values in a single transaction to avoid race conditions during automated deployment scripts.

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

Troubleshooting Guide: SQL Server Error 5810 — Invalid Fill Factor Value

Why This Error Happens

Error 5810 occurs when a FILLFACTOR value specified in an index creation or rebuild statement falls outside the valid range of 0 to 100. This typically happens due to a typo, a corrupted or auto-generated deployment script, or a dynamic SQL statement that calculates the fill factor incorrectly (resulting in a negative number or a value exceeding 100). In some cases, this also surfaces when legacy maintenance scripts or third-party tools pass an uninitialized or null variable that defaults to an out-of-range integer.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Check SQL Server Management Studio (SSMS) Query Results pane or SQL Server Agent Job History for the exact T-SQL statement that triggered Error 5810.
  • Look specifically for CREATE INDEX, ALTER INDEX, or sp_configure 'fill factor' statements.
  • Run the following to check the current server-wide default:
  EXEC sp_configure 'fill factor';

Step 2: Correct the Fill Factor Value in the Script

  • Open the script in SSMS or Azure Data Studio and locate the WITH (FILLFACTOR = n) clause.
  • Ensure n is an integer between 0 and 100 (inclusive). Common valid examples: 90, 80, 0 (which behaves like 100).
  • Fix dynamic SQL variables that calculate fill factor, ensuring no arithmetic operation can produce a negative or >100 result:
  DECLARE @FillFactor INT = 90;
  IF @FillFactor NOT BETWEEN 0 AND 100
      SET @FillFactor = 90; -- fallback safeguard

Step 3: Reset the Server-Level Default (If Applicable)

  • If the error originates from a server configuration rather than a single script, reset the instance-wide default fill factor using SSMS or PowerShell on Windows Server 2025/Windows 11.
  • Run the following in a query window connected via SSMS:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'fill factor', 90;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or Restart-Service -Name MSSQLSERVER in an elevated PowerShell session for changes to take full effect.

Step 4: Validate Index Maintenance Jobs

  • Review any SQL Server Agent jobs or Ola Hallengren maintenance solution scripts that rebuild indexes with custom fill factor logic.
  • Correct any @FillFactor parameter passed into stored procedures like IndexOptimize to ensure it stays within the 0–100 bound.

Alternative or Verification Steps

  • Re-run the corrected CREATE INDEX or ALTER INDEX statement and confirm it completes without Error 5810; check sys.indexes to verify the fill_factor column reflects the intended value.
  • If the issue persists in automated jobs, add input validation/sanitization logic in the calling application or ETL tool before the value reaches SQL Server, preventing out-of-range values from ever being submitted.

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

Troubleshooting Guide: SQL Server Error 5812 – “You do not have permission to run the RECONFIGURE statement”

Why This Error Happens

This error occurs because the login attempting to execute RECONFIGURE lacks the ALTER SETTINGS server-level permission, which is required alongside sp_configure changes. By default, only members of the sysadmin or serveradmin fixed server roles hold this permission, so standard users or application service accounts are denied. This commonly surfaces when a deployment script, DBA tool, or automated job runs under a low-privilege account during server configuration changes.

Step-by-Step Resolution Guide

Step 1: Verify the Current Login’s Role Membership

  • Open SQL Server Management Studio (SSMS) and connect using an account with sysadmin privileges.
  • Run the following query to check role membership for the problematic login:
  SELECT sp.name, r.name AS role_name
  FROM sys.server_principals sp
  JOIN sys.server_role_members rm ON sp.principal_id = rm.member_principal_id
  JOIN sys.server_principals r ON rm.role_principal_id = r.principal_id
  WHERE sp.name = 'YourLoginName';
  • Confirm whether sysadmin or serveradmin is missing from the results.

Step 2: Grant the ALTER SETTINGS Permission

  • Instead of adding the user to a full admin role, grant only the specific permission needed:
  USE master;
  GRANT ALTER SETTINGS TO [YourLoginName];
  • This follows the principle of least privilege while resolving the RECONFIGURE error.
  • Alternatively, if broader administrative rights are appropriate for this account, add it to the serveradmin role:
  ALTER SERVER ROLE serveradmin ADD MEMBER [YourLoginName];

Step 3: Re-run the Configuration Command

  • Log back in (or reconnect) as the affected user to refresh the session’s security token.
  • Execute the original command sequence again, for example:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  • Check the Messages tab in SSMS for confirmation that the command completed without permission errors.

Step 4: Check for Policy-Based Management Restrictions

  • On Windows Server 2025 environments using Group Policy or SQL Server Policy-Based Management (PBM), confirm no server-level policy is blocking ALTER SETTINGS grants.
  • Navigate to SSMS > Management > Policy Management > Policies and review any policies tagged “Surface Area Configuration.”

Alternative or Verification Steps

  • Verify the fix by logging in as the previously failing account and running EXEC sp_configure 'remote access', 1; RECONFIGURE; — it should complete without Error 5812.
  • If permissions still fail after granting ALTER SETTINGS, check for a Contained Database context or a Deny ALTER SETTINGS rule explicitly set at the login level using SELECT * FROM sys.server_permissions WHERE state = 'D';.

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

Troubleshooting Guide: SQL Server Error 5828 — “User Connections Are Limited to %d”

Why This Error Happens

This error occurs when SQL Server 2025 reaches the configured ceiling for the user connections setting, which caps the maximum number of simultaneous user connections the instance will accept. It can happen because an administrator manually set a low, fixed value in sp_configure, or because the system calculated a default limit based on insufficient memory or stale configuration metadata left over from a migration. In some cases, orphaned connections from application pools or linked server sessions that are not properly closed can also exhaust the available connection slots faster than expected.

Step-by-Step Resolution Guide

Step 1: Check the Current User Connections Configuration

  • Open SQL Server Management Studio (SSMS) or sqlcmd and run:
  • EXEC sp_configure 'user connections';
  • Review the run_value column — a value of 0 means “unlimited” (dynamically allocated), while any positive number is a hard cap.
  • Note the current limit reported in the Error 5828 message to compare against this output.

Step 2: Reset or Increase the User Connections Limit

  • To allow SQL Server to manage connections dynamically, run:
  • EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
  • EXEC sp_configure 'user connections', 0;
  • RECONFIGURE;
  • If a specific higher limit is required instead of 0, replace it with an appropriate integer (e.g., 500), based on expected concurrent workloads.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (Windows Server 2025/Windows 11) for the change to take effect.

Step 3: Identify and Terminate Orphaned Connections

  • Run sp_who2 or query sys.dm_exec_sessions to identify idle or orphaned sessions consuming connection slots.
  • SELECT session_id, login_name, status, last_request_end_time FROM sys.dm_exec_sessions WHERE is_user_process = 1;
  • Use KILL <session_id>; to manually terminate stale or zombie sessions if the application layer is not releasing them properly.

Step 4: Audit Application Connection Pooling Settings

  • Check connection strings in IIS, .NET apps, or middleware for Max Pool Size settings that may be set unnecessarily high.
  • Ensure connection pooling is enabled (Pooling=True) to reuse connections efficiently instead of opening new ones per request.
  • Adjust Min Pool Size and Max Pool Size values to align with the SQL Server’s actual user connections limit.

Alternative or Verification Steps

  • Verify the fix by monitoring active connections in real time using SELECT COUNT(*) FROM sys.dm_exec_connections; and confirming it stays below the configured threshold during peak load.
  • If Error 5828 persists after reconfiguration, check Windows Server 2025 Event Viewer (Applications and Services Logs > MSSQLSERVER) for memory pressure warnings, as insufficient RAM can also cause SQL Server to silently cap connections regardless of the sp_configure value.

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

Troubleshooting Guide: SQL Server Error 5805 – “Too Few Locks Specified”

Why This Error Happens

This error occurs when the locks configuration option in SQL Server has been manually set to a value below the minimum threshold required for the engine to start and operate safely. SQL Server 2025 requires a baseline number of lock structures to manage concurrency, and setting this value too low (often during an attempt to manually tune memory) prevents the Lock Manager from initializing. This is typically caused by a misconfigured sp_configure 'locks' value or a legacy startup parameter carried over from a server migration or restore.

Step-by-Step Resolution Guide

Step 1: Verify the Current Locks Configuration

  • Open SQL Server Management Studio (SSMS) or connect via sqlcmd using the Dedicated Administrator Connection (DAC) if the instance won’t start normally.
  • Run the following query to check the current setting: EXEC sp_configure 'locks';
  • Note the config_value and run_value columns; a non-zero value below the system minimum (typically 5000) is the likely culprit.

Step 2: Reset the Locks Value to Dynamic (Default)

  • Execute the following T-SQL commands to restore dynamic lock management, which is the recommended setting for SQL Server 2025:
  • EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
  • EXEC sp_configure 'locks', 0; RECONFIGURE;
  • Setting the value to 0 allows SQL Server to dynamically allocate and de-allocate lock memory as needed, preventing manual threshold errors.

Step 3: Start the Instance Using Minimal Configuration (If Service Won’t Start)

  • If the SQL Server service fails to start due to this error, open the Services app (services.msc) on Windows Server 2025/Windows 11.
  • Locate the SQL Server service, right-click, and navigate to Properties.
  • Temporarily add the startup parameter -f (minimal configuration) in the Startup Parameters tab to force the engine to bypass the invalid locks setting.
  • Start the service, apply the fix detailed in Step 2, remove the -f flag, and restart the service normally.

Step 4: Check for Registry or Startup Script Overrides

  • Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLServer\Parameters in the Windows Registry.
  • Inspect for any legacy -T trace flags or startup scripts that might be re-applying an old locks value on every restart.
  • Remove or correct any deprecated parameters found in this key.

Alternative or Verification Steps

  • Verify the Fix: Restart the SQL Server service via services.msc or net start MSSQLSERVER and confirm the instance comes online without Error 5805 appearing in the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Alternative Solution: If the configuration continues to revert, restore the master database from a known-good backup taken prior to the configuration change, as a corrupted master database can sometimes cause configuration values to stick incorrectly.

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

Troubleshooting Guide: SQL Server Error 5807 – Recovery Interval Exceeds Recommended Threshold

Why This Error Happens

This error occurs because the recovery interval (min) server configuration option has been set to a value that exceeds Microsoft’s recommended safe threshold, typically triggered when an administrator attempts to manually extend checkpoint intervals to reduce I/O overhead. SQL Server 2025 enforces this soft limit by default because excessively long recovery intervals can dramatically increase database startup and crash recovery time, risking extended downtime. The engine blocks the change via standard RECONFIGURE as a safety guardrail, requiring explicit override intent from the administrator.

Step-by-Step Resolution Guide

Step 1: Verify the Current Recovery Interval Setting

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check current configuration values:
  EXEC sp_configure 'recovery interval';
  • Confirm whether the config_value exceeds the recommended range (values above 60 minutes typically trigger this warning).

Step 2: Decide Between Reverting or Overriding the Setting

  • If the high value was unintentional, reset it to a safer default (0 for automatic management, or a value under 60):
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'recovery interval', 0;
  RECONFIGURE;
  • If the extended interval is intentional (e.g., for a specific workload reducing checkpoint frequency), proceed to Step 3 to force the configuration.

Step 3: Apply the Override Using RECONFIGURE WITH OVERRIDE

  • Execute the following T-SQL block to force the setting despite the warning:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'recovery interval', <desired_value>;
  RECONFIGURE WITH OVERRIDE;
  • Replace <desired_value> with your intended minute value (e.g., 90 or 120).
  • Restart the SQL Server service via Windows Services (services.msc) or PowerShell to ensure the change is fully applied:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Review SQL Server Error Logs for Confirmation

  • Navigate to the default log path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Search for configuration change entries confirming the new recovery interval value was accepted without further errors.

Alternative or Verification Steps

  • Run EXEC sp_configure 'recovery interval'; again post-restart and confirm the run_value column matches your intended setting, indicating the override was successfully applied.
  • If performance issues arise from extended recovery intervals (e.g., slow crash recovery during testing), consider reverting to the default value of 0, which allows SQL Server to auto-manage checkpoint frequency based on workload.

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

Troubleshooting Guide: SQL Server Error 5808 – “Ad Hoc Update to System Catalogs Is Not Supported”

Why This Error Happens

This error occurs when an application, script, or administrator attempts to directly modify SQL Server’s system catalog tables (such as sys.sysobjects, sys.syscolumns, or other internal metadata tables) using direct INSERT, UPDATE, or DELETE statements. Microsoft SQL Server 2025 deliberately blocks this behavior because direct manipulation of system catalogs can corrupt database metadata, break internal consistency checks, and lead to unrecoverable database states. This typically happens when legacy scripts written for older SQL Server versions (pre-2005) are run on modern instances, or when the allow updates configuration option is mistakenly referenced in automation scripts.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Review the SQL Server error log or Extended Events session to capture the exact T-SQL statement that triggered Error 5808.
  • Check if the query directly references system tables like sys.sysdatabases, sys.sysobjects, or sys.syscolumns.
  • Command to check recent errors: EXEC sp_readerrorlog 0, 1, 'Error: 5808';

Step 2: Replace Direct Catalog Edits with Supported DDL/Catalog Views

  • Rewrite any direct UPDATE/INSERT/DELETE statements against system tables using supported system stored procedures (e.g., sp_rename, sp_configure, ALTER DATABASE, ALTER TABLE).
  • Use read-only catalog views (sys.tables, sys.columns, sys.objects) for querying metadata instead of legacy system tables.
  • If metadata correction is required, use DBCC CHECKDB with appropriate repair options rather than manual edits.

Step 3: Verify the allow updates Configuration Is Disabled (Default in 2025)

  • Open SQL Server Management Studio (SSMS) or a query window and run:
  • EXEC sp_configure 'allow updates', 0;
  • RECONFIGURE WITH OVERRIDE;
  • Confirm this value is set to 0, as SQL Server 2025 ignores this setting for catalog protection by design, but legacy scripts may still attempt to toggle it.
  • Restart the SQL Server service via services.msc or Get-Service MSSQLSERVER | Restart-Service in PowerShell if changes were made.

Step 4: Audit and Update Legacy Automation Scripts

  • Search deployment scripts, SSIS packages, and scheduled jobs (via SQL Server Agent) for references to system table names.
  • Update third-party tools or custom DBA scripts to use DMVs (sys.dm_*) and catalog views instead of direct table access.
  • Document and version-control the corrected scripts to prevent recurrence.

Alternative or Verification Steps

  • To verify the fix, re-run the original script or job in a test environment and confirm it completes without raising Error 5808 in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • If the error persists and originates from a third-party application, contact the vendor for an updated version compatible with SQL Server 2025, as direct catalog access was deprecated in favor of catalog views starting with SQL Server 2005 and is fully enforced in 2025.

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

Why This Error Happens

Error 5703 is technically an informational message rather than a critical failure, triggered when the SQL Server Database Engine switches the session or server-wide default language setting. This typically occurs due to a mismatch between the client application’s regional settings and the server’s default language configuration, or because a login’s default language property differs from master.sys.syslanguages. While not inherently destructive, frequent triggering of this message in high-transaction environments can indicate configuration drift that leads to unnecessary plan recompilations.

Step-by-Step Resolution Guide

Step 1: Verify the Current Server Default Language

  • Open SQL Server Management Studio (SSMS) and connect to the Windows Server 2025 instance.
  • Run the following T-SQL query to check the current configuration:
  EXEC sp_configure 'default language';
  • Note the run_value; if it does not match your organizational standard (e.g., 0 for us_english), proceed to Step 2.

Step 2: Align Login-Specific Language Settings

  • Navigate to Security > Logins in SSMS Object Explorer.
  • Right-click the specific login reporting the error and select Properties.
  • Under the General tab, check the Default language dropdown.
  • Ensure this matches the language pack installed on the Windows Server 2025 OS layer (Control Panel > Region > Administrative > Language for non-Unicode programs).

Step 3: Update Server-Wide Configuration via T-SQL

  • If the issue stems from a server-wide misconfiguration rather than a single user, execute the following to reset the default language ID (0 = us_english):
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'default language', 0;
  RECONFIGURE WITH OVERRIDE;
  • Restart the SQL Server (MSSQLSERVER) service via the Services console (services.msc) or SQL Server Configuration Manager to apply the engine-level changes.

Step 4: Check for Regional Settings Conflicts in Windows 11/Server 2025

  • Open Settings > Time & Language > Language & Region.
  • Verify that the “Windows display language” does not conflict with the SQL Server collation settings established during installation.
  • If a conflict exists, you may need to reinstall the specific Language Pack for SQL Server 2025 to ensure dictionary and error message files align.

Alternative or Verification Steps

  • Verify the Fix: Query the SQL Server Error Log via EXEC sp_readerrorlog; after a new connection attempt. If the environment is stable, the “Changed language setting” message should cease appearing for standard connections, or appear only once per distinct session as expected (not continuously).
  • Alternative Solution: If the message persists due to a specific application (like a reporting tool) forcing a language change via connection string, update the application’s connection string to explicitly exclude the Language parameter, forcing it to inherit the server default instead.

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

Troubleshooting Guide: SQL Server Error 5803 — “Unknown Configuration (id = %d) Encountered in sys.configurations”

Why This Error Happens

This error typically occurs when the sys.configurations system catalog becomes out of sync with the internal configuration metadata table maintained by the SQL Server engine, often due to an incomplete upgrade or patch installation on SQL Server 2025. It can also arise from a corrupted master database, where configuration IDs referenced internally no longer match the expected schema definitions. In some cases, manual edits to configuration values via unsupported trace flags or direct registry manipulation on Windows Server 2025 can introduce orphaned or unrecognized configuration IDs.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Patch Level

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; to confirm the current build number.
  • Compare this against the latest Cumulative Update (CU) for SQL Server 2025 listed on the Microsoft Update Catalog.
  • If the instance is mid-upgrade or on a hotfix build, apply the latest CU package to ensure sys.configurations metadata is fully reconciled.

Step 2: Rebuild the Configuration Metadata Cache

  • Stop the SQL Server service via services.msc or run NET STOP MSSQLSERVER from an elevated Command Prompt.
  • Restart the instance using the -f (minimal configuration) startup parameter to force SQL Server to rebuild internal configuration structures.
  • Once started, run RECONFIGURE WITH OVERRIDE; followed by EXEC sp_configure; to confirm all configuration IDs now resolve correctly.

Step 3: Check for master Database Corruption

  • Run DBCC CHECKDB('master') WITH NO_INFOMSGS, ALL_ERRORMSGS; to scan for corruption in system tables.
  • If corruption is detected, restore the master database from a known-good backup using RESTORE DATABASE master FROM DISK = 'C:\Backup\master.bak' WITH REPLACE; in single-user mode (sqlservr.exe -m).
  • If no backup exists, rebuild system databases using the SQL Server 2025 installation media via Setup.exe /ACTION=REBUILDDATABASE.

Step 4: Clear Orphaned Trace Flags or Custom Configuration Entries

  • Review the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for any custom startup trace flags tied to the unknown configuration ID.
  • Remove unsupported trace flags from SQL Server Configuration Manager under SQL Server Services > Startup Parameters.
  • Restart the SQL Server service normally and re-check sys.configurations for consistency.

Alternative or Verification Steps

  • Run SELECT * FROM sys.configurations WHERE configuration_id = <id>; using the specific ID from the error message to confirm it now returns a valid, recognized row.
  • If the error persists after patching and a master database rebuild, open a Microsoft Support (CSS) case and provide the full ERRORLOG along with SELECT * FROM sys.dm_server_registry; output for deeper diagnostic analysis.