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

Troubleshooting Guide: SQL Server Error 4071 (XP Callback Failure in INSERT-EXEC)

Why This Error Happens

This error occurs because SQL Server restricts extended stored procedures executed inside an INSERT...EXEC statement to returning only a single result set—no print messages, error messages, or output parameters are permitted through the XP callback interface. The conflict typically arises when a legacy extended procedure (such as a custom XP or xp_cmdshell-style wrapper) attempts to send informational messages via srv_message or similar ODS API calls while its output is simultaneously being captured by the INSERT...EXEC construct. This is a protocol-level limitation enforced by the SQL Server Open Data Services (ODS) layer, not a permissions or connectivity issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Extended Procedure and Query

  • Capture the exact query text using Extended Events (sqlserver.error_reported filtered on Error = 4071) or by reviewing the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Note the extended procedure name referenced in the error message (the %.*ls placeholder will resolve to the actual XP name, e.g., xp_myCustomProc).
  • Confirm whether the call is wrapped in INSERT INTO #TempTable EXEC xp_myCustomProc.

Step 2: Refactor the Code to Avoid INSERT-EXEC with XPs

  • Rewrite the extended procedure call to execute standalone (without INSERT...EXEC), and instead have the XP write directly to a table using an internal SQLExecDirect/ODBC call from within the C/C++ XP code if you control its source.
  • If you do not control the XP source, modify the calling T-SQL batch to capture output using OLE Automation Procedures (sp_OACreate) or a CLR Table-Valued Function instead of INSERT...EXEC.
  • Example safe pattern:
  EXEC xp_myCustomProc;
  -- Avoid: INSERT INTO #Temp EXEC xp_myCustomProc;

Step 3: Update or Patch the Extended Procedure DLL

  • Check the vendor or internal development team for an updated build of the XP DLL that suppresses srv_message calls when invoked in a result-set-only context.
  • Locate the DLL under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and verify version/timestamp against the vendor’s latest release.
  • Replace the DLL, restart the SQL Server (MSSQLSERVER) service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER, and re-test.

Step 4: Enable Trace Flag for Diagnostic Logging (Optional)

  • Add Trace Flag 3621 or enable verbose XP logging temporarily via SQL Server Configuration Manager under Startup Parameters to capture more context on which callback (print, error, or message) triggered the failure.
  • Remove the trace flag once root cause is confirmed, as it adds overhead.

Step 5: Migrate Away from Legacy Extended Procedures

  • Evaluate replacing the extended procedure entirely with a CLR Integration stored procedure, which natively supports structured result sets without ODS callback restrictions.
  • Enable CLR integration if not already active:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;

Alternative or Verification Steps

  • Re-run the original query outside of INSERT...EXEC (standalone EXEC) to confirm the XP executes cleanly and the 4071 error does not reproduce.
  • If immediate remediation isn’t possible, wrap the XP call in a stored procedure that uses SET NOCOUNT ON and suppresses PRINT/RAISERROR statements internally, then validate via SQL Server Profiler/Extended Events that no error-class messages are emitted during the INSERT...EXEC execution.

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

Troubleshooting Guide: SQL Server Error 4070 – “More Than 255 Columns Specified in the COMPUTE Clause”

Why This Error Happens

This error occurs because Transact-SQL enforces a hard limit of 255 columns within a single COMPUTE or COMPUTE BY clause, and your query attempts to exceed that threshold. It is typically caused by dynamically generated SQL, legacy reporting scripts, or ORM-generated queries that loop through table columns programmatically without accounting for this restriction. Since COMPUTE is a deprecated feature in modern SQL Server versions (including SQL Server 2025), this limitation is rigidly enforced and will not be increased in future updates.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Extended Events session for the exact query text that triggered Error 4070.
  • Use SQL Server Management Studio (SSMS) 2025 to run the query manually and confirm the column count in the COMPUTE clause.
  • Look for dynamically generated SELECT * statements combined with COMPUTE SUM, COMPUTE AVG, or similar aggregate functions.

Step 2: Refactor the Query Using Modern T-SQL Syntax

  • Replace COMPUTE and COMPUTE BY with GROUP BY combined with ROLLUP, CUBE, or GROUPING SETS for aggregate calculations.
  • Example rewrite:
  • Old: SELECT * FROM Sales COMPUTE SUM(Amount)
  • New: SELECT *, SUM(Amount) OVER() AS TotalAmount FROM Sales
  • Use Window Functions (OVER(), PARTITION BY) as a direct, high-performance replacement for COMPUTE behavior.

Step 3: Update Application Code and Stored Procedures

  • Search all stored procedures using the built-in query:
  • SELECT * FROM sys.sql_modules WHERE definition LIKE '%COMPUTE%'
  • Update any ORM mappings (Entity Framework, Dapper) or reporting tools (SSRS) that may generate COMPUTE clauses automatically.
  • Deploy the updated stored procedures via SQL Server Management Studio or Azure Data Studio.

Step 4: Restart the SQL Server Service (If Cached Execution Plans Persist)

  • Open Services.msc on Windows Server 2025.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Right-click and select Restart to clear cached execution plans that may still reference the old query structure.

Alternative or Verification Steps

  • Run DBCC FREEPROCCACHE in SSMS to ensure no stale execution plans referencing COMPUTE remain in memory, then re-execute the corrected query to confirm Error 4070 no longer appears.
  • If refactoring is not immediately feasible, temporarily split the query into multiple smaller COMPUTE statements, each processing fewer than 255 columns, as a short-term workaround until the code is modernized.

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

Why This Error Happens

Error 4069 occurs when a stored procedure terminates execution before it can assign a value to a declared OUTPUT parameter, causing SQL Server to return NULL instead of the expected result. This is typically triggered by an unhandled exception, a RAISERROR/THROW statement firing mid-procedure, or a RETURN statement being hit prematurely due to faulty conditional logic. It can also occur if the calling application’s connection is reset (via CONTEXT_INFO or session state changes) while the batch is still executing on SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Review the Stored Procedure Logic

  • Open the procedure definition in SQL Server Management Studio (SSMS) using sp_helptext 'YourProcedureName';
  • Check every IF/ELSE branch to confirm the OUTPUT parameter is assigned a value (e.g., SET @OutParam = @Value;) before any RETURN statement is reached.
  • Pay close attention to TRY...CATCH blocks, as an error in the TRY block often skips the assignment logic entirely.

Step 2: Implement Default Value Initialization

  • At the very top of the stored procedure, immediately after the parameter declaration, initialize the output parameter to a safe default (e.g., SET @OutParam = 0; or SET @OutParam = '';).
  • This prevents a NULL value from propagating if an unexpected code path or early exit occurs later in the script.

Step 3: Check for Premature Connection Termination

  • Open Windows Server Manager or Event Viewer on Windows Server 2025 and navigate to Applications and Services Logs > Microsoft > SQL Server.
  • Look for correlating timeout errors or killed sessions (SPID) that align with the timestamp of the 4069 error.
  • If using a .NET or ODBC driver, verify the CommandTimeout property in the connection string is set higher than the expected execution time of the stored procedure to prevent the client from cutting the connection early.

Step 4: Validate CATCH Block Handling

  • Modify the CATCH block to explicitly set the output parameter to NULL or a specific error code (e.g., -1) before re-throwing the error.
  • Use the following syntax inside the CATCH block to ensure a value is always returned:
  SET @OutParam = -1;
  THROW;

Alternative or Verification Steps

  • Verification: Execute the stored procedure manually in SSMS using a DECLARE and EXEC block, then run PRINT @OutParam; immediately after execution to confirm a non-NULL value is returned under normal and error-forced conditions.
  • Alternative: If modifying the procedure is not immediately possible, update the client-side application code (C#/Java) to check for DBNull.Value on the parameter object before processing the result, preventing the application from crashing while you schedule a permanent SQL fix.

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

Troubleshooting Guide: Error 4068 – “sp_resetconnection was sent as part of a remote procedure call (RPC) batch”

Why This Error Happens

This error occurs when a client driver (such as an outdated ODBC or OLE DB provider) attempts to bundle the internal sp_resetconnection call within the same RPC batch as a user-defined stored procedure call, which SQL Server 2025’s stricter protocol parser now rejects. It is typically triggered by legacy connection pooling logic in older client libraries that have not been updated to align with the TDS (Tabular Data Stream) protocol changes introduced in this release. Additionally, this can surface when middleware or connection pooling software reuses a connection improperly, sending a reset command alongside a batched procedure call rather than as a standalone operation.

Step-by-Step Resolution Guide

Step 1: Update Client Drivers and Connectivity Components

  • Navigate to the application server and check the installed version of msodbcsql.msi or Microsoft.Data.SqlClient via Control Panel > Programs and Features.
  • Download and install the latest Microsoft ODBC Driver (18.5 or higher) or update the NuGet package Microsoft.Data.SqlClient to version 6.0+ in your application project.
  • Restart the application pool or service referencing the driver (iisreset if applicable).

Step 2: Disable Connection Pooling Temporarily to Isolate the Issue

  • Open your application’s connection string configuration file (e.g., web.config, app.config, or appsettings.json).
  • Add or modify the parameter: Pooling=False; to test if the issue persists without pooled connections reusing the reset command improperly.
  • Monitor SQL Server logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for recurrence of Error 4068.

Step 3: Apply the Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Configuration Manager and confirm the current build number via SELECT @@VERSION; in SQL Server Management Studio (SSMS).
  • Visit the Microsoft Update Catalog and download the latest Cumulative Update (CU) package for SQL Server 2025.
  • Run the installer as Administrator and follow the prompts to patch the instance, then restart the SQL Server (MSSQLSERVER) service via services.msc.

Step 4: Review and Correct Application-Level RPC Batching Logic

  • Inspect the application source code or stored procedure call wrapper for instances where sp_executesql or raw RPC calls are manually concatenated with reset logic.
  • Ensure that calls to stored procedures use parameterized SqlCommand objects with CommandType.StoredProcedure rather than raw batched SQL strings.
  • Remove any custom connection-reset wrapper code that manually injects sp_resetconnection into a batch.

Alternative or Verification Steps

  • To verify the fix, run a load test using SQL Server Profiler or Extended Events to capture RPC:Completed events and confirm sp_resetconnection no longer appears bundled with user procedure calls.
  • If the error persists after driver and CU updates, as a temporary workaround, configure the application’s connection pool to set Connection Lifetime=0 and Max Pool Size to a lower value to reduce aggressive connection reuse cycles.

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

Troubleshooting Guide: SQL Server Error 4067 — CLR Type Serialization Failed (Invalid Cookie)

Why This Error Happens

This error typically occurs when a CLR user-defined type (UDT) or user-defined aggregate becomes corrupted or mismatched due to an incomplete assembly update, a version mismatch between the serialized binary data and the registered CLR type metadata, or improper ALTER ASSEMBLY operations that did not fully synchronize type definitions. It can also happen if the assembly was deployed with PERMISSION_SET = UNSAFE or EXTERNAL_ACCESS without properly registering the native serialization format, causing SQL Server to reject the data cookie during deserialization. In some cases, this is triggered by database migration or restoration from an older SQL Server version where the CLR type binary layout is incompatible with SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration is Properly Enabled

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

Step 2: Rebuild and Redeploy the CLR Assembly

  • Drop the affected assembly and any dependent types:
  DROP TYPE IF EXISTS dbo.YourCLRType;
  DROP ASSEMBLY IF EXISTS YourAssemblyName;
  • Rebuild the .dll from source using Visual Studio 2022/2025 targeting the correct .NET Framework/CLR version supported by SQL Server 2025.
  • Redeploy the assembly from a trusted local path, e.g.:
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Recreate the CLR type:
  CREATE TYPE dbo.YourCLRType
  EXTERNAL NAME YourAssemblyName.[YourCLRType];

Step 3: Check for Version Mismatches After Migration or Restore

  • If the database was migrated or restored from an older SQL Server version, confirm the assembly binary matches the current CLR hosting version in Windows Server 2025.
  • Use the following query to inspect assembly metadata:
  SELECT * FROM sys.assemblies;
  SELECT * FROM sys.assembly_types;
  • If mismatched, drop and redeploy the assembly using Step 2 instead of relying on the restored binary.

Step 4: Validate Windows and SQL Server Patch Level

  • Confirm Windows Server 2025 / Windows 11 has the latest cumulative updates installed via Settings > Windows Update.
  • Confirm SQL Server 2025 is patched to the latest Cumulative Update (CU) using:
  SELECT @@VERSION;
  • Apply any pending CUs from the official Microsoft Download Center, as CLR serialization bugs are frequently addressed in these updates.

Alternative or Verification Steps

  • After redeployment, run a test query that inserts and retrieves data using the CLR type (e.g., SELECT CAST(... AS dbo.YourCLRType)) to confirm serialization/deserialization completes without Error 4067.
  • If the error persists, as a fallback, export the affected table data to a native SQL type (e.g., VARBINARY or NVARCHAR), drop the CLR type entirely, and rebuild the column using plain SQL types to bypass CLR serialization altogether.

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

Why This Error Happens

Error 4065 occurs when a client application attempts to execute a procedure or function through the Open Data Services (ODS) layer that SQL Server does not recognize as a valid remote procedure call. This typically happens when a legacy extended stored procedure (xp_) or system procedure has been deprecated, renamed, or is being invoked with an incorrect calling convention from an ODBC/OLE DB driver. It can also surface when a third-party or custom application uses outdated driver libraries that attempt to call internal SQL Server procedures no longer exposed in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Procedure Call

  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact procedure name substituted into '%.*ls'.
  • Run SELECT * FROM sys.sysmessages WHERE error = 4065; to confirm the message template and correlate it with the Event Viewer entry under Windows Logs > Application.
  • Cross-reference the procedure name against sys.objects to see if it still exists: SELECT name FROM sys.objects WHERE name = '<procedure_name>';

Step 2: Update Client Drivers and Connection Strings

  • Open ODBC Data Source Administrator (search odbcad32.exe on Windows Server 2025 / Windows 11) and verify the driver version is ODBC Driver 18 for SQL Server or later.
  • Update any legacy OLE DB provider (SQLOLEDB) references in connection strings to MSOLEDBSQL19.
  • Restart the dependent application pool or service in IIS Manager or Services.msc after updating the driver.

Step 3: Validate Extended Stored Procedure Permissions

  • Confirm the login has EXECUTE permission: GRANT EXECUTE ON <procedure_name> TO [DOMAIN\User];
  • If the procedure is a custom extended stored procedure (xp_), ensure its DLL is still registered under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and re-register it using sp_addextendedproc.
  • If the DLL is missing or corrupted, reinstall the component from the original vendor package.

Step 4: Enable Trace Flags for Deeper Diagnostics

  • Start SQL Server with trace flag 3656 to capture more verbose ODS call stack information:
  DBCC TRACEON (3656, -1);
  • Reproduce the error and review the enhanced log output in SQL Server Configuration Manager > SQL Server Logs.

Alternative or Verification Steps

  • Run DBCC TRACESTATUS(-1); to confirm active trace flags, then re-run the original application request to verify the error no longer appears in the SQL Server Error Log.
  • If the issue persists, use SQL Server Profiler (or Extended Events in SSMS) to capture the exact RPC call and compare it against Microsoft’s current list of supported system/extended stored procedures for SQL Server 2025, replacing any deprecated calls with their modern T-SQL equivalents.

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

Troubleshooting Guide: SQL Server Error 4066 — Type IDs Larger Than 65535

Why This Error Happens

This error occurs when SQL Server 2025 attempts to send metadata for types (such as user-defined types, table types, or system types with extended IDs) whose internal Type ID exceeds 65535 to a client driver that only understands the legacy TDS (Tabular Data Stream) protocol used by SQL Server 2000 or earlier. Because older client libraries (such as outdated versions of SQL Native Client, MDAC, or legacy ODBC/OLE DB drivers) allocate only a 16-bit field for Type IDs, they cannot parse the larger ID space introduced in modern SQL Server versions. This is fundamentally a protocol/client-compatibility mismatch rather than a server-side configuration defect.

Step-by-Step Resolution Guide

Step 1: Identify the Outdated Client Driver

  • Check the connection string or application configuration (ODBC DSN, OLE DB provider, or ADO connection) to determine which driver version is being used.
  • Run the following query on the server to capture client details from recent connections:
  SELECT session_id, client_interface_name, client_version, program_name
  FROM sys.dm_exec_sessions
  WHERE is_user_process = 1;
  • Look specifically for client_version values indicating SQL Server 2000 (version 8.x) or earlier.

Step 2: Upgrade the Client Connectivity Component

  • On Windows Server 2025 / Windows 11, download and install the latest Microsoft OLE DB Driver for SQL Server or ODBC Driver 18+ for SQL Server from the official Microsoft Download Center.
  • Uninstall legacy components via Control Panel > Programs > Programs and Features, specifically remove:
  • “Microsoft SQL Server Native Client”
  • “Microsoft Data Access Components (MDAC)” remnants if present.
  • Reinstall the application’s connectivity layer pointing to the updated driver.

Step 3: Update the Application’s Connection String

  • Modify the DSN or connection string to explicitly reference the new provider, for example:
  Provider=MSOLEDBSQL19;Server=YourServerName;Database=YourDB;Trusted_Connection=yes;
  • Avoid using deprecated provider strings like SQLOLEDB or SQLNCLI, as these trigger legacy TDS negotiation.

Step 4: Restrict or Isolate Legacy Type Usage (If Upgrade Isn’t Possible)

  • If the client absolutely cannot be upgraded, avoid using data types or features that generate Type IDs beyond the legacy range (e.g., CLR user-defined types, newer system types, or large table-valued parameter type definitions).
  • Create a compatibility view or stored procedure that casts/returns only basic legacy-safe types (e.g., INT, VARCHAR, DATETIME) to that specific client application.

Step 5: Restart SQL Services and Validate Connectivity

  • Restart the SQL Server service via:
  net stop MSSQLSERVER && net start MSSQLSERVER
  • Re-run the client application to confirm Error 4066 no longer appears in the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).

Alternative or Verification Steps

  • Verify the Fix: Reconnect using the updated client driver and execute a query touching the previously failing type; confirm no Error 4066 appears in sys.dm_exec_connections session logs.
  • Alternative Workaround: If legacy software cannot be replaced, deploy a middleware/API layer (e.g., a REST or gRPC service) between the old client and SQL Server 2025 so the legacy application never directly negotiates TDS with the new type system.

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

Troubleshooting Guide: SQL Server Error 4064 — “Cannot Open User Default Database. Login Failed.”

Why This Error Happens

This error occurs when a SQL Server login’s default database is either offline, dropped, corrupted, or the login no longer has valid access permissions to it. Windows Server 2025 and Windows 11 environments are particularly sensitive to this issue after in-place OS upgrades, where SQL Server service accounts may lose mapped permissions during the migration. Additionally, this can happen if the database was detached, renamed, or restored under a different name without updating the login’s default database property.

Step-by-Step Resolution Guide

Step 1: Identify the Login’s Default Database

  • Open SQL Server Management Studio (SSMS) using the SQLCMD mode or connect via sqlcmd -S servername -E -d master since the default database connection will fail otherwise.
  • Run the following query to check which database is causing the conflict:
  SELECT name, default_database_name FROM sys.server_principals WHERE name = 'YourLoginName';
  • Confirm whether the referenced database exists and is online by checking sys.databases.

Step 2: Reset the Default Database to Master

  • Execute the following T-SQL command to temporarily redirect the login to the master database, restoring login capability:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = [master];
  • This bypasses the immediate login failure and allows administrative access to diagnose the original target database.
  • Verify the change took effect by re-running the query from Step 1.

Step 3: Repair or Restore the Target Database

  • Navigate to the SQL Server Configuration Manager and check if the database files (.mdf/.ldf) are present in the expected directory, typically located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • If the database shows as “Suspect” or “Offline” in SSMS, attempt to bring it online using:
  ALTER DATABASE [YourDatabaseName] SET ONLINE;
  • If corruption is suspected, run DBCC CHECKDB('YourDatabaseName') to assess the extent of the damage before considering a restore from backup.

Step 4: Validate Windows Server 2025 Permissions

  • Open Services.msc and ensure the SQL Server (MSSQLSERVER) service account has not been reset to a default profile during a Windows Update or Server Core transition.
  • Confirm the service account has “Log on as a service” rights via secpol.msc under Local Policies > User Rights Assignment.
  • Restart the SQL Server service to apply any permission changes.

Alternative or Verification Steps

  • Verification: Attempt to log in via SSMS using the specific login credentials; if successful, run SELECT DB_NAME(); to confirm the session is landing in the correct default database.
  • Alternative Fix: If the original database cannot be recovered, create a new database with the same schema requirements and reassign it as the default using ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = [NewDatabaseName]; to restore user access immediately while data recovery continues in the background.

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

Troubleshooting Guide: SQL Server Error 4063 – “Cannot Open Database”

Why This Error Happens

This error occurs when a login’s default database (or a database explicitly requested in the connection string) is either offline, dropped, renamed, or the login no longer has the necessary permissions to access it. SQL Server falls back to the user’s configured default database instead of throwing a hard connection failure. In many cases, this is caused by a database restore/detach operation that didn’t update the login mappings, or a mismatch between the login’s sid and the database user’s sid after a migration.

Step-by-Step Resolution Guide

Step 1: Verify the Database State and Existence

  • Open SQL Server Management Studio (SSMS) and connect to the instance via the Database Engine.
  • Run the following query to check if the database exists and its current status:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the state_desc shows OFFLINE, RESTORING, or SUSPECT, this confirms the database is inaccessible rather than a permissions issue.

Step 2: Check and Fix Login Permissions

  • Identify the login causing the issue and its currently mapped default database:
  SELECT name, default_database_name FROM sys.sql_logins WHERE name = 'YourLoginName';
  • If permissions are missing, grant access to the database explicitly:
  USE YourDatabaseName;
  CREATE USER [YourLoginName] FOR LOGIN [YourLoginName];
  • On Windows Server 2025, ensure the SQL Server service account (visible in Services.msc) has not lost NTFS permissions on the .mdf and .ldf files located typically in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.

Step 3: Reset the Login’s Default Database

  • If the mapped default database was deleted or renamed, reset it to a valid database (like master) to prevent future login failures:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = [master];
  • This ensures that even if the target application database is temporarily down, the login can still authenticate into the instance.

Step 4: Repair Orphaned Users (SID Mismatch)

  • If the database was restored from a different server, the User SID might not match the Login SID, causing an “orphaned user” state. Run this to check:
  EXEC sp_change_users_login 'Report';
  • Fix the mismatch by remapping the user to the login:
  EXEC sp_change_users_login 'Auto_Fix', 'YourLoginName';

Alternative or Verification Steps

  • Verification: Attempt to connect to the specific database again using SSMS or sqlcmd -S ServerName -d YourDatabaseName. If the connection succeeds without reverting to master, the issue is resolved.
  • Alternative Fix: If the database remains corrupted, restore the specific database from the latest valid .bak file via SSMS > Restore Database, ensuring the “Overwrite the existing database (WITH REPLACE)” option is checked if the file is in a suspect state.

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

Troubleshooting Guide: SQL Server Error 4062 – “Cannot Open User Default Database”

Why This Error Happens

This error occurs when a login’s default database, as defined in sys.server_principals, is either offline, dropped, renamed, or restored under a different name, making it unreachable at connection time. It can also happen if the login lacks the necessary CONNECT permission on that specific database following a permissions change, security audit, or migration. SQL Server 2025 correctly falls back to master to prevent a hard connection failure, but any application expecting to land in the original user database will fail silently or throw application-level errors.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic Login and Its Default Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance using an admin account (or via sqlcmd if GUI access is blocked).
  • Run the following query to check the configured default database for the affected login:
  SELECT name, default_database_name 
  FROM sys.server_principals 
  WHERE name = 'YourLoginName';
  • Cross-reference the result against sys.databases to confirm whether the database exists and is ONLINE.

Step 2: Verify Database State and Availability

  • Check if the database is offline, suspect, or in recovery pending mode:
  SELECT name, state_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If the state is OFFLINE, bring it back online:
  ALTER DATABASE YourDatabaseName SET ONLINE;
  • If the database was renamed or dropped during a migration (common after moving to Windows Server 2025 clusters), confirm the correct current name and update records accordingly.

Step 3: Reset the Login’s Default Database

  • If the original database is permanently gone or renamed, repoint the login to a valid, existing database:
  ALTER LOGIN YourLoginName WITH DEFAULT_DATABASE = YourCorrectDatabaseName;
  • Ensure the login has at least CONNECT permissions on the new default database:
  USE YourCorrectDatabaseName;
  GO
  CREATE USER YourLoginName FOR LOGIN YourLoginName;
  GO

Step 4: Validate Permissions on the Target Database

  • Confirm the login is mapped correctly to a database user and has not been orphaned (a common issue after restoring a .bak file from a different server).
  • Run sp_change_users_login 'Report' (legacy instances) or use the newer orphaned user remediation script in SQL Server 2025 to repair broken SIDs:
  ALTER USER YourLoginName WITH LOGIN = YourLoginName;

Step 5: Restart the SQL Server Service (If Caching Persists)

  • If changes do not take effect immediately due to cached login sessions, restart the SQL Server service via Services.msc on Windows Server 2025/Windows 11.
  • Alternatively, use PowerShell to restart the specific instance:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Verify the Fix: Attempt to log in using SSMS or your application connection string and confirm you land directly in the intended database rather than master. You can also check the active session context using SELECT DB_NAME(); immediately after connecting.
  • Alternative Fix: If the original database cannot be recovered, update the application’s connection string to explicitly specify the Initial Catalog (database name) parameter, bypassing reliance on the server-side default database setting entirely.

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

Troubleshooting Guide: SQL Server Error 4061

Why This Error Happens

Error 4061 occurs when the login attempting to connect does not have an associated database it can access, either because the requested database is offline, has been dropped, or is still recovering. This also commonly happens when the login’s configured “default database” no longer exists or the login lacks the CONNECT permission on that database. As a result, SQL Server 2025 falls back to using the master database as a safety measure, which often fails silently for applications expecting a specific schema.

Step-by-Step Resolution Guide

Step 1: Verify the Database State

  • Open SQL Server Management Studio (SSMS) and connect using an admin account (e.g., sa).
  • Run the query: SELECT name, state_desc FROM sys.databases;
  • Check if the target database status reads ONLINE. If it reads RECOVERY_PENDING or SUSPECT, the database files may be corrupted or the drive path is missing.

Step 2: Check and Reset the Login’s Default Database

  • Expand Security > Logins in SSMS, right-click the specific login, and select Properties.
  • Look at the Default database dropdown field; if it points to a database that was deleted, change it back to master temporarily.
  • Alternatively, run this T-SQL command to fix it via query:
  • ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = [master];

Step 3: Validate User Permissions and Mapping

  • Navigate to User Mapping under the Login Properties window.
  • Ensure the checkbox next to the target database is checked, granting the login access.
  • Verify the user has the db_datareader or appropriate role assigned; a mismatch between the Login (Server level) and the User (Database level) often triggers this error even if the database is online.

Step 4: Restart SQL Server Services

  • Open the Services app (services.msc) on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER) or the specific named instance.
  • Right-click and select Restart to clear any cached connection states or locks that might be blocking the database file.

Alternative or Verification Steps

  • Verification: Attempt to reconnect using SSMS or your application; if successful, run SELECT DB_NAME(); to confirm you are no longer defaulting to the master database.
  • Alternative: If the database file (.mdf) is missing from the disk, restore the database from the latest .bak file using the Restore Database wizard in SSMS, ensuring the file paths match the original server configuration.

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

Troubleshooting Guide: SQL Server Error 4060 – “Cannot Open Database Requested by the Login”

Why This Error Happens

Error 4060 typically occurs because the login attempting to connect does not have an associated user account or permissions within the target database, or the default database specified for that login no longer exists or is inaccessible. This can also happen if the database is still in a RESTORING, OFFLINE, or SINGLE_USER state, or if the database name was misspelled in the connection string. In some cases, orphaned SIDs (Security Identifiers) between the login and the database user mapping can trigger this failure even when the user technically “exists.”

Step-by-Step Resolution Guide

Step 1: Verify the Database Status and Existence

  • Open SQL Server Management Studio (SSMS) and connect using an administrative account (e.g., sa).
  • Run the following query to check the database state:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the state_desc returns ONLINE. If it shows RESTORING or OFFLINE, you will need to restore the backup chain or bring the database back online manually.

Step 2: Check Login Permissions and Database Mapping

  • Navigate to Security > Logins in SSMS, right-click the specific login causing the error, and select Properties.
  • Go to the User Mapping tab and confirm the checkbox next to the target database is checked.
  • If the mapping is missing, add it manually or run:
  USE YourDatabaseName;
  CREATE USER [YourLoginName] FOR LOGIN [YourLoginName];
  • If the user already exists but is “orphaned,” repair the SID link using ALTER USER [YourLoginName] WITH LOGIN = [YourLoginName];.

Step 3: Correct Firewall and Default Database Settings

  • On Windows Server 2025, verify that the Windows Defender Firewall isn’t blocking the specific database instance port (though this usually throws a different error, misconfigured VLANs can sometimes cause intermittent connection drops that mimic 4060).
  • Check the login’s “Default Database” setting in Login Properties > General. If it points to a decommissioned database, change it back to master to allow the login to connect first, then troubleshoot the specific DB access.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc if configuration changes were made at the instance level.

Step 4: Review SQL Server Error Logs

  • Navigate to the default log path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG (path may vary based on the 2025 instance naming convention).
  • Look for specific sub-errors occurring alongside the 4060, such as “Login failed for user” combined with State codes (e.g., State 38 indicates the database does not exist, while State 5 indicates insufficient permissions).

Alternative or Verification Steps

  • Verify the Fix: Attempt to log in via SSMS using the specific SQL login (not Windows Auth) and explicitly select the problematic database from the “Connect to Database” dropdown in the Options tab.
  • Alternative Fix: If the user mapping continues to fail, drop the user from the database (DROP USER [YourLoginName]) and recreate it, then manually re-assign the necessary roles (e.g., db_datareader, db_datawriter) to rule out corrupted permission schemas.

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

Troubleshooting Guide: SQL Server Error 4037 – MEDIANAME Mismatch

Why This Error Happens

Error 4037 occurs when SQL Server attempts to read a backup device (tape, file, or media set) and finds that the MEDIANAME value stored in the device header does not match the MEDIANAME specified in the RESTORE or BACKUP command (via the MEDIANAME = clause). This typically happens because the backup media was created with a different name (or no name at all), the backup file was overwritten/reused by another backup set, or the wrong physical device/file path was referenced in the command. It can also occur if a backup file was copied or renamed after creation, causing a mismatch between the expected logical identifier and the actual header metadata embedded in the file.

Step-by-Step Resolution Guide

Step 1: Verify the Actual MEDIANAME on the Device

  • Run the following T-SQL command against the backup file or device to inspect its true header metadata:
  RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourBackupFile.bak';
  • Review the MediaName column in the result set to confirm the actual name stored on the device.
  • Cross-check this against the name you supplied in your RESTORE/BACKUP statement.

Step 2: Correct the MEDIANAME Clause in Your Script

  • Update your RESTORE or BACKUP command to use the exact MEDIANAME returned in Step 1.
  • Example corrected syntax:
  RESTORE DATABASE YourDB
  FROM DISK = 'C:\Backups\YourBackupFile.bak'
  WITH MEDIANAME = 'CorrectMediaNameHere', REPLACE;
  • If you do not need strict media validation, simply remove the MEDIANAME = clause entirely from the command.

Step 3: Check for File Reuse or Corruption

  • Confirm the backup file has not been overwritten by a different backup job pointing to the same path.
  • Use File Explorer or PowerShell to check file timestamps and size:
  Get-Item "C:\Backups\YourBackupFile.bak" | Select-Object Name, Length, LastWriteTime
  • If the file appears truncated or inconsistent with your backup schedule, restore from a known-good backup copy instead.

Step 4: Validate SQL Server Agent Job Configurations

  • Open SQL Server Agent > Jobs in SQL Server Management Studio (SSMS) on Windows Server 2025.
  • Inspect any maintenance plans or scripted jobs that reference MEDIANAME to ensure they are hardcoded correctly and not pulling stale variables from an old job step.
  • Update the job step command text to match the verified MEDIANAME or remove the parameter if media set validation isn’t required.

Alternative or Verification Steps

  • Re-run the RESTORE DATABASE command after applying the corrected MEDIANAME and confirm it completes without Error 4037.
  • As a quick workaround, strip the MEDIANAME parameter entirely from both your BACKUP and RESTORE scripts — SQL Server will bypass this validation check and proceed using only the file/device path.

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

Troubleshooting Guide: SQL Server Error 4038 – “Cannot find file ID %d on device ‘%ls'”

Why This Error Happens

This error occurs when SQL Server’s internal metadata (stored in sys.database_files or sys.master_files) references a file ID that no longer exists on the physical device, typically due to a corrupted or out-of-sync database file header. It commonly arises after an improper file shrink operation, a failed ALTER DATABASE command that removed a file, or physical disk corruption that damaged the file allocation map (FAM) pages. In rare cases, this also surfaces when a database is restored or attached using an outdated or mismatched set of files, causing SQL Server to look for a file ID that was dropped in a newer version of the database.

Step-by-Step Resolution Guide

Step 1: Verify Database File Consistency

  • Open SQL Server Management Studio (SSMS) and run SELECT file_id, name, physical_name, state_desc FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Compare the returned physical_name paths against the actual files present in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Note any file_id referenced in the error (e.g., file ID 4) and confirm whether its corresponding .ndf or .ldf file is missing from disk.

Step 2: Take the Database Offline and Inspect for Orphaned File References

  • Run ALTER DATABASE YourDatabaseName SET OFFLINE WITH ROLLBACK IMMEDIATE; to safely stop active connections.
  • Check the SQL Server Error Log (via EXEC sp_readerrorlog; or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for prior entries indicating a failed shrink or file removal event.
  • If a .ndf secondary file was deleted or moved outside of SQL Server (e.g., via Windows File Explorer or a third-party backup tool), locate the original file from a recent backup.

Step 3: Restore the Missing File Reference

  • If you have the original physical file, bring the database back online and run: ALTER DATABASE YourDatabaseName MODIFY FILE (NAME = LogicalFileName, FILENAME = 'D:\SQLData\MissingFile.ndf');
  • If the file is permanently lost and no backup exists, remove the broken reference using: ALTER DATABASE YourDatabaseName REMOVE FILE LogicalFileName; (only valid if the file belonged to an empty filegroup).
  • For critical production data, restore the entire database from the last known good full backup plus transaction log backups using RESTORE DATABASE YourDatabaseName FROM DISK = 'E:\Backups\YourDatabaseName.bak' WITH NORECOVERY; followed by RESTORE LOG statements as needed.

Step 4: Run Integrity Checks

  • Bring the database back online with ALTER DATABASE YourDatabaseName SET ONLINE;
  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no further file or page-level corruption exists.
  • Review the output for any Msg 8928 or Msg 8944 errors that may indicate deeper corruption requiring REPAIR_ALLOW_DATA_LOSS.

Alternative or Verification Steps

  • Confirm the fix by querying sys.database_files again and ensuring all listed physical_name paths resolve to existing files on disk, then run a test SELECT TOP 10 * FROM a table residing in the previously affected filegroup.
  • If restoring the file is not possible and the error persists, consider creating a brand-new database and migrating data via BCP export/import or SSIS packages to bypass the corrupted file structure entirely.

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

Why This Error Happens

Message 4035 (“Processed %I64d pages for database ‘%ls'”) is an informational message generated during BACKUP, RESTORE, or DBCC CHECKDB operations in SQL Server 2025, and it typically surfaces as a symptom when the underlying operation terminates abnormally rather than being an error itself. The root cause is usually an interrupted I/O stream caused by insufficient NTFS permissions on the backup/data directory, a corrupted database page preventing the read from completing, or the SQL Server service account lacking access to the target volume on Windows Server 2025. In some cases, antivirus or Windows Defender real-time scanning locks the .bak or .mdf file mid-operation, causing the page count to halt unexpectedly.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11 and confirm the SQL Server (MSSQLSERVER) service is running under a valid domain or managed service account.
  • Navigate to the backup/data directory (e.g., D:\SQLData\Backups) and ensure “NT SERVICE\MSSQLSERVER” has Modify/Write permissions via right-click → Properties → Security.
  • Run icacls "D:\SQLData\Backups" in an elevated Command Prompt to confirm ACL entries.

Step 2: Run a Consistency Check to Identify Corruption

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; in SQL Server Management Studio.
  • Review the output for allocation or consistency errors that may have halted the page-processing operation.
  • If corruption is found, note the page ID and object ID for targeted repair.

Step 3: Exclude SQL Directories from Antivirus Scanning

  • Open Windows Security → Virus & threat protection → Exclusions on the Windows Server 2025 host.
  • Add exclusions for *.mdf, *.ldf, *.bak, and the full data/log/backup folder paths.
  • Restart the SQL Server service via net stop MSSQLSERVER && net start MSSQLSERVER to clear any locked file handles.

Step 4: Re-run the Backup or Restore Operation

  • Re-trigger the operation using BACKUP DATABASE [YourDatabaseName] TO DISK = 'D:\SQLData\Backups\YourDB.bak' WITH CHECKSUM, STATS = 10;
  • Monitor the SQL Server Error Log (Management → SQL Server Logs) in real time for confirmation that the full page count completes without interruption.

Alternative or Verification Steps

  • Confirm resolution by checking that the final message reports the expected total page count matching the database size, with no accompanying error codes (e.g., 823, 824) in the SQL Server Error Log.
  • If the issue persists, restore from a known-good backup to a test instance and run DBCC CHECKDB there to isolate whether the corruption is storage-related (check Windows Event Viewer → System log for Disk/NTFS warnings).

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

Troubleshooting Guide: SQL Server Error 4030 – Media Expiration Conflict

Why This Error Happens

This error occurs because SQL Server enforces a retention policy on backup media through the MEDIADESCRIPTION and expiration date metadata written to the backup header. When a backup device (tape or disk file) has an active expiration date set via EXPIREDATE or RETAINDAYS, SQL Server blocks any new BACKUP operation from overwriting that media until the specified date has passed. This is a protective mechanism, not a corruption issue, and most commonly happens when backup jobs reuse the same device name without accounting for retention settings, or when a FORMAT option was omitted on a backup set that still has life remaining.

Step-by-Step Resolution Guide

Step 1: Verify the Current Expiration Date on the Media

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a new query window.
  • Run the following to inspect the backup set metadata:
RESTORE HEADERONLY FROM DISK = 'E:\Backups\YourFile.bak';
  • Check the ExpirationDate column in the result set to confirm whether the media is still within its retention window.

Step 2: Force an Overwrite Using the WITH Clause

  • If the backup content is no longer needed, explicitly override the expiration check in your backup script.
  • Use WITH FORMAT, INIT, SKIP to bypass expiration and retention checks on the next write:
BACKUP DATABASE [YourDB]
TO DISK = 'E:\Backups\YourFile.bak'
WITH FORMAT, INIT, SKIP, STATS = 10;
  • The SKIP option specifically disables the expiration date and backup set name checks that trigger Error 4030.

Step 3: Correct the Retention Settings in the Maintenance Plan

  • Open SQL Server Agent in SSMS and locate the relevant Maintenance Plan under Management > Maintenance Plans.
  • Edit the Back Up Database Task and check the Backup set will expire setting; adjust RETAINDAYS to 0 if indefinite overwrites are intended, or set a realistic value matching your retention policy.
  • Save and redeploy the plan, then manually trigger the job via SQL Server Agent > Jobs to confirm it executes without raising 4030.

Step 4: Check for Group Policy or File-Level Immutability (Windows Server 2025 / Windows 11)

  • Navigate to the backup folder (e.g., E:\Backups\) in File Explorer and right-click the .bak file to open Properties > Security.
  • Confirm the SQL Server service account has Modify/Write permissions, as Windows Server 2025’s stricter default ACLs can sometimes compound perceived “locked” media issues alongside the SQL-level expiration flag.
  • Run icacls "E:\Backups\YourFile.bak" from an elevated Command Prompt to audit permissions if the file was moved or restored from another system.

Alternative or Verification Steps

  • Re-run RESTORE HEADERONLY FROM DISK = 'E:\Backups\YourFile.bak'; after the fix — if the query returns without error and shows the new BackupStartDate, the overwrite succeeded.
  • As an alternative, bypass the existing media entirely by targeting a new file name or device (e.g., YourFile_New.bak) to avoid the expiration conflict without altering retention logic.

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

Troubleshooting Guide: SQL Server Error 4028 – “End of Tape Has Been Reached”

Why This Error Happens

This error occurs when SQL Server completes writing data to the current tape volume during a backup or restore operation and requires an additional tape to continue the process, but no additional media has been loaded into the drive. It commonly happens when the database or backup set being processed exceeds the physical storage capacity of a single tape cartridge. Additionally, this can occur if the tape drive hardware fails to signal proper media-change events back to SQL Server, or if the backup operation was configured without accounting for multi-volume sets in unattended/scheduled jobs.

Step-by-Step Resolution Guide

Step 1: Prepare and Insert the Next Tape Volume

  • Physically locate the tape labeled in the error message (the %ls placeholder will show the specific tape name/sequence number).
  • Remove the full tape from the drive bay and insert the next blank or designated tape in the sequence.
  • Ensure the new tape is not write-protected and is compatible with the drive firmware (check for LTO generation mismatches on Windows Server 2025 hardware).

Step 2: Resume the Backup/Restore Operation in SSMS or T-SQL

  • If running via SQL Server Management Studio (SSMS), click the Retry button on the prompt dialog to signal SQL Server that the tape has been swapped.
  • If running a scripted job via T-SQL, ensure your script includes the BLOCKSIZE and MEDIANAME parameters correctly to avoid mismatch errors upon tape swap.
  • For unattended jobs, verify that xp_cmdshell or the SQL Server Agent job step does not time out while waiting for manual intervention.

Step 3: Verify Tape Drive Hardware and Drivers

  • Open Device Manager on Windows Server 2025 and check the Tape drives node for any yellow warning icons.
  • Update the tape drive driver via Update driver > Search automatically for drivers or download the vendor-specific driver (e.g., IBM, Quantum, HPE).
  • Restart the Removable Storage service via services.msc to ensure Windows correctly detects the newly inserted media.

Step 4: Switch to Multi-File Backup Striping (Recommended Fix)

  • To avoid the need for physical tape swaps on large databases, modify your backup script to stripe the backup across multiple tape drives simultaneously if your server has more than one drive bay.
  • Alternatively, migrate the backup destination to a Virtual Tape Library (VTL) or disk-based backup to eliminate physical capacity limits entirely.
  • Update the backup command to include multiple TAPE = destinations in the BACKUP DATABASE syntax to allow parallel writing.

Alternative or Verification Steps

  • Verify the fix: Check the SQL Server Error Log or the Windows Event Viewer (Application Log) for Event ID 4028 to ensure the backup completed with a “Processed X pages” success message rather than terminating with a fatal error.
  • Alternative solution: If physical tape changes are consistently causing bottlenecks or failures, consider decommissioning the tape backup strategy in favor of Azure Blob Storage backup targets, which are natively supported in SQL Server 2025 and eliminate the “end of volume” limitation entirely.

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

Why This Error Happens

Error 4022 occurs when the SQL Server BCP (Bulk Copy Program) or BULK INSERT operation initiates a bulk load session, but the client application fails to transmit the expected data stream before the connection times out. This is typically caused by a mismatched file format definition, an interrupted network connection between the client and SQL Server 2025 instance, or a source file that was moved, locked, or corrupted mid-transfer. It can also occur when the format file (.fmt) specifies more columns or a different structure than the actual data file provides.

Step-by-Step Resolution Guide

Step 1: Verify the Source Data File and Path

  • Confirm the file path referenced in your BULK INSERT or bcp command is accessible from the SQL Server 2025 service account (not just your local user account).
  • Check file permissions: right-click the file/folder → Properties → Security → ensure NT SERVICE\MSSQLSERVER (or the custom service account) has at least Read access.
  • Test with a UNC path (e.g., \\ServerName\Share\datafile.csv) instead of a mapped drive letter, as mapped drives are often invisible to the SQL Server service context.

Step 2: Validate the Format File and Column Mapping

  • Open the .fmt file (if used) and compare the column count/order against the actual source file headers.
  • Regenerate the format file using:
  bcp YourDatabase.dbo.YourTable format nul -c -f YourTable.fmt -S YourServerName -T
  • Ensure field terminators (,, \t) and row terminators (\n, \r\n) in your BULK INSERT statement match the actual encoding of the file (check for CRLF vs LF mismatches, common when files originate from Linux-based ETL pipelines).

Step 3: Check Network Stability and Timeout Settings

  • On Windows Server 2025, open Server Manager → SQL Server Configuration Manager → SQL Server Network Configuration → confirm TCP/IP is enabled and not experiencing packet drops.
  • Increase the client-side command timeout in your application or SSMS query timeout settings (Tools → Options → Query Execution → Execution time-out) if large files are causing premature termination.
  • If using a linked server or remote client, run a ping -t or tracert test to rule out intermittent network latency during the bulk transfer window.

Step 4: Rebuild the Bulk Insert Statement with Explicit Options

  • Re-run the operation using explicit WITH options to rule out default assumption errors:
  BULK INSERT YourTable
  FROM 'C:\Data\YourFile.csv'
  WITH (
      FORMATFILE = 'C:\Data\YourTable.fmt',
      FIRSTROW = 2,
      TABLOCK,
      ERRORFILE = 'C:\Data\ErrorLog.txt'
  );
  • Review the generated ErrorLog.txt for row-specific failures that may indicate truncated or empty data batches.

Alternative or Verification Steps

  • Run the bulk load against a small sample file (5–10 rows) first; if it succeeds, the issue is almost certainly a data/format mismatch rather than a permissions or network problem.
  • As an alternative, use SQL Server Import and Export Wizard or SSIS instead of raw BULK INSERT/bcp, as it provides better column-mapping validation and clearer error diagnostics for Windows 11 client-to-server transfers.

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

Troubleshooting Guide: SQL Server Error 4027 – “Mount tape for %hs of database ‘%ls’ on tape drive ‘%ls'”

Why This Error Happens

This error occurs when SQL Server 2025 initiates a backup or restore operation targeting a physical tape device but cannot proceed because it is waiting for an operator to mount the correct tape volume. The underlying cause is typically that the tape drive is either empty, contains the wrong volume, or the SQL Server Service Account lacks the necessary permissions to communicate with the tape hardware/driver. In some cases, this is also triggered by a misconfigured or orphaned backup device pointing to a non-existent or offline tape resource.

Step-by-Step Resolution Guide

Step 1: Verify Physical Tape Drive Status and Connectivity

  • Check the physical tape drive on the Windows Server 2025 host to ensure it is powered on and connected via the correct SAS/Fibre Channel interface.
  • Open Device Manager on the host and look under “Tape drives” to confirm the OS recognizes the hardware without a yellow warning icon.
  • If the drive is missing, reseat the hardware connection or update the tape drive drivers via the manufacturer’s latest Windows Server 2025 compatible package.

Step 2: Insert or Replace the Correct Tape Media

  • Since this specific error is a “prompt” rather than a hard failure, confirm that a blank or appropriately overwritable tape is physically loaded into the drive.
  • If using a tape library/autoloader, check the magazine slots to ensure the barcode-labeled tape requested by the backup job is actually present in the robotic arm’s accessible queue.
  • Run RESTORE LABELONLY FROM TAPE = '\\.\Tape0' in SQL Server Management Studio (SSMS) to verify the drive can read the currently inserted media header.

Step 3: Validate SQL Server Service Account Permissions

  • Navigate to Services.msc on Windows Server 2025 and locate the “SQL Server (MSSQLSERVER)” service.
  • Ensure the “Log On As” account has been granted Read/Write access to the tape device path (e.g., \\.\Tape0) via local security policy.
  • Add the service account to the local Backup Operators group to ensure it has the SeBackupPrivilege and SeRestorePrivilege rights required to interface with removable storage.

Step 4: Update the Backup Job Configuration

  • If the tape drive has been replaced or renamed in the Windows OS, update the legacy T-SQL script or SQL Agent Job step.
  • Modify the BACKUP DATABASE syntax to reflect the current, active tape drive letter/path:
  BACKUP DATABASE [YourDB] TO TAPE = '\\.\Tape0' WITH NOREWIND, NOUNLOAD;
  • Ensure the NOUNLOAD parameter is used if you intend to keep the tape mounted for sequential multi-database backups to avoid repeated mount prompts.

Alternative or Verification Steps

  • Verification: Once the tape is loaded and permissions are updated, re-run the specific backup job via SQL Server Agent; the job history should show a “Succeeded” status without triggering the Error 4027 mount prompt.
  • Alternative: If physical tape hardware continues to fail intermittently, consider migrating the backup strategy to a Virtual Tape Library (VTL) or standard disk-based backup (TO DISK =) to eliminate physical media handling errors entirely.

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

Troubleshooting Guide: SQL Server Error 4021 — Connection Reset Results in Different Login State

Why This Error Happens

Error 4021 occurs when SQL Server’s connection resiliency feature attempts to reset a session after an idle or dropped connection, but the session-level settings (such as database context, SET options, or temporary objects) cannot be restored to match the original login state. This typically happens due to changes in default database availability, mismatched collation or language settings applied mid-session, or interference from connection pooling in the client driver (such as an outdated ODBC or OLE DB provider). It can also be triggered when Contained Database Users or Azure AD/Entra ID authentication tokens expire mid-session on Windows Server 2025 environments.

Step-by-Step Resolution Guide

Step 1: Verify the Default Database State

  • Open SQL Server Management Studio (SSMS) and run SELECT name, state_desc FROM sys.databases; to confirm the user’s default database is ONLINE and not RESTORING or OFFLINE.
  • Check sp_helplogin 'username' to ensure the default database assigned to the login still exists and hasn’t been renamed or dropped.
  • If the default database is unavailable, reassign it using ALTER LOGIN [username] WITH DEFAULT_DATABASE = [master];

Step 2: Update Client Drivers and Connection Strings

  • Navigate to Control Panel > Programs > Programs and Features on the Windows Server 2025/Windows 11 machine and check the version of “Microsoft ODBC Driver for SQL Server” or “Microsoft OLE DB Driver for SQL Server.”
  • Download and install the latest driver from the Microsoft Download Center if the version predates 18.x.
  • In the application’s connection string, disable aggressive connection pooling by setting Pooling=false; temporarily to isolate whether pooling is causing stale session resets.
  • Alternatively, add ConnectRetryCount=3;ConnectRetryInterval=10; to allow graceful retries instead of abrupt resets.

Step 3: Audit SET Options and Session Context Scripts

  • Open SQL Server Configuration Manager and review any Logon Triggers under Server Objects > Triggers in SSMS that might be altering session state (e.g., SET ANSI_NULLS, SET QUOTED_IDENTIFIER) inconsistently.
  • Run DBCC USEROPTIONS; immediately after connecting to compare active session settings against the expected defaults.
  • Disable any custom logon triggers temporarily using DISABLE TRIGGER [trigger_name] ON ALL SERVER; to test if they are the source of the state mismatch.

Step 4: Check Authentication Token Expiry (Azure AD/Entra ID)

  • If using Entra ID authentication, open Event Viewer on the Windows Server 2025 host and navigate to Applications and Services Logs > Microsoft > Windows > AAD.
  • Look for token expiration events that align with the timestamp of Error 4021.
  • Increase the token refresh interval in your application’s authentication library or switch to SQL Server native authentication for service accounts experiencing frequent resets.

Step 5: Restart SQL Server Services and Clear Connection Cache

  • Open Services.msc, locate “SQL Server (MSSQLSERVER)” or the named instance, and perform a restart to clear any cached session states.
  • Run DBCC FREESYSTEMCACHE('ALL'); in SSMS to purge stale connection and plan cache data that might be causing the mismatch.

Alternative or Verification Steps

  • To verify the fix, open a new connection in SSMS, run a test transaction that switches database context, then force a network interruption (e.g., briefly disable the network adapter) to confirm the connection resumes without triggering Error 4021.
  • If the issue persists, enable Extended Events with the error_reported event filtered for Error 4021 to capture the exact session state mismatch for deeper diagnosis with Microsoft Support.

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

Troubleshooting Guide: SQL Server Error 4020 — Invalid Default Date Order

Why This Error Happens

This error occurs when the dateorder configuration associated with a specific language ID in the syslanguages (or sys.syslanguages compatibility view) contains an invalid or corrupted value instead of a valid pattern like mdy, dmy, or ymd. This is typically caused by corruption in system catalog metadata, a botched collation/language upgrade during migration to SQL Server 2025, or manual tampering with language settings via sp_configure or direct system table edits. SQL Server detects the invalid entry at parse time and silently falls back to the mdy default to prevent a hard failure, but the underlying metadata issue remains unresolved.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Language and Current Dateorder Value

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the instance reporting the error.
  • Run the following query to inspect language metadata:
  SELECT langid, name, alias, dateformat 
  FROM sys.syslanguages;
  • Look for any row where the dateformat column contains a value other than mdy, dmy, or ymd — this is the corrupted entry.

Step 2: Check the Default Language Setting at the Login and Server Level

  • Verify the server-wide default language:
  EXEC sp_configure 'default language';
  • Check if a specific login has a non-standard default language assigned:
  SELECT name, language 
  FROM sys.server_principals 
  WHERE type = 'S';
  • If a login is tied to the corrupted language entry, temporarily reset it to us_english using:
  ALTER LOGIN [YourLoginName] WITH LANGUAGE = us_english;

Step 3: Repair or Reset the Corrupted Language Entry

  • If a custom/regional language pack was installed manually (common in non-English Windows Server 2025 deployments), reinstall it using the official SQL Server 2025 language resource files located in:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Resources\<LCID>\
  • If the corruption persists in system tables, run DBCC CHECKCATALOG against the master database to confirm catalog integrity:
  DBCC CHECKCATALOG;
  • As a last resort, rebuild the master database language definitions by re-running SQL Server Setup in repair mode (Setup.exe /ACTION=REPAIR) from the installation media.

Step 4: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart the SQL Server (MSSQLSERVER) service to ensure the corrected language metadata is reloaded into memory.
  • Confirm there are no residual Error 4020 entries in the SQL Server Error Log located at:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG

Alternative or Verification Steps

  • Run SELECT @@DATEFORMAT; after reconnecting to confirm the session is now using the correct date order (should return 1 for mdy, 2 for dmy, etc., depending on your intended locale).
  • If the issue reappears only for specific client applications, check the connection string for an explicit Language parameter that may be overriding the server default — remove it and let the login’s default language setting take precedence.

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

Troubleshooting Guide: SQL Server Error 4019 — Invalid Login Language

Why This Error Happens

This error occurs when a login (either in the connection string, application configuration, or user default settings) specifies a LANGUAGE value that does not match any entry in SQL Server’s sys.syslanguages system table. This commonly happens after a SQL Server upgrade/migration (such as moving to SQL Server 2025) where the Language Resource files were not fully installed, or when a default language was manually set via ALTER LOGIN using a typo or deprecated language name (e.g., using regional variants that were deprecated in newer builds). It can also occur if the server’s default language setting was corrupted during a collation change or master database restore from an incompatible version.

Step-by-Step Resolution Guide

Step 1: Identify the Invalid Language String

  • Open SQL Server Management Studio (SSMS) and connect using a Windows Admin account (since the SQL login itself may be broken).
  • Run the following query to see all valid languages recognized by the instance:
  SELECT * FROM sys.syslanguages;
  • Compare the output against the language name referenced in the error message (usually found in the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).

Step 2: Correct the Login’s Default Language

  • Identify the broken login using:
  SELECT name, language FROM sys.sql_logins;
  • Reset the specific login to the server’s default language (usually us_english) using the ALTER LOGIN command:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_LANGUAGE = [us_english];
  • If the application connection string is forcing a specific language via the Language keyword, update the connection string on the client machine or IIS configuration to remove the invalid parameter.

Step 3: Repair Missing Language Resources (Server-Side)

  • If sys.syslanguages is missing standard languages (indicating a corrupted installation), launch the SQL Server 2025 Installation Center from the original setup media.
  • Select Maintenance > Repair and choose the specific instance name on your Windows Server 2025 machine.
  • Allow the repair utility to restore the default language resource files located in the Binn directory, then restart the SQL Server (MSSQLSERVER) service via services.msc.

Step 4: Restart Services and Clear Cache

  • Restart the SQL Server service to ensure the language cache is reloaded into memory.
  • Open PowerShell as Administrator and run:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Attempt the login again using the previously failing credentials to confirm the queue has cleared.

Alternative or Verification Steps

  • Verification: Attempt to log in via SSMS using the specific login that previously failed; if successful, check the sys.dm_exec_sessions view to confirm the language column now displays a valid, officially supported name.
  • Alternative: If the repair fails to restore language files, manually drop and recreate the specific language using sp_addlanguage (though this is deprecated) or simply force all client applications to omit the Language parameter entirely, allowing SQL Server to default to the server-level setting.

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

Troubleshooting Guide: SQL Server Error 4018

Why This Error Happens

This error occurs when a login’s default language, as defined in sys.server_principals or sys.sql_logins, references a language name (syslanguages/sys.syslanguages) that has been removed, renamed, or was never properly registered on the SQL Server instance. This commonly happens after a server migration, an in-place upgrade to SQL Server 2025, or a restoration of logins from an older server instance where regional language packs differed. Since SQL Server cannot locate a matching entry in the sys.syslanguages catalog view, it silently falls back to the server-wide default language (typically us_english) and raises Error 4018 as a warning.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Login and Its Configured Language

  • Open SQL Server Management Studio (SSMS) 21 or later and connect to the instance via Windows Authentication (sysadmin role required).
  • Run the following query to find logins with invalid default languages:
SELECT name, language 
FROM sys.syslogins 
WHERE language NOT IN (SELECT name FROM sys.syslanguages);
  • Note down the exact login names returned — these are the accounts triggering Error 4018.

Step 2: Verify Installed Languages on the SQL Server Instance

  • Run EXEC sp_helplanguage; to list all official language names recognized by this instance.
  • Compare the output against the language value found in Step 1 (common mismatches include British vs British English, or deprecated regional names from SQL Server 2016/2019).
  • Confirm the server-wide default language setting via:
EXEC sp_configure 'default language';

Step 3: Correct the Login’s Default Language

  • Use ALTER LOGIN to reset the affected login to a valid, officially supported language name:
ALTER LOGIN [YourLoginName] WITH LANGUAGE = N'us_english';
  • If managing multiple logins, script this change in bulk using a cursor over the result set from Step 1.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER (PowerShell, run as Administrator) to clear cached session language settings.

Step 4: Re-check Server and Client Collation Settings

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and confirm the sqlservr.exe version matches SQL Server 2025 build requirements.
  • Ensure client connection strings do not explicitly pass a deprecated Language= parameter in the connection string (common in legacy ODBC/OLEDB drivers).

Alternative or Verification Steps

  • Reconnect using the affected login and check the SSMS “Messages” tab — Error 4018 should no longer appear, and SELECT @@LANGUAGE; should return the corrected value.
  • If the error persists after altering the login, run DBCC FREEPROCCACHE to clear any cached execution plans referencing the old language metadata, then retry the connection.

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

Troubleshooting Guide: SQL Server Error 4017 – Language Mismatch Warning

Why This Error Happens

This warning occurs when the login’s requested language or the user’s default language setting does not match any of the official language names configured on the SQL Server instance (e.g., “us_english,” “French,” “Deutsch”). This typically happens due to a mismatch between the client connection string’s language parameter and the sys.syslanguages catalog, or because a user’s default language ID points to a language that was removed or was never installed correctly. While SQL Server gracefully falls back to the server-wide default language to maintain the connection, the root cause usually lies in misconfigured login properties or missing language packs.

Step-by-Step Resolution Guide

Step 1: Identify the Server’s Available Languages

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025.
  • Run the following query to view all officially supported languages: EXEC sp_helplanguage;
  • Note the exact alias names (case-sensitive syntax matters for connection strings) listed in the result set.

Step 2: Verify the Login’s Default Language Setting

  • Query the specific login causing the error to check its configured default language:
  • SELECT name, language FROM sys.sql_logins WHERE name = 'YourLoginName';
  • If the language column is blank, NULL, or references a non-standard name, proceed to Step 3 to reset it.

Step 3: Correct the Login’s Default Language

  • Use the ALTER LOGIN command to explicitly set a valid language matching the alias found in Step 1.
  • Run: ALTER LOGIN [YourLoginName] WITH DEFAULT_LANGUAGE = [us_english];
  • If the application connection string is forcing a specific language via the Language keyword, update the connection string to match a valid sp_helplanguage alias exactly.

Step 4: Check Server-Wide Default Language Configuration

  • Verify the server’s default language ID using sp_configure 'default language';
  • If necessary, reconfigure the default language ID to ensure it points to a valid, installed language set (usually ID 0 for us_english) using sp_configure 'default language', 0; RECONFIGURE;
  • Restart the SQL Server service via the SQL Server Configuration Manager for the change to take full effect on Windows Server 2025.

Alternative or Verification Steps

  • Verification: Re-attempt the login connection via SSMS or the application; check the SQL Server Error Log (via EXEC sp_readerrorlog;) to confirm Error 4017 is no longer being generated for that specific login.
  • Alternative: If the error persists across multiple logins, consider reinstalling the specific Language Pack/Collation support feature via the SQL Server 2025 setup wizard, as this may indicate a corrupted syslanguages system table.

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

Troubleshooting Guide: SQL Server Error 4015 – Language Not an Official Name

Why This Error Happens

This informational error occurs when a login attempts to connect to SQL Server 2025 using a DEFAULT LANGUAGE setting (either at the login level or specified by the client connection string) that does not correspond to an officially installed language alias in the sys.syslanguages (or sys.server_principals) catalog. This typically happens after a server migration, a case-sensitive mismatch in the language name, or because a client-side application is hardcoding a regional language value (e.g., “British”) that was never installed or aliased on this specific instance. Since SQL Server cannot locate the matching langid, it safely falls back to the server-wide default language (usually us_english) to prevent the login from failing entirely.

Step-by-Step Resolution Guide

Step 1: Identify the Current Server Default Language

  • Open SQL Server Management Studio (SSMS) and connect to your instance via a sysadmin account.
  • Run the following query to check the current server default langid:
  EXEC sp_configure 'default language';
  • Note the run_value; this is the language ID currently being used as the fallback.

Step 2: Audit Official Language Names on the Instance

  • Query the system view to see exactly which names are “official” (aliases) versus simply display names.
  • Run this command to see the valid list of names SQL Server will accept for login configuration:
  SELECT langid, name, alias FROM sys.syslanguages;
  • Compare this list against the specific language string being passed in the connection string or login properties. Pay close attention to regional differences (e.g., “English” vs. “us_english”).

Step 3: Update the Login’s Default Language Property

  • Navigate to the specific login causing the error.
  • In SSMS, right-click the login under Security > Logins > [LoginName] > Properties > General.
  • Update the Default Language dropdown to a valid official name/alias found in Step 2.
  • Alternatively, fix this via T-SQL by executing:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_LANGUAGE = [us_english];

Step 4: Check the Application Connection String

  • If the login itself is correctly configured but the error persists, the issue likely lies in the client application (e.g., a .NET or ODBC driver) explicitly setting SET LANGUAGE upon connection.
  • Locate the web.config, app.config, or connection pooling settings on the Windows Server 2025/Windows 11 client machine.
  • Remove any hardcoded Language= parameters from the connection string unless they exactly match an alias from the sys.syslanguages table.

Alternative or Verification Steps

  • Verify the Fix: Re-attempt the login connection and check the SQL Server Error Log (via SSMS or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) to confirm Error 4015 is no longer being raised upon connection.
  • Alternative Fix: If specific regional languages are required but missing, you may need to reinstall the Language Pack component via the SQL Server 2025 setup media to register the missing syslanguages aliases before assigning them to the login.

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

Troubleshooting Guide: SQL Server Error 4016

Why This Error Happens

Error 4016 occurs when a login attempts to connect to SQL Server 2025 using a @LANGUAGE value or client-configured language setting that does not match an official language name or alias registered in the sys.syslanguages (or sys.server_principals default language mapping) on the target instance. This commonly happens after a server migration, a mismatched regional/locale setting on the client driver, or when a login’s default language was set via a script referencing a language pack that was never installed on this particular SQL Server instance. Because SQL Server cannot resolve the requested language, it silently falls back to the user’s default language, but still raises this informational/warning event in the error log.

Step-by-Step Resolution Guide

Step 1: Identify the Requested vs. Available Languages

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a working admin login.
  • Run EXEC sp_helplanguage; to list all official languages and aliases installed on this SQL Server 2025 instance.
  • Check the SQL Server Error Log (Management > SQL Server Logs) and locate the full Error 4016 text to identify the exact login name and the malformed language string being requested.

Step 2: Correct the Login’s Default Language Setting

  • Run EXEC sp_helpuser 'login_name'; or query sys.server_principals to check the current default_language_name assigned to the affected login.
  • Reset the login’s default language to a valid, officially supported value using:
  ALTER LOGIN [login_name] WITH DEFAULT_LANGUAGE = [us_english];
  • If the language should exist but doesn’t, verify the regional language pack was properly installed during SQL Server 2025 setup via Add/Remove Programs > Microsoft SQL Server 2025 Features.

Step 3: Fix the Client-Side Connection String or Driver Setting

  • On the client application or connection string (ODBC/ADO.NET/JDBC), remove or correct any explicit Language= parameter that references a non-standard or deprecated locale name (e.g., Language=Deutsch instead of the official German).
  • For applications using a SET LANGUAGE T-SQL command at session startup, update the script to use the exact name returned by sp_helplanguage.
  • Restart the application pool or client service and re-test the connection to confirm the explicit language request now resolves correctly.

Step 4: Review Group Policy and OS Regional Settings (Windows Server 2025 / Windows 11)

  • Check Control Panel > Region > Administrative > Language for non-Unicode programs on the client machine, as mismatched OS locale settings can sometimes propagate unexpected language strings to the driver.
  • Ensure the Windows Server 2025 instance hosting SQL Server has the correct regional and language pack installed under Settings > Time & Language > Language & Region.

Alternative or Verification Steps

  • Verify the fix by re-attempting the login and confirming Error 4016 no longer appears in the SQL Server Error Log; also run SELECT @@LANGUAGE; in a new session to confirm the correct language is now active.
  • If the issue persists, as a workaround, standardize all logins to use the server’s default language by running ALTER LOGIN [login_name] WITH DEFAULT_LANGUAGE = [your_server_default]; for every affected account, bypassing the need for per-login language resolution entirely.

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

Why This Error Happens

Error 4014 typically occurs when the SQL Server network connection between the client and server is unexpectedly interrupted at the TCP/IP packet level. This is often caused by network instability, a misconfigured firewall dropping packets mid-session, antivirus/deep packet inspection software interfering with the TDS (Tabular Data Stream) protocol, or corrupted network drivers on Windows Server 2025 / Windows 11. It can also stem from client-side connection timeouts conflicting with long-running queries or large result sets being transmitted over an unstable link.

Step-by-Step Resolution Guide

Step 1: Verify Network Stability and Firewall Rules

  • Run ping <SQLServerInstanceName> and tracert <SQLServerInstanceName> continuously to check for packet loss or latency spikes.
  • Open Windows Defender Firewall with Advanced Security and confirm inbound/outbound rules allow TCP port 1433 (default instance) and any dynamic ports used by named instances.
  • Temporarily disable third-party antivirus/firewall software to rule out deep packet inspection interference, then re-test the connection.

Step 2: Check SQL Server Network Configuration

  • Open SQL Server Configuration Manager → SQL Server Network Configuration → Protocols for [InstanceName].
  • Ensure TCP/IP is enabled and verify the correct IP address/port bindings under the IP Addresses tab.
  • Restart the SQL Server (MSSQLSERVER) service after any configuration changes via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Update Network Drivers and Adapter Settings

  • Navigate to Device Manager → Network Adapters, right-click the active NIC, and select Update Driver.
  • Disable TCP Chimney Offload and Receive Side Scaling (RSS) if packet corruption is suspected, using PowerShell: Disable-NetAdapterChecksumOffload -Name "*".
  • Reboot the server/workstation to apply the driver and adapter changes cleanly.

Step 4: Adjust Client and Server Timeout Settings

  • In your client application or SSMS, increase the Connection Timeout and Query Timeout values under Tools → Options → Query Execution.
  • On the server side, review sp_configure 'remote query timeout' and adjust if queries are being prematurely terminated.
  • Apply changes with RECONFIGURE and restart the SQL Server service to ensure settings take effect.

Alternative or Verification Steps

  • Reproduce the original workload (large query/data transfer) and monitor the SQL Server Error Log and Windows Event Viewer (Application log) to confirm Error 4014 no longer appears.
  • If the issue persists, capture a network trace using Wireshark or Netmon during the failure window to identify the exact point of packet loss, and share the trace with your network team for deeper TCP-level analysis.

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

Troubleshooting Guide: SQL Server Error 4013 — Incorrect TDS Protocol Stream / Missing MARS TDS Header

Why This Error Happens

This error occurs when the Tabular Data Stream (TDS) packets sent by the client do not conform to the structure SQL Server expects when Multiple Active Result Sets (MARS) is enabled on the connection. It is typically caused by a mismatch between the client driver version and the SQL Server 2025 engine, network-level packet corruption or fragmentation (often from misconfigured firewalls, proxies, or load balancers), or an outdated/corrupted client-side network library (such as an old ODBC or OLE DB driver) that does not properly format MARS session headers. In some cases, antivirus or deep packet inspection software intercepting the connection can also strip or alter TDS headers mid-stream.

Step-by-Step Resolution Guide

Step 1: Update and Verify Client Drivers

  • Ensure the client application is using the latest Microsoft ODBC Driver or OLE DB Driver compatible with SQL Server 2025.
  • On Windows 11 / Windows Server 2025, check installed driver versions via Control Panel > ODBC Data Sources (64-bit).
  • Uninstall legacy drivers (e.g., SQL Server Native Client) and replace with the current Microsoft OLE DB Driver for SQL Server (MSOLEDBSQL) or ODBC Driver 18+.

Step 2: Inspect and Reset Network Path

  • Disable any proxy, SSL-inspection, or deep packet inspection (DPI) features on firewalls/antivirus that intercept SQL traffic on port 1433.
  • Run netstat -ano | findstr 1433 to confirm no unexpected intermediary process is binding to the SQL Server port.
  • If using a load balancer, confirm it is configured in “TCP pass-through” mode rather than re-packetizing TDS traffic.

Step 3: Validate MARS Configuration on the Connection String

  • Confirm the client connection string includes MultipleActiveResultSets=True only if the application logic actually requires concurrent result sets.
  • Remove or correct malformed MARS parameters, as inconsistent flags between client and server can trigger header mismatches.
  • Example corrected connection string:
    Server=myServer;Database=myDB;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;

Step 4: Restart SQL Server Services and Clear Session Cache

  • Open SQL Server Configuration Manager and restart the SQL Server (MSSQLSERVER) service to clear any corrupted session buffers.
  • Clear client-side connection pooling by restarting the application pool (IIS) or application service that hosts the database client.

Step 5: Check for Network Packet Fragmentation

  • Verify the Network Packet Size setting in SQL Server under Server Properties > Connections matches what the network infrastructure (MTU size) supports — default is 4096 bytes.
  • Run Test-NetConnection -ComputerName <SQLServerName> -Port 1433 on Windows 11/Server 2025 to confirm clean connectivity without timeouts or resets.

Alternative or Verification Steps

  • After applying the fixes, reproduce the original query/application action that triggered Error 4013 and confirm no TDS-related errors appear in SQL Server Error Logs (SQL Server Management Studio > Management > SQL Server Logs).
  • If the issue persists, capture a network trace using Wireshark or Network Monitor while reproducing the error to confirm whether TDS packets are being altered in transit by security middleware, and work with your network team to exclude SQL Server traffic from inspection rules.

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

Troubleshooting Guide: SQL Server Error 4012 – Invalid TDS Collation

Why This Error Happens

Error 4012 occurs when the Tabular Data Stream (TDS) packet sent to SQL Server 2025 contains a collation identifier that the server cannot recognize or map to a valid collation in its internal collation table. This typically happens due to a mismatch between client driver versions and the server’s collation set, a corrupted sqlncli or msodbcsql driver installation, or an outdated client library attempting to negotiate a collation introduced in a newer SQL Server version that the driver doesn’t understand. It can also surface after an in-place upgrade where system databases retain a legacy collation reference that conflicts with newly introduced server-level collation metadata.

Step-by-Step Resolution Guide

Step 1: Verify and Update Client Drivers

  • Confirm which driver the failing application uses (ODBC, OLE DB, or JDBC) via Event Viewer under Windows Logs > Application.
  • Download and install the latest Microsoft ODBC Driver or msodbcsql18.msi from the official Microsoft Download Center.
  • Restart the application pool or client service after installation to force driver reload.

Step 2: Check Server Collation Configuration

  • Open SQL Server Management Studio (SSMS) and run:
  SELECT SERVERPROPERTY('Collation');
  • Compare this output against the collation expected by the client connection string.
  • If mismatched, update the connection string or application config file (appsettings.json, web.config, or DSN entry) to explicitly specify the correct collation parameter.

Step 3: Rebuild or Repair System Databases

  • Open an elevated Command Prompt on Windows Server 2025.
  • Navigate to the SQL Server binn directory, typically:
  C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn
  • Run a repair install using the setup media:
  setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=BUILTIN\Administrators /SAPWD=<StrongPassword>
  • This resets master, model, msdb, and tempdb collation metadata to a known-good state.

Step 4: Clear TDS Endpoint Cache and Restart Services

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart the SQL Server (MSSQLSERVER) and SQL Server Browser services to flush cached TDS negotiation parameters.
  • If using a named instance, restart the corresponding SQL Server (InstanceName) service as well.

Alternative or Verification Steps

  • Test the fix by connecting via sqlcmd -S <ServerName> -E -Q "SELECT @@VERSION" — a successful connection with no 4012 error confirms resolution.
  • If the error persists, create a new client alias using SQL Server Configuration Manager with explicit TCP/IP protocol settings and a matching collation flag to bypass any cached negotiation data.

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

Troubleshooting Guide: Error 4011 – Incorrect MARS TDS Header Stream

Why This Error Happens

This error occurs when Multiple Active Result Sets (MARS) is enabled on a connection and the underlying TDS packet stream becomes malformed or desynchronized, often due to network packet corruption, a faulty network driver, or an outdated client provider (such as an old ODBC or OLE DB driver) that mismanages concurrent batches. It can also surface when third-party network security software (antivirus/deep packet inspection) intercepts and modifies SQL Server traffic on port 1433, or when there is a mismatch between the client-side connection string MARS settings and the server’s session state. Additionally, corrupted or fragmented TCP packets caused by faulty NIC offloading settings (like TCP Chimney or RSS) on Windows Server 2025 can trigger this header corruption.

Step-by-Step Resolution Guide

Step 1: Update and Verify Client Drivers

  • Ensure the application is using the latest Microsoft OLE DB Driver or ODBC Driver 18+ for SQL Server, as older drivers have known MARS handling bugs.
  • Check the connection string to confirm MultipleActiveResultSets=True is explicitly set only if the application logic requires concurrent batches.
  • Restart the client application service after the driver update to clear cached connection pools.

Step 2: Disable NIC Offloading Features

  • Open PowerShell as Administrator on the Windows Server 2025 host.
  • Run Disable-NetAdapterChecksumOffload -Name "*" to rule out checksum calculation errors corrupting packets.
  • Run Set-NetAdapterAdvancedProperty -Name "*" -DisplayName "Receive Side Scaling" -DisplayValue "Disabled" to test if RSS is causing packet reordering issues.
  • Reboot the network adapter or server to apply changes.

Step 3: Flush Connection Pooling and Reset Sessions

  • Access SQL Server Management Studio (SSMS) and run DBCC FREESYSTEMCACHE('ALL') to clear corrupted cached execution plans associated with the bad session.
  • Kill any hanging SPIDs associated with the specific application using KILL [Session_ID].
  • If using .NET, ensure SqlConnection.ClearPool() is called within the application error handling to force a fresh TDS handshake.

Step 4: Inspect Antivirus and Firewall Packet Inspection

  • Navigate to Windows Defender Firewall with Advanced Security on the Windows Server 2025 machine.
  • Create an exclusion rule for the SQL Server process (sqlservr.exe) and port 1433 to bypass deep packet inspection (DPI) that might be altering TDS headers.
  • Temporarily disable third-party antivirus real-time scanning to test if it resolves the TDS stream corruption.

Alternative or Verification Steps

  • Verification: Use SQL Server Profiler or Extended Events to trace the Errors and Warnings event category; confirm that Error 4011 no longer appears during high-concurrency MARS transactions.
  • Alternative: If the error persists, disable MARS entirely in the connection string (MultipleActiveResultSets=False) as a temporary workaround while further investigating network hardware (switches/routers) for Jumbo Frame misconfigurations.

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

Troubleshooting Guide: TDS Protocol Stream Error 4009 in SQL Server 2025

Why This Error Happens

Error 4009 occurs when the SQL Server Database Engine receives a Tabular Data Stream (TDS) packet that is malformed, truncated, or out of sequence, causing the server to immediately terminate the connection. This is most commonly caused by network-layer corruption (faulty NICs, misconfigured routers, or MTU mismatches), an outdated or buggy client driver (such as an older ODBC or JDBC driver that doesn’t correctly format TDS headers), or interference from a security appliance/antivirus performing deep packet inspection on port 1433. In rarer cases, it stems from a corrupted installation of the SQL Server Native Client or a mismatch between the TDS version expected by the client versus the server.

Step-by-Step Resolution Guide

Step 1: Verify Network Integrity and Packet Handling

  • Run ping -f -l 1472 <SQLServerIP> from the client to check for fragmentation issues or packet loss.
  • Check Windows Server 2025 NIC settings in Device Manager; disable “TCP Checksum Offload” and “Large Send Offload (LSO)” temporarily to rule out NIC driver bugs.
  • Inspect any load balancers or firewalls sitting between the client and server for TCP reassembly issues on port 1433.

Step 2: Update or Reinstall Client Drivers

  • Navigate to the client machine and uninstall outdated connectivity components via Control Panel > Programs and Features (look for “Microsoft OLE DB Driver for SQL Server” or “ODBC Driver”).
  • Download and install the latest Microsoft OLE DB Driver 19+ or ODBC Driver 18+ compatible with SQL Server 2025 from the official Microsoft Download Center.
  • Restart the client application and re-attempt the connection to confirm the TDS handshake completes.

Step 3: Review SQL Server Network Configuration

  • Open SQL Server Configuration Manager on the Windows Server 2025 host.
  • Navigate to SQL Server Network Configuration > Protocols for MSSQLSERVER and ensure TCP/IP is enabled with correct Static Port (default 1433) under the IPAll section.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Step 4: Exclude Security Software Interference

  • Open Windows Defender Firewall with Advanced Security and verify there is no deep packet inspection rule altering traffic on port 1433.
  • Temporarily disable third-party antivirus/endpoint protection software and attempt the connection again to isolate the cause.
  • If the connection succeeds, add an application-specific exclusion for sqlservr.exe and the SQL port in the antivirus configuration.

Step 5: Check SQL Server Error Log for Correlating Details

  • Open SQL Server Management Studio (SSMS) and navigate to Management > SQL Server Logs.
  • Look for entries immediately preceding the 4009 error, such as “A fatal error occurred while reading the input stream from the network,” which confirms a transport-layer issue.
  • Cross-reference the client IP and timestamp to narrow down whether the issue is isolated to a single machine or affects all incoming connections.

Alternative or Verification Steps

  • Use SQL Server Profiler or Extended Events to capture a trace during the next failed connection attempt; confirm no further 4009 errors appear after driver/network changes.
  • If the issue persists only for specific clients, bypass any intermediate proxy/VPN software and connect directly via the server’s IP address to confirm whether routing hardware is the root cause.

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

Troubleshooting Guide: Error 4010 – Incorrect TDS Protocol Stream (Query Notification Header)

Why This Error Happens

This error occurs when the Query Notification request sent to SQL Server contains a malformed TDS header, typically caused by an outdated or mismatched SQL Server Native Client driver on the client application. It can also result from network packet corruption introduced by a misconfigured proxy, firewall, or load balancer sitting between the client and the SQL Server 2025 instance. In some cases, custom applications manually constructing TDS notification requests (via SqlDependency or Service Broker) send improperly formatted message bodies, triggering this validation failure on the server side.

Step-by-Step Resolution Guide

Step 1: Verify and Update Client Drivers

  • Confirm the application is using the latest Microsoft OLE DB Driver or ODBC Driver compatible with SQL Server 2025.
  • On Windows 11 / Windows Server 2025, check installed driver versions via Control Panel > Programs and Features.
  • Update outdated drivers using the official Microsoft Download Center package for “Microsoft ODBC Driver for SQL Server.”
  • Restart the application pool or service after updating to ensure the new driver binaries are loaded.

Step 2: Inspect Service Broker and Query Notification Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to confirm Service Broker is enabled on the target database:
  SELECT is_broker_enabled FROM sys.databases WHERE name = 'YourDatabaseName';
  • If disabled, enable it with:
  ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
  • Validate that the SqlDependency.Start() call in application code is not being invoked multiple times with conflicting connection strings, as this can corrupt the notification queue.

Step 3: Capture and Analyze the TDS Stream

  • Use SQL Server Profiler or Extended Events to capture the raw TDS traffic at the time the error occurs.
  • Filter for Error 4010 events and inspect the packet payload for truncation or unexpected byte sequences.
  • Cross-reference the capture timestamp with any network hardware (firewall, load balancer) logs to rule out mid-stream packet tampering.

Step 4: Check for Network Layer Interference

  • On Windows Server 2025, open Windows Defender Firewall with Advanced Security and confirm no rules are fragmenting or inspecting TCP port 1433 traffic deeply.
  • Disable any third-party antivirus or deep packet inspection (DPI) proxy temporarily to test if the error persists.
  • If using a load balancer, ensure it is configured for raw TCP pass-through rather than TDS-aware inspection, since SQL Server 2025 TDS packets can be rejected if re-encapsulated incorrectly.

Step 5: Reinstall or Repair SQL Server Native Client Components

  • Navigate to Settings > Apps > Installed Apps on Windows 11, search for “SQL Server Native Client.”
  • Select Repair, or uninstall and reinstall using the latest setup package from Microsoft.
  • Re-test the Query Notification subscription after the repair completes.

Alternative or Verification Steps

  • Re-run the application’s notification subscription logic and confirm no Error 4010 entries appear in the SQL Server Error Log (Management > SQL Server Logs in SSMS) over a 24-hour monitoring window.
  • If the issue persists after driver updates, bypass Query Notifications temporarily by switching to a polling-based data refresh mechanism to isolate whether the root cause is TDS-specific or application logic-specific.

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

Microsoft SQL Server 2025 — Error 4008: “The data types varchar(max) … are incompatible”

Why This Error Happens

This error occurs when a T-SQL operation—typically a UNION, concatenation, comparison, or a built-in function like REPLICATE, CHARINDEX, or a CLR/XML operation—attempts to implicitly combine or compare varchar(max)/nvarchar(max)/varbinary(max) large object (LOB) data with an incompatible type, such as text, ntext, image, or a type with a mismatched collation. SQL Server’s query optimizer cannot find an implicit conversion path between the legacy deprecated LOB types (text/ntext/image) and the modern MAX types, so it rejects the operation rather than risk silent data truncation or corruption. This is almost always a schema design issue rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Query and Columns Causing the Conflict

  • Capture the failing statement from SQL Server Management Studio (SSMS) error output or the Windows Application Event Log (Event ID 4008, Source: MSSQLSERVER).
  • Run sp_help 'YourTableName' or query sys.columns joined with sys.types to check the data types of every column involved in the query:
SELECT c.name, t.name AS data_type, c.max_length
FROM sys.columns c
JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID('YourTableName');
  • Look specifically for legacy types: text, ntext, or image mixed with varchar(max), nvarchar(max), or varbinary(max).

Step 2: Convert Legacy LOB Columns to Modern MAX Types

  • Alter any columns still using deprecated types to their MAX equivalents:
ALTER TABLE dbo.YourTableName
ALTER COLUMN YourColumnName VARCHAR(MAX);
  • For ntext → use NVARCHAR(MAX); for image → use VARBINARY(MAX).
  • Note: tables with full-text indexes, replication, or indexed views may need those dependencies dropped before altering, then recreated afterward.

Step 3: Explicitly CAST or CONVERT in the Query Itself

  • If you cannot alter the underlying schema immediately (e.g., third-party vendor tables), wrap the offending column in an explicit conversion inside the query:
SELECT CAST(YourColumn AS VARCHAR(MAX)) FROM dbo.YourTableName
UNION
SELECT CAST(OtherColumn AS VARCHAR(MAX)) FROM dbo.OtherTable;
  • Ensure both sides of UNION, JOIN, or comparison operators use matching target types.

Step 4: Check and Align Collation Settings

  • Run SELECT DATABASEPROPERTYEX('YourDB', 'Collation'); and compare against SELECT collation_name FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName');.
  • If collations differ between the two source tables/columns in a UNION or JOIN, add COLLATE DATABASE_DEFAULT to the conflicting column in your query.

Step 5: Update Client Drivers and Application Code

  • On Windows Server 2025 / Windows 11, confirm you are using the latest Microsoft OLE DB Driver for SQL Server or ODBC Driver 18+, since older drivers (pre-2012 era) mishandle MAX types.
  • Update connection strings and ORM mappings (Entity Framework, Dapper, etc.) to use MAX length definitions instead of legacy fixed-length LOB bindings.

Alternative or Verification Steps

  • Re-run the original query in SSMS after applying the ALTER TABLE or CAST fix — the 4008 error should no longer appear, and result sets should return without truncation warnings.
  • As a quick workaround while planning a full schema migration, use CONVERT(VARCHAR(MAX), column, 0) inline in reporting queries to bypass the type mismatch without altering production tables.

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

Troubleshooting Guide: SQL Server Error 4007

Why This Error Happens

Error 4007 occurs when an INSERT or UPDATE statement attempts to directly write a value into a column that SQL Server computes automatically, such as a computed column, an identity column, a timestamp/rowversion column, or a column backed by a view expression. This typically happens when application code or migration scripts reference a column by name without checking whether its definition was changed to a computed expression, or when a view’s underlying table schema was altered without updating the view. It can also surface after schema drift between development and production environments where a column was converted to a computed type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Review the full error message to capture the exact column name referenced in %.*ls.
  • Run the following query against the target table to check column properties:
SELECT name, is_computed, system_type_id 
FROM sys.columns 
WHERE object_id = OBJECT_ID('YourSchema.YourTable');
  • Confirm whether is_computed = 1 for the flagged column.

Step 2: Correct the INSERT/UPDATE Statement

  • Remove the computed column from the explicit column list in your INSERT INTO (...) statement.
  • If using an UPDATE statement, remove the SET ColumnName = value clause for that specific column.
  • For bulk insert operations via SSIS or bcp, update the mapping file to exclude the computed column, e.g.:
bcp YourDatabase.dbo.YourTable in data.txt -c -t, -S ServerName -T -k

Step 3: Validate View or Schema Definitions

  • If the error originates from a view, run sp_helptext 'ViewName' to inspect the underlying SELECT statement and confirm which columns are derived expressions (e.g., CAST, CASE, or string concatenation).
  • Update application ORM mappings (Entity Framework, Dapper, etc.) to mark the column as database-generated so it is excluded from write operations.
  • Restart the SQL Server service only if you modified computed column definitions via ALTER TABLE:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Rebuild Dependent Objects (If Schema Was Altered)

  • If the column was recently converted to computed, refresh dependent views and stored procedures using sp_refreshview or sp_refreshsqlmodule to ensure cached metadata matches the new schema.
  • Clear the plan cache for the affected database if stale execution plans persist:
DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Re-run the original INSERT/UPDATE statement in SQL Server Management Studio (SSMS) and confirm no Error 4007 is raised; check sys.columns again to ensure the computed flag matches expectations.
  • If the column must accept direct writes, consider removing the computed definition via ALTER TABLE ... DROP COLUMN and recreating it as a standard column, then repopulate data manually.

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

Troubleshooting Guide: SQL Server Error 4006

Why This Error Happens

Error 4006 occurs when a single DELETE statement targets a view or joined query that spans multiple underlying base tables, which the SQL Server engine cannot resolve into a single valid deletion operation. This typically happens when a view lacks an INSTEAD OF trigger to handle the multi-table logic, or when the view’s underlying query joins tables without a clear primary key relationship to isolate the delete target. Additionally, this can surface if a partitioned view is improperly configured, causing the engine to misidentify which partition or table owns the row being removed.

Step-by-Step Resolution Guide

Step 1: Identify the View or Query Causing the Conflict

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) to inspect the view definition.
  • Check whether the FROM clause contains a JOIN between two or more base tables.
  • Confirm whether the view is partitioned by querying sys.views and sys.partitions for metadata flags.

Step 2: Create an INSTEAD OF Trigger to Handle Multi-Table Deletes

  • Navigate to SSMS, open a New Query window connected to the target database.
  • Write a trigger using the following template:
CREATE TRIGGER trg_InsteadOfDelete
ON YourViewName
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM TableA WHERE ID IN (SELECT ID FROM deleted);
    DELETE FROM TableB WHERE ID IN (SELECT ID FROM deleted);
END
  • Save and execute this script to bind the trigger to the problematic view.

Step 3: Split the Delete Operation into Separate Statements

  • Instead of running a single DELETE against the view, issue individual DELETE statements directly against each base table.
  • Use explicit WHERE clauses matching primary keys to ensure referential integrity is preserved.
  • If using an ORM (Entity Framework, Dapper), update the mapping configuration to disable cascading multi-table deletes through the view.

Step 4: Validate Permissions and Schema Bindings

  • Open SQL Server Configuration Manager (Windows Server 2025 / Windows 11 path: C:\Windows\System32\SQLServerManager16.msc).
  • Confirm the executing user has ALTER and CONTROL permissions on the view and underlying tables via sys.database_permissions.
  • Re-bind the view schema using sp_refreshview 'YourViewName' if columns were recently altered.

Alternative or Verification Steps

  • Re-run the original DELETE statement against the view; if Error 4006 no longer appears, the INSTEAD OF trigger is functioning correctly.
  • As an alternative, convert the view into a stored procedure (usp_DeleteFromMultipleTables) that explicitly handles deletion logic across both tables, bypassing the view-based restriction entirely.

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

Troubleshooting Guide: SQL Server Error 4005 — “Cannot Update Columns From More Than One Underlying Table”

Why This Error Happens

This error occurs when an UPDATE statement targets a view that joins two or more base tables, and the columns listed in the SET clause belong to more than one of those underlying tables. SQL Server’s query engine requires that a single UPDATE operation map to exactly one base table per call, since it cannot resolve ambiguous write paths across joined result sets. This is a design restriction of updatable views, not a bug, and typically surfaces when developers migrate reporting views into write-enabled application logic without accounting for view composition.

Step-by-Step Resolution Guide

Step 1: Identify the View Definition and Its Base Tables

  • Run sp_helptext 'YourViewName'; in SQL Server Management Studio (SSMS) to inspect the underlying JOIN structure.
  • Confirm which columns in your UPDATE statement map to which base table — Error 4005 almost always means columns span two tables in the FROM clause.
  • Check the Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) to correlate the Error 4005 timestamp with the exact query submitted.

Step 2: Split the Update Into Separate Statements Per Table

  • Rewrite the single UPDATE into two (or more) discrete UPDATE statements, each targeting only one base table directly.
  • Example: instead of UPDATE vw_CustomerOrders SET CustomerName = @Name, OrderStatus = @Status, issue:
  • UPDATE Customers SET CustomerName = @Name WHERE CustomerID = @ID;
  • UPDATE Orders SET OrderStatus = @Status WHERE CustomerID = @ID;
  • Wrap both statements in a single BEGIN TRAN / COMMIT TRAN block to preserve atomicity if the application requires a transactional guarantee.

Step 3: Use INSTEAD OF Triggers for Persistent Multi-Table Views

  • If the application must keep issuing updates against the view (and cannot be refactored), create an INSTEAD OF UPDATE trigger on the view in SSMS.
  • Inside the trigger, parse the inserted and deleted pseudo-tables and route column updates to the correct base table programmatically.
  • Example skeleton:
  CREATE TRIGGER trg_UpdateView
  ON vw_CustomerOrders
  INSTEAD OF UPDATE
  AS
  BEGIN
      UPDATE c SET c.CustomerName = i.CustomerName
      FROM Customers c JOIN inserted i ON c.CustomerID = i.CustomerID;

      UPDATE o SET o.OrderStatus = i.OrderStatus
      FROM Orders o JOIN inserted i ON o.OrderID = i.OrderID;
  END

Step 4: Validate Application Connection and ORM Layer

  • If the error originates from an Entity Framework, Dapper, or other ORM-generated query, inspect the generated SQL via SQL Server Profiler or Extended Events on Windows Server 2025.
  • Ensure the ORM mapping targets individual tables (not the composite view) for write operations, adjusting entity mappings in the data context configuration file.

Alternative or Verification Steps

  • Re-run the original application transaction and confirm Error 4005 no longer appears in SSMS or the Windows Application Event Log.
  • As a quick validation, execute SELECT * FROM sys.triggers WHERE parent_id = OBJECT_ID('vw_CustomerOrders'); to confirm the INSTEAD OF trigger is active, then test an update against the view directly to ensure both base tables update correctly.

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

Troubleshooting Guide: SQL Server Error 4004 – Unicode Data Cannot Be Sent to Legacy Clients

Why This Error Happens

This error occurs because the client application is connecting to SQL Server 2025 using an outdated communication protocol, specifically DB-Library (DB-Lib) or ODBC driver versions 3.7 or earlier, neither of which support the transmission of Unicode (nchar, nvarchar, ntext) data types. Since SQL Server 2025 relies heavily on Unicode-only collations for internationalization, the legacy driver stack lacks the necessary API calls to decode the UCS-2/UTF-16 stream being sent by the server. Essentially, the client driver is too old to understand the modern data format required by the server instance.

Step-by-Step Resolution Guide

Step 1: Identify the Outdated Driver Component

  • Check the specific client tool generating the error (e.g., ISQL, older OLE DB applications, or legacy ODBC connections).
  • Navigate to Control Panel > Administrative Tools > ODBC Data Sources (64-bit) to check the version number of the currently configured DSN (Data Source Name).
  • Look for drivers named “SQL Server” (the legacy driver) rather than “ODBC Driver 17/18 for SQL Server.”

Step 2: Install the Modern Microsoft ODBC Driver

  • Download and install the Microsoft ODBC Driver 18 for SQL Server from the official Microsoft Download Center.
  • Run the installer on the Windows Server 2025 / Windows 11 machine with Administrator privileges.
  • Verify installation path integrity at C:\Windows\System32\msodbcsql18.dll.

Step 3: Reconfigure the Data Source Name (DSN)

  • Open the ODBC Data Source Administrator tool again.
  • Select the problematic DSN and click Configure.
  • Change the “Driver” dropdown from the legacy SQL Server driver to ODBC Driver 18 for SQL Server.
  • Re-enter the Server name and Authentication credentials to refresh the connection string.

Step 4: Update the Connection String in Application Code

  • If the error stems from a custom application rather than a GUI tool, locate the web.config or app.config file.
  • Update the Provider or Driver keyword in the connection string from {SQL Server} to {ODBC Driver 18 for SQL Server}.
  • Save the file and recycle the Application Pool (IIS) or restart the service to apply changes.

Step 5: Adjust Database Collation (If Driver Update is Not Feasible)

  • If legacy hardware restricts driver updates, open SQL Server Management Studio (SSMS).
  • Run a script to alter the specific column collation from a Unicode-only type (like Latin1_General_100_CI_AS_SC) to a standard Windows collation that supports non-Unicode clients.
  • Note: This is a workaround and may affect character support for special symbols.

Alternative or Verification Steps

  • Verification: Re-run the specific query or stored procedure that triggered Error 4004 via the updated connection; the data should now render correctly in the client’s grid/text view instead of throwing a conversion error.
  • Alternative: If updating ODBC is not possible, use the SQL Server Native Client (SNAC) or switch the client application to use ADO.NET, which fully supports Unicode data types natively.

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

Troubleshooting Guide: SQL Server Error 4002 – Incorrect TDS Protocol Stream

Why This Error Happens

This error typically occurs when the Tabular Data Stream (TDS) packets sent between the client and SQL Server 2025 are malformed, truncated, or interrupted mid-transmission. Common root causes include network instability or packet fragmentation, a mismatch between the client driver version and the server’s TDS protocol version, or interference from a firewall/antivirus application inspecting and altering the traffic. It can also result from an unstable or improperly closed connection pool on the application side.

Step-by-Step Resolution Guide

Step 1: Verify Network Stability and Packet Integrity

  • Run ping -t <ServerName> for an extended period to check for packet loss or latency spikes.
  • Check for network card driver issues in Windows 11/Server 2025 via Device Manager.
  • Disable TCP Chimney Offload and Receive Side Scaling (RSS) temporarily using netsh int tcp set global rss=disabled to rule out NIC offloading bugs.

Step 2: Update Client Drivers and Connection Strings

  • Ensure the client is using the latest Microsoft ODBC Driver or OLE DB Driver compatible with SQL Server 2025.
  • Check the application’s connection string for Encrypt and TrustServerCertificate settings, as TLS handshake failures can sometimes manifest as TDS stream errors.
  • Update the driver via the official Microsoft Download Center rather than relying on cached OS drivers.

Step 3: Adjust SQL Server Network Configuration

  • Open SQL Server Configuration Manager.
  • Navigate to SQL Server Network Configuration > Protocols for MSSQLSERVER.
  • Ensure “TCP/IP” is enabled and check the IPAll section to verify the correct Port (default 1433) is set without conflicting duplicate entries.
  • Restart the MSSQLSERVER service to apply changes.

Step 4: Check Firewall and Antivirus Packet Inspection

  • Temporarily disable Windows Defender Firewall or third-party antivirus software to see if the error persists.
  • If disabling resolves the issue, create a specific inbound/outbound rule for port 1433 to exclude SQL traffic from deep packet inspection.
  • Verify no Intrusion Detection System (IDS) is truncating large TDS packets sent during bulk data transfers.

Alternative or Verification Steps

  • Run a test query via SQL Server Management Studio (SSMS) immediately after applying the fixes to ensure the connection remains stable for at least 10 minutes without dropping.
  • If the error persists only during large data transfers, set the Network Packet Size property in the connection string to a lower value (e.g., 4096) to prevent oversized TDS packets from being rejected by intermediary network hardware.

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

Troubleshooting Guide: SQL Server Error 3999 – Failed to Flush Commit Table to Disk

Why This Error Happens

Error 3999 occurs when SQL Server’s In-Memory OLTP engine cannot persist the commit table (part of the transaction log/checkpoint process for memory-optimized filegroups) to disk. This is typically caused by underlying storage I/O failures, insufficient disk space on the volume hosting the memory-optimized filegroup, file system corruption, or the SQL Server service account lacking write permissions to the container files. It can also surface when the storage subsystem returns a hardware-level error (such as a stale file handle or disk timeout) that propagates up through the database engine.

Step-by-Step Resolution Guide

Step 1: Review the SQL Server Error Log for the Underlying Error Code

  • Open SQL Server Management Studio (SSMS) and navigate to Management > SQL Server Logs, or check the raw log file at C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Locate the accompanying error number referenced in the message (error %d) — this is usually a Windows OS error code (e.g., 1450 “Insufficient system resources” or 112 “Disk full”).
  • Cross-reference the OS error code using net helpmsg <error_code> in an elevated Command Prompt to get a plain-language description.

Step 2: Verify Disk Space and Storage Health on the Memory-Optimized Filegroup Volume

  • Run the following query to identify the physical path of the memory-optimized filegroup container:
SELECT name, physical_name FROM sys.database_files WHERE type_desc = 'FILESTREAM';
  • Check free space on that volume using Get-PSDrive in PowerShell or File Explorer; ensure at least 15-20% free space is available.
  • Run chkdsk <drive>: /f /r during a maintenance window if disk corruption is suspected, and review Windows Event Viewer (System log) for Disk or NTFS warnings.

Step 3: Confirm Service Account Permissions on the Database Container Folder

  • Navigate to the folder housing the memory-optimized filegroup (commonly under D:\SQLData\<DBName>\<FilegroupName>).
  • Right-click the folder, select Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER or a custom domain account) has Full Control.
  • If permissions are missing, grant them via icacls "D:\SQLData\<DBName>" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)F.

Step 4: Restart the SQL Server Service and Force a Manual Checkpoint

  • Restart the SQL Server service via services.msc or run Restart-Service MSSQLSERVER in an elevated PowerShell session.
  • Once the database is back online, manually force a checkpoint to retest the flush operation:
USE [YourDatabaseName];
CHECKPOINT;
  • Monitor the ERRORLOG immediately after to confirm Error 3999 does not reoccur.

Step 5: Rebuild or Restore the Affected Database if Corruption Persists

  • If the error persists after confirming disk space, permissions, and hardware health, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS to check for underlying corruption.
  • If corruption is confirmed in the memory-optimized filegroup, restore the database from the last known good backup, as memory-optimized data/delta files generally cannot be repaired in place.

Alternative or Verification Steps

  • Verify the fix by inserting/updating a test row in a memory-optimized table and running CHECKPOINT again — confirm no new entries for Error 3999 appear in the ERRORLOG.
  • As an alternative diagnostic path, enable Extended Events with the sqlserver.error_reported event filtered on error number 3999 to capture the exact query and session context the next time the failure occurs.

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

Troubleshooting Guide: SQL Server Error 4001 — “Client Sends spresetconnection While There Is Still Pending Requests”

Why This Error Happens

This error occurs when the Tabular Data Stream (TDS) protocol detects that a client-side connection pool attempted to reset and reuse a connection via sp_reset_connection before the server finished processing an outstanding batch or result set from a prior command. This typically results from improper connection handling in application code, such as failing to fully read or cancel a DataReader before returning the connection to the pool, or from MARS (Multiple Active Result Sets) misconfiguration. It can also surface after driver mismatches between the client library (ODBC, OLE DB, or ADO.NET) and SQL Server 2025, which enforces stricter TDS state validation than previous versions.

Step-by-Step Resolution Guide

Step 1: Audit Application Connection Handling

  • Review application code for any SqlDataReader, SqlCommand, or similar objects that are not explicitly closed or disposed before the connection is returned to the pool.
  • Ensure every DataReader is wrapped in a using block or explicitly calls .Close()/.Dispose().
  • Check for asynchronous calls (ExecuteReaderAsync, ExecuteNonQueryAsync) that are not properly awaited, as this is the most common cause of orphaned pending requests.

Step 2: Enable and Verify MARS Configuration

  • Open the connection string used by the application and confirm whether MultipleActiveResultSets=True is required for your workload.
  • If MARS is enabled unintentionally, disable it unless the application explicitly handles multiple concurrent result sets, since MARS increases the risk of this race condition.
  • Update the connection string in web.config, app.config, or the relevant application settings file, for example:
    Server=myServer;Database=myDB;MultipleActiveResultSets=False;TrustServerCertificate=True;

Step 3: Update SQL Server Native Client / Driver Stack

  • On Windows Server 2025 / Windows 11, confirm the client is using the latest Microsoft ODBC Driver 18+ or Microsoft.Data.SqlClient (not the legacy System.Data.SqlClient).
  • Navigate to Control Panel > Programs > Programs and Features to check installed driver versions, or run:
    Get-OdbcDriver | Where-Object {$_.Name -like "*SQL Server*"}
  • Reinstall or update via the official Microsoft Download Center package matching SQL Server 2025 compatibility requirements.

Step 4: Adjust Connection Pooling Settings

  • In the application’s connection string, reduce Max Pool Size temporarily and set Pooling=True with a lower Connection Lifetime to force more frequent, cleaner connection resets.
  • For IIS-hosted applications, recycle the Application Pool via IIS Manager > Application Pools > Recycle after configuration changes to clear any stale pooled connections.

Step 5: Enable Extended Events Tracing for Confirmation

  • Open SQL Server Management Studio (SSMS) and navigate to Management > Extended Events > Sessions.
  • Create a new session capturing the sqlserver.error_reported event, filtered on Error Code 4001, to capture the exact query/session triggering the reset conflict.
  • Correlate the captured session_id with the application thread to pinpoint the exact faulty code path.

Alternative or Verification Steps

  • After applying fixes, monitor the SQL Server Error Log (Management > SQL Server Logs in SSMS) for 24–48 hours to confirm Error 4001 no longer appears.
  • If the issue persists, as a temporary workaround, disable connection pooling entirely (Pooling=False in the connection string) to isolate whether the pool itself is the root cause versus an application logic defect.

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

Troubleshooting Guide: SQL Server Error 3998 — “Uncommittable Transaction Detected at End of Batch”

Why This Error Happens

This error occurs when a transaction within a batch encounters an unhandled exception (such as a severity-level error, constraint violation, or explicit ROLLBACK mismatch) that leaves it in an uncommittable state, but the batch continues executing without checking XACT_STATE(). SQL Server 2025, by default, requires explicit handling of doomed transactions (XACT_STATE() = -1), and without a TRY...CATCH block that properly detects this state, the engine forcibly rolls back the transaction at the end of the batch. This is frequently caused by missing error-handling logic in stored procedures, triggers, or application-level T-SQL scripts rather than a server configuration fault.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Transaction Block

  • Review the stored procedure, trigger, or ad-hoc script referenced in the error log around Event ID 3998.
  • Check SQL Server Logs via SQL Server Management Studio (SSMS) > Management > SQL Server Logs or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025.
  • Look for the specific batch or query that precedes the 3998 error to isolate the transaction scope.

Step 2: Implement Proper TRY…CATCH Error Handling

  • Wrap the transaction logic in a BEGIN TRY...END TRY and BEGIN CATCH...END CATCH block.
  • Inside the CATCH block, check the transaction state using:
  IF XACT_STATE() = -1
      ROLLBACK TRANSACTION;
  ELSE IF XACT_STATE() = 1
      COMMIT TRANSACTION;
  • Ensure every BEGIN TRANSACTION has a corresponding conditional COMMIT or ROLLBACK based on XACT_STATE(), not just @@ERROR.

Step 3: Adjust SET XACT_ABORT Configuration

  • Add SET XACT_ABORT ON; at the top of the affected stored procedure or script.
  • This forces SQL Server to automatically roll back the entire transaction on a runtime error, preventing orphaned uncommittable states.
  • Deploy the updated script via SSMS or Azure Data Studio and redeploy to any linked CI/CD pipelines targeting Windows Server 2025 instances.

Step 4: Validate Nested Transaction Logic

  • Check for nested BEGIN TRANSACTION calls using @@TRANCOUNT to ensure counts are balanced.
  • Avoid mixing SAVE TRANSACTION logic with full rollbacks without explicitly managing savepoints.
  • Refactor any legacy code using bare ROLLBACK without specifying the transaction name/savepoint if nested transactions are present.

Step 5: Restart the SQL Server Service (If Session State Persists)

  • Open Services.msc on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart.
  • This clears any lingering session-level transaction states that may be causing repeated 3998 errors across connections.

Alternative or Verification Steps

  • Run the corrected stored procedure or script manually in SSMS and confirm no Error 3998 appears in the Messages tab, then verify @@TRANCOUNT returns to 0 after execution.
  • If the error persists under high concurrency, enable Extended Events (xEvents) with the error_reported event filtered to Error 3998 to capture the exact query and session causing the doomed transaction for deeper analysis.

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

Troubleshooting Guide: Error 3997 – MARS Batch Transaction Still Active at End of Batch

Why This Error Happens

This error occurs when Multiple Active Result Sets (MARS) is enabled on a connection, and an application explicitly begins a transaction (via BEGIN TRANSACTION) inside one batch but fails to commit or roll it back before that batch completes execution. SQL Server 2025 enforces strict transactional boundaries within MARS sessions, and leaving a transaction open across batch boundaries violates connection state integrity. As a safeguard against orphaned locks and inconsistent session state, SQL Server automatically rolls back the incomplete transaction and raises Error 3997.

Step-by-Step Resolution Guide

Step 1: Audit the Application’s Transaction Logic

  • Review the client code (ADO.NET, ODBC, or JDBC) for any BEGIN TRAN statements that are not matched with a corresponding COMMIT TRAN or ROLLBACK TRAN within the same batch execution.
  • Pay close attention to conditional branches (IF/ELSE) where an error path might skip the commit/rollback logic.
  • Search stored procedures for early RETURN statements that bypass transaction closure.

Step 2: Verify MARS Connection String Settings

  • Open the application’s configuration file (e.g., web.config, app.config, or connection string source).
  • Confirm MultipleActiveResultSets=True; is actually required for the workload; if not, disabling it forces sequential batch execution and prevents this specific error class.
  • If MARS is required, ensure the driver version supports SQL Server 2025 transactional semantics (update to the latest Microsoft.Data.SqlClient via NuGet or the ODBC Driver 18+ from the Microsoft Download Center).

Step 3: Implement Explicit TRY/CATCH with Transaction Handling

  • Wrap all transaction logic in T-SQL using BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH.
  • Inside the CATCH block, add logic to check XACT_STATE():
  • If XACT_STATE() = -1, force a ROLLBACK TRANSACTION.
  • If XACT_STATE() = 1, issue a COMMIT or ROLLBACK as appropriate before exiting the batch.

Step 4: Enable Session-Level Tracing for Validation

  • Use SQL Server Profiler or Extended Events (XEvents) on the Windows Server 2025 instance to capture error_reported events filtered by Error Number 3997.
  • Correlate the captured batch_text with the specific client session to pinpoint which stored procedure or ad-hoc query is leaving the transaction open.

Alternative or Verification Steps

  • Verify the Fix: Run the application under load and query sys.dm_tran_active_transactions joined with sys.dm_tran_session_transactions to confirm no transactions remain in an uncommitted state after batch execution.
  • Alternative Solution: If refactoring the application code is not immediately feasible, set SET XACT_ABORT ON at the top of the stored procedure; this forces SQL Server to automatically roll back and terminate the batch immediately upon encountering a runtime error, preventing the transaction from persisting into an invalid state.

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

Troubleshooting Guide: Error 3996 — Snapshot Isolation Not Supported for Distributed Transaction

Why This Error Happens

This error occurs because SQL Server 2025 does not allow the SNAPSHOT or READ COMMITTED SNAPSHOT isolation level to be used once a transaction has been promoted to a distributed transaction via MSDTC (Microsoft Distributed Transaction Coordinator). It is typically triggered when a session with ALLOW_SNAPSHOT_ISOLATION or READ_COMMITTED_SNAPSHOT enabled on the database attempts to enlist in a linked server call, a BEGIN DISTRIBUTED TRANSACTION, or a cross-database transaction that spans multiple instances. The underlying engine architecture simply does not support versioning-based consistency models across a two-phase commit boundary.

Step-by-Step Resolution Guide

Step 1: Identify the Query or Procedure Triggering the Error

  • Check the application connection string or session settings for SET TRANSACTION ISOLATION LEVEL SNAPSHOT.
  • Review SQL Server logs and SSMS error output to locate the exact stored procedure or linked server call causing the promotion to a distributed transaction.
  • Use sys.dm_tran_active_transactions and sys.dm_tran_session_transactions to confirm if the transaction is distributed.

Step 2: Change the Isolation Level for the Affected Session

  • Explicitly set the isolation level before the transaction begins:
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
  BEGIN TRANSACTION;
  -- your distributed/linked server query here
  COMMIT TRANSACTION;
  • Avoid using READ_COMMITTED_SNAPSHOT or SNAPSHOT for any code path that touches linked servers or BEGIN DISTRIBUTED TRANSACTION.
  • If the database-level default is SNAPSHOT, override it at the session level rather than changing the database default globally.

Step 3: Isolate Distributed Transaction Logic from Snapshot-Dependent Code

  • Refactor stored procedures so that distributed transaction calls run in a separate batch/session that does not inherit SNAPSHOT isolation.
  • If using .NET or ODBC drivers, ensure Enlist=true connections default to READ COMMITTED unless explicitly required otherwise.
  • For linked server queries, confirm remote proc transaction promotion settings via:
  EXEC sp_configure 'remote proc trans', '1';
  RECONFIGURE;

Step 4: Verify MSDTC Configuration on Windows Server 2025 / Windows 11

  • Open Component Services (dcomcnfg.exe) → Computers → My Computer → Distributed Transaction Coordinator → Local DTC.
  • Confirm Network DTC Access is enabled and that “Allow Inbound/Outbound” transactions are permitted if the query spans remote instances.
  • Restart the MSDTC service after any configuration change:
  Restart-Service MSDTC

Alternative or Verification Steps

  • Re-run the failing transaction after setting isolation level to READ COMMITTED or SERIALIZABLE; confirm no Error 3996 appears in SQL Server logs or sys.messages.
  • If the issue persists, avoid distributed transactions altogether by using application-level two-phase logic (e.g., saga pattern) or linked server queries wrapped in local transactions only.

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

Troubleshooting Guide: SQL Server Error 3995 — “Unknown Transaction Isolation Level %d”

Why This Error Happens

This error occurs when SQL Server’s transaction manager receives an isolation level value that does not map to any of the recognized levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable, or Snapshot). It is typically caused by a corrupted connection string parameter, a driver mismatch between the client API (ODBC/OLE DB/ADO.NET) and SQL Server 2025, or a malformed bitmask value passed programmatically via SET TRANSACTION ISOLATION LEVEL. In rare cases, it can also surface due to memory corruption in the session context or an outdated client-side provider that does not recognize newer isolation level enumerations introduced in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the Client Driver and Provider Versions

  • Confirm you are using the latest Microsoft OLE DB Driver (MSOLEDBSQL19) or ODBC Driver 18+ compatible with SQL Server 2025.
  • Check installed driver version via Control Panel > Programs > Programs and Features on Windows Server 2025/Windows 11.
  • Update outdated drivers from the official Microsoft Download Center and restart the application.

Step 2: Inspect and Correct the Connection String / Application Code

  • Search application code or ORM configuration (Entity Framework, JDBC, etc.) for manually set isolation level integers instead of named constants.
  • Replace raw integer values with proper enumerations, for example in T-SQL:
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
  • In ADO.NET, ensure IsolationLevel enum values map correctly (avoid using IsolationLevel.Unspecified directly in BeginTransaction()).

Step 3: Validate SQL Server Configuration and Compatibility Level

  • Open SQL Server Management Studio (SSMS) and run:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure compatibility level is set to 170 (SQL Server 2025) using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (Run as Administrator).

Step 4: Check for Corrupted System Files or Memory Issues

  • Run DBCC CHECKDB('YourDatabaseName') to rule out database corruption affecting session metadata.
  • On Windows Server 2025/Windows 11, run sfc /scannow in an elevated Command Prompt to repair corrupted system files that might affect the SQL Server service.

Alternative or Verification Steps

  • Re-run the failing transaction/query after driver and compatibility updates; confirm no Error 3995 appears in SQL Server Error Logs (EXEC sp_readerrorlog;).
  • If the issue persists, create a minimal repro script using SET TRANSACTION ISOLATION LEVEL SNAPSHOT; directly in SSMS to isolate whether the issue is client-side (driver/code) or server-side (corrupted metadata).

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

Troubleshooting Guide: SQL Server Error 3994 — “User Defined Routine” Failure

Why This Error Happens

Error 3994 typically occurs when a user-defined routine (function, stored procedure, or CLR assembly) encounters an unhandled exception during execution, often due to corrupted or outdated CLR assembly bindings within SQL Server 2025. This can also stem from insufficient permissions on the TRUSTWORTHY database property or missing SQL Server service account access to the referenced assembly files. In some cases, the issue arises from version mismatches between the .NET runtime used by Windows Server 2025 and the CLR integration expected by SQL Server.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Status

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run SELECT * FROM sys.configurations WHERE name = 'clr enabled'; to confirm CLR is active.
  • If disabled, enable it using sp_configure 'clr enabled', 1; RECONFIGURE;

Step 2: Check Assembly and Permission Integrity

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Assemblies.
  • Right-click the relevant assembly and select Script Assembly as > DROP and CREATE to refresh its binary definition.
  • Ensure the database has TRUSTWORTHY set correctly: ALTER DATABASE [YourDB] SET TRUSTWORTHY ON; (only if the source is verified safe).
  • Confirm the SQL Server service account has Read & Execute permissions on the assembly’s source .dll path, typically under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.

Step 3: Update and Restart SQL Server Services

  • Open Services.msc on Windows Server 2025 and locate SQL Server (MSSQLSERVER).
  • Restart the service to clear any cached execution plans tied to the faulty routine.
  • Apply the latest Cumulative Update (CU) for SQL Server 2025 via SQL Server Setup > Maintenance Wizard to patch known CLR execution bugs.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 3994 and check the SQL Server Error Log (via EXEC sp_readerrorlog;) to confirm no further CLR-related exceptions appear.
  • If the error persists, consider recompiling the routine entirely using sp_recompile '[RoutineName]'; or rebuilding the assembly from source code to rule out binary corruption.

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

Why This Error Happens

Error 3993 occurs when a trigger, user-defined function, or stored procedure begins an explicit transaction (via BEGIN TRAN) but the routine terminates—either by completing execution or hitting an unhandled exception—before issuing a matching COMMIT or ROLLBACK. SQL Server 2025 enforces strict transaction nesting rules, so any mismatch between @@TRANCOUNT at the start and end of the routine triggers this error to prevent orphaned transactions. This is almost always a code-level issue rather than a server configuration problem, often surfacing after a migration to SQL Server 2025 due to its updated transaction validation engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Routine

  • Check the SQL Server error log (via SSMS or xp_readerrorlog) for the exact stored procedure, trigger, or function name referenced in the 3993 message.
  • Use DBCC INPUTBUFFER(<session_id>) or Extended Events to capture the exact statement that caused the failure in real time.
  • Note the @@TRANCOUNT value logged alongside the error for context on how deep the nesting went.

Step 2: Audit the Transaction Logic in the Code

  • Open the routine in SSMS or Azure Data Studio and search for BEGIN TRAN, COMMIT, and ROLLBACK keywords.
  • Verify every code branch (including CATCH blocks, early RETURN statements, and IF/ELSE conditions) has a corresponding COMMIT or ROLLBACK for every BEGIN TRAN.
  • Pay special attention to nested triggers or procedures calling other procedures that also manage transactions—this is the most common cause of mismatched counts.

Step 3: Implement TRY…CATCH with Proper Rollback Handling

  • Wrap the transactional logic in a BEGIN TRY...END TRY / BEGIN CATCH...END CATCH block.
  • Inside the CATCH block, add:
IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  • Ensure SET XACT_ABORT ON; is declared at the top of the procedure/trigger to force automatic rollback on severe errors, reducing the chance of a dangling transaction state.

Step 4: Test in an Isolated Environment

  • Deploy the corrected routine to a Windows Server 2025 test instance or a local Windows 11 development environment with SQL Server 2025 installed.
  • Run the original failing transaction/workload against the patched code and monitor @@TRANCOUNT before and after execution using PRINT or SELECT @@TRANCOUNT debug statements.

Step 5: Deploy and Monitor in Production

  • Push the validated script to production during a low-traffic maintenance window.
  • Enable SQL Server Agent alerts for Error 3993 (Severity 16) so any recurrence is immediately flagged via email or SCOM notification.

Alternative or Verification Steps

  • Run DBCC OPENTRAN on the affected database immediately after reproducing the workload to confirm no transaction is left open.
  • If the error persists despite code fixes, temporarily enable Trace Flag 3609 on a test instance to get verbose transaction-state logging, which helps pinpoint exactly where the trancount drifts.

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

Why This Error Happens

Error 3991 occurs when a COMMIT or ROLLBACK statement is executed inside a stored procedure, trigger, or user-defined function that terminates the outer transaction context that was already active before the routine was called. SQL Server 2025 strictly enforces transaction nesting rules, and modifying the parent transaction’s state from within a nested routine is not permitted. This is typically caused by poorly designed error-handling logic (e.g., a TRY...CATCH block issuing a blind ROLLBACK without checking @@TRANCOUNT) or legacy code migrated from older SQL Server versions that didn’t enforce this as strictly.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Routine

  • Check the full error message text — it names the specific procedure, trigger, or function (e.g., “…inside of it, which is not allowed” will reference the object name).
  • Open SQL Server Management Studio (SSMS) and script out the object using sp_helptext 'YourProcName' or right-click → Modify.
  • Look specifically for COMMIT TRANSACTION, ROLLBACK TRANSACTION, or COMMIT WORK statements inside TRY...CATCH blocks.

Step 2: Fix the Transaction Logic

  • Wrap rollback logic with a check against XACT_STATE() instead of blindly calling ROLLBACK:
IF XACT_STATE() <> 0
    ROLLBACK TRANSACTION;
  • Avoid starting a new BEGIN TRANSACTION inside a routine if one is already active; use SAVE TRANSACTION (savepoints) instead for nested logic.
  • Ensure every BEGIN TRY has a matching CATCH block that does not terminate a transaction it did not start.

Step 3: Validate Transaction Count Before Exit

  • Add a check at the end of the routine to confirm @@TRANCOUNT matches the value captured on entry:
DECLARE @TranCountStart INT = @@TRANCOUNT;
-- routine logic here
IF @@TRANCOUNT <> @TranCountStart
    RAISERROR('Transaction count mismatch detected', 16, 1);
  • Deploy the corrected object using ALTER PROCEDURE or ALTER FUNCTION via SSMS or sqlcmd.

Step 4: Clear Cached Execution Plans

  • After altering the object, run DBCC FREEPROCCACHE (or targeted sp_recompile 'YourProcName') to ensure Windows Server 2025’s SQL Server instance isn’t executing a stale, cached version of the faulty logic.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER if the issue persists after recompilation.

Alternative or Verification Steps

  • Re-run the original query or application transaction that triggered Error 3991 and confirm it completes without raising the exception; check SQL Server Logs (Management → SQL Server Logs in SSMS) for recurrence.
  • If the error persists, enable Extended Events (xp_trace or the “Errors and Warnings” template) to capture the exact call stack and transaction state at the moment of failure for deeper root-cause analysis.

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

Troubleshooting Guide: SQL Server Error 3992 – “Transaction Count Has Been Changed Inside of User Defined Routine”

Why This Error Happens

This error occurs when a stored procedure, function, or trigger commits or rolls back a transaction that it did not explicitly begin, causing a mismatch between the @@TRANCOUNT value when the routine started versus when it exited. SQL Server 2025 enforces strict transaction nesting rules, and any unbalanced BEGIN TRAN/COMMIT/ROLLBACK logic inside a user-defined routine will trigger this error to prevent silent data integrity issues. This is almost always a code-level defect rather than a server configuration or permissions problem, often introduced after a migration, stored procedure update, or ORM-generated batch script.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Routine

  • Check the SQL Server error log or Windows Event Viewer (Applications and Services Logs > MSSQLSERVER) for the exact procedure name referenced alongside Error 3992.
  • Run the following to capture the current transaction count context:
SELECT @@TRANCOUNT AS CurrentTranCount;
  • Use SQL Server Profiler or Extended Events (sqlserver.error_reported) filtered on Error Number = 3992 to capture the exact batch and session that triggered it.

Step 2: Audit the Transaction Logic in the Procedure

  • Open the procedure definition using SSMS or Azure Data Studio:
EXEC sp_helptext 'YourSchema.YourProcedureName';
  • Look specifically for unmatched COMMIT TRAN, ROLLBACK TRAN, or COMMIT WORK statements, especially inside TRY...CATCH blocks or conditional branches (IF/ELSE) where one path commits/rolls back and another does not.
  • Confirm that every BEGIN TRANSACTION has a corresponding COMMIT or ROLLBACK within the same scope, and that nested calls do not issue a blanket ROLLBACK that wipes out the caller’s transaction unexpectedly.

Step 3: Standardize Transaction Handling with SAVE TRAN or TRY/CATCH Pattern

  • Rewrite the routine using a consistent pattern that tracks the starting @@TRANCOUNT:
DECLARE @TranCountStart INT = @@TRANCOUNT;
BEGIN TRY
    IF @TranCountStart = 0
        BEGIN TRANSACTION;
    -- business logic here
    IF @TranCountStart = 0
        COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > @TranCountStart
        ROLLBACK TRANSACTION;
    THROW;
END CATCH;
  • Deploy the corrected procedure using ALTER PROCEDURE and test it in a staging environment before pushing to production on Windows Server 2025.

Step 4: Validate XACT_ABORT and Nested Trigger Settings

  • Ensure SET XACT_ABORT ON; is declared at the top of the routine to force automatic rollback on error, preventing orphaned transactions.
  • Check sys.configurations for nested triggers and remote proc trans settings, as these can compound transaction count mismatches in multi-server or linked-server calls:
EXEC sp_configure 'nested triggers';

Alternative or Verification Steps

  • Re-execute the original failing batch or application workflow and monitor @@TRANCOUNT before and after the call using PRINT @@TRANCOUNT; to confirm it returns to the expected baseline (usually 0 at the outermost scope).
  • If the error persists in a third-party or vendor-supplied procedure that cannot be modified, wrap the call in your own transaction-safe wrapper procedure that isolates the external call using SAVE TRANSACTION savepoints instead of full BEGIN TRAN.

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

Troubleshooting Guide: SQL Server Error 3989 — “New request is not allowed to start because it should come with valid transaction descriptor”

Why This Error Happens

This error occurs when a distributed or marked transaction becomes orphaned or invalid on the SQL Server session, typically because the client application attempted to reuse a transaction descriptor after the original transaction was aborted, timed out, or the connection pool returned a stale enlisted transaction. It frequently surfaces after MSDTC (Microsoft Distributed Transaction Coordinator) communication failures, abrupt network interruptions during a distributed transaction, or when connection pooling hands back a connection still bound to a dead transaction context. In some cases, corrupted or mismatched MSDTC configuration between the application server and SQL Server 2025 instance on Windows Server 2025 triggers this behavior.

Step-by-Step Resolution Guide

Step 1: Verify and Restart MSDTC Service

  • Open Services.msc on both the SQL Server host and the application server.
  • Locate Distributed Transaction Coordinator, right-click, and select Restart.
  • Confirm the service is set to Automatic startup type to prevent recurrence after reboot.
  • Run msdtc -resetlog from an elevated Command Prompt if the service fails to start cleanly.

Step 2: Reconfigure MSDTC Security Settings

  • Open Component Services (dcomcnfg.exe) → Component Services > Computers > My Computer > Distributed Transaction Coordinator > Local DTC.
  • Right-click Local DTC, choose Properties, and go to the Security tab.
  • Enable Network DTC Access, Allow Inbound, Allow Outbound, and set Transaction Manager Communication to No Authentication Required (or Mutual Authentication if domain policy requires it).
  • Apply changes and restart the MSDTC service when prompted.

Step 3: Audit Application Connection Pooling and Transaction Handling

  • Review application code for any SqlConnection or ADO.NET objects that reuse a TransactionScope after it has been disposed or timed out.
  • Ensure Enlist=true is correctly set in the connection string only when distributed transactions are intended.
  • Reduce Connection Lifetime in the connection string to force pooled connections to recycle more frequently, preventing stale transaction descriptors from being reused.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Check SQL Server Configuration Manager for the current build version.
  • Download and apply the latest Cumulative Update (CU) from Microsoft, as transaction descriptor handling bugs are periodically patched.
  • Reboot the server after installation and confirm via SELECT @@VERSION; in SQL Server Management Studio (SSMS).

Step 5: Review SQL Server Error Logs and Extended Events

  • Open SSMS and navigate to Management > SQL Server Logs.
  • Search for correlating Error 3989 entries alongside any MSDTC or network-related warnings.
  • Set up an Extended Events session tracking sqlserver.error_reported filtered on Error 3989 to capture the exact query/session triggering the fault for deeper diagnosis.

Alternative or Verification Steps

  • Verify the fix by running a test distributed transaction (e.g., BEGIN DISTRIBUTED TRANSACTION) from both an SSMS query window and the application layer, confirming it commits/rolls back without triggering Error 3989.
  • If the issue persists, as a workaround, disable connection pooling temporarily (Pooling=false in the connection string) to isolate whether the descriptor corruption originates from pooled connection reuse versus a genuine MSDTC/network failure.

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

Troubleshooting Guide: Error 3990 – “Transaction Is Not Allowed to Commit Inside of a User Defined Routine”

Why This Error Happens

This error occurs because SQL Server 2025 does not permit a stored procedure, trigger, or user-defined function to commit or roll back a transaction that it did not explicitly begin itself. Typically, this happens when a nested stored procedure calls COMMIT TRANSACTION or ROLLBACK TRANSACTION without matching the exact transaction count (@@TRANCOUNT) at the scope in which it was opened. It can also surface when a trigger attempts to manage transaction state directly, which violates SQL Server’s strict transaction nesting rules.

Step-by-Step Resolution Guide

Step 1: Audit the Transaction Nesting in Your Code

  • Open the stored procedure or routine referenced in the error log and locate every BEGIN TRAN, COMMIT, and ROLLBACK statement.
  • Check the value of @@TRANCOUNT before and after each block to ensure the routine isn’t closing a transaction it did not open.
  • Run the following diagnostic query to capture the current transaction state during execution:
  SELECT @@TRANCOUNT AS CurrentTranCount;

Step 2: Refactor the Routine to Use SAVEPOINTS Instead of Direct Commits

  • Replace internal COMMIT TRANSACTION calls within nested procedures with SAVE TRANSACTION (savepoints) so only the outermost caller controls the final commit.
  • Update the routine logic as follows:
  BEGIN TRY
      SAVE TRANSACTION MySavePoint;
      -- business logic here
  END TRY
  BEGIN CATCH
      ROLLBACK TRANSACTION MySavePoint;
  END CATCH
  • Ensure the outermost calling script (not the inner procedure) is solely responsible for the final COMMIT.

Step 3: Validate Trigger Logic (If Applicable)

  • If the error originates from an INSTEAD OF or AFTER trigger, remove any explicit COMMIT or ROLLBACK statements inside the trigger body.
  • Triggers should rely on RAISERROR or THROW to signal failure, allowing the calling transaction scope to decide whether to roll back.
  • Re-deploy the modified trigger using SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.

Step 4: Check XACT_ABORT and Transaction Isolation Settings

  • Verify that SET XACT_ABORT ON; is declared at the top of the routine to ensure automatic rollback on runtime errors, preventing orphaned transaction states.
  • Confirm the connection string used by the application (especially if running on Windows 11 client machines) isn’t manually overriding transaction isolation levels mid-session.

Alternative or Verification Steps

  • To verify the fix, execute the stored procedure manually in SSMS while monitoring SELECT @@TRANCOUNT; before and after execution—it should return to 0 after the outer transaction commits successfully.
  • If the error persists, use SQL Server Profiler or Extended Events to trace the exact nesting level where the COMMIT is being rejected, as this often reveals a secondary hidden procedure call causing the conflict.

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

Troubleshooting Guide: SQL Server Error 3988

Why This Error Happens

Error 3988 occurs when an application attempts to open a new transaction (via BEGIN TRANSACTION or an API call) while another thread or batch within the same session (SPID) still has an active operation running, such as an unfinished SELECT or an asynchronous command. This is common in applications using Multiple Active Result Sets (MARS) incorrectly, or when connection pooling reuses a session before the previous transaction thread has fully released control. It can also occur if a client-side timeout forces a new command onto a connection string that the server still considers “busy” with a prior thread.

Step-by-Step Resolution Guide

Step 1: Verify MARS Configuration in the Connection String

  • Check the application’s connection string (web.config, appsettings.json, or ODBC DSN) for the MultipleActiveResultSets parameter.
  • If using ADO.NET, ensure it is explicitly set: MultipleActiveResultSets=True;
  • If the driver does not support MARS correctly, disable it and rely on standard sequential processing instead.

Step 2: Isolate the Session Using Activity Monitor

  • Open SQL Server Management Studio (SSMS) and connect to the Windows Server 2025 instance.
  • Navigate to Activity Monitor > Processes and filter by the specific SPID reporting the error.
  • Run the following query to identify blocking threads within the same session:
SELECT session_id, status, command, blocking_session_id 
FROM sys.dm_exec_requests 
WHERE session_id = <Your_SPID>;

Step 3: Refactor Application Threading Logic

  • Audit the application code (C#, Java, or Python) for instances where a connection object is shared across multiple threads simultaneously.
  • Ensure that SqlConnection objects are not static or singleton instances shared by concurrent processes; implement a connection pool per-thread instead.
  • Add explicit SqlCommand.Cancel() calls before attempting to open a new transaction on a recycled connection object.

Step 4: Update SQL Server Native Client/Driver

  • Navigate to the Microsoft Download Center and ensure you are running the latest ODBC Driver 18 or newer, compatible with SQL Server 2025.
  • Uninstall legacy “SQL Server Native Client” drivers via Control Panel > Programs and Features on the Windows 11/Server 2025 machine, as these often mismanage thread handles.
  • Restart the SQL Server (MSSQLSERVER) service to ensure the new driver handshake takes effect:
Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Verification: Run a load test using SQLQueryStress or a custom script to simulate concurrent transactions; confirm Error 3988 no longer appears in the SQL Server Error Log (Management > SQL Server Logs).
  • Alternative: If the error persists under MARS, switch the application logic to explicit TransactionScope management in .NET, ensuring the scope is disposed of immediately after the thread completes its read/write operation.

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

Troubleshooting Guide: Error 3987 — SNAPSHOT ISOLATION is Always Enabled in This Database

Why This Error Happens

This error occurs because the database already has ALLOW_SNAPSHOT_ISOLATION set to ON, which is a persistent, database-level setting that does not reset between sessions or connections. When an attempt is made to re-run the ALTER DATABASE command to enable snapshot isolation on a database where it is already active, SQL Server raises Error 3987 instead of silently ignoring the redundant command. This is typically caused by a misunderstanding of the current database state, an automated deployment or migration script running without a pre-check, or a conflict between multiple scripts/tools attempting to configure isolation levels simultaneously.

Step-by-Step Resolution Guide

Step 1: Verify the Current Snapshot Isolation State

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check the current state of the database:
  SELECT name, snapshot_isolation_state, snapshot_isolation_state_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • A result of 1 or ON confirms that snapshot isolation is already active and no further action is needed to “enable” it.

Step 2: Review and Correct the Deployment Script

  • Locate the source of the command, typically found in a .sql deployment file, a DACPAC post-deployment script, or a DevOps pipeline (e.g., Azure DevOps YAML or Jenkinsfile).
  • Modify the script to include a conditional check before executing the ALTER DATABASE command to prevent the error from halting the pipeline:
  IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'YourDatabaseName' AND snapshot_isolation_state = 0)
  BEGIN
      ALTER DATABASE YourDatabaseName SET ALLOW_SNAPSHOT_ISOLATION ON;
  END
  • Save the script and ensure it is updated in the source control repository (e.g., Git) to prevent future occurrences.

Step 3: Check for Conflicting Automation Tools

  • Audit SQL Server Agent Jobs via SSMS under SQL Server Agent > Jobs to ensure no other scheduled job is attempting to toggle this setting.
  • Check for third-party monitoring tools or ORM frameworks (like Entity Framework migrations) that might be forcing this setting on every application startup.
  • Disable or update the redundant job/script to remove the duplicate ALTER DATABASE call.

Step 4: Restart the Target Service (If State Appears Stuck)

  • If the sys.databases view shows inconsistent data compared to the actual behavior, restart the SQL Server service to clear the cache.
  • Open Command Prompt as Administrator on Windows Server 2025 and run:
  net stop MSSQLSERVER
  net start MSSQLSERVER
  • Re-verify the state using the query from Step 1 immediately after the service restarts.

Alternative or Verification Steps

  • Verification: Run a test transaction using SET TRANSACTION ISOLATION LEVEL SNAPSHOT; followed by a SELECT statement to ensure the database accepts the isolation level without throwing errors.
  • Alternative: If the setting needs to be toggled (e.g., for maintenance), first disable it using ALTER DATABASE YourDatabaseName SET ALLOW_SNAPSHOT_ISOLATION OFF;, ensure no active snapshot transactions are running, and then re-enable it successfully without triggering Error 3987.

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

Why This Error Happens

Error 3986 occurs when the internal global transaction timestamp counter used by SQL Server’s In-Memory OLTP (Hekaton) engine reaches its maximum allowable value. This counter is a lightweight, monotonically increasing value used to order transactions across memory-optimized tables, and once exhausted, SQL Server cannot generate new timestamps for incoming transactions. This typically happens on servers with extremely high transaction volumes against memory-optimized objects that have been running for a very long time without a restart, or due to a bug in older builds that increments the counter more aggressively than expected.

Step-by-Step Resolution Guide

Step 1: Confirm the Scope of the Issue

  • Check the SQL Server Error Log (Management > SQL Server Logs in SSMS, or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for repeated instances of Error 3986.
  • Identify whether the affected database(s) use memory-optimized tables (In-Memory OLTP) by running:
SELECT name, is_memory_optimized_elevate_to_snapshot_on 
FROM sys.databases;
  • Note the exact time of failure to correlate with transaction volume spikes.

Step 2: Perform a Controlled Restart of the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11 and locate SQL Server (MSSQLSERVER) or the named instance.
  • Right-click and select Restart, or run from an elevated PowerShell prompt:
Restart-Service -Name 'MSSQLSERVER' -Force
  • This resets the in-memory transaction timestamp counter, which is the only way to recover from this specific error once it occurs.

Step 3: Apply the Latest Cumulative Update (CU) for SQL Server 2025

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update for SQL Server 2025.
  • Install the patch using the setup wizard or silently via:
Setup.exe /Action=Patch /IAcceptSQLServerLicenseTerms /Quiet /InstanceName=MSSQLSERVER
  • This CU includes fixes to the timestamp allocation logic that reduce the frequency of counter exhaustion under heavy In-Memory OLTP workloads.

Step 4: Schedule Proactive Maintenance Restarts

  • Configure a maintenance plan or Task Scheduler job to restart the SQL Server service during a low-traffic window (e.g., weekly) to preemptively reset the timestamp counter.
  • Use SQL Server Agent to create a job with a CmdExec step:
net stop MSSQLSERVER && net start MSSQLSERVER
  • Document this as a known mitigation until the underlying workload is optimized or reduced.

Alternative or Verification Steps

  • After restarting, verify the fix by monitoring the Error Log for 24–48 hours to confirm Error 3986 does not recur, and check sys.dm_db_xtp_transaction_stats for healthy timestamp generation.
  • If the error reoccurs frequently, consider reviewing application logic to reduce unnecessary transaction churn on memory-optimized tables, or open a support case with Microsoft to evaluate a hotfix specific to your build number.

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

Troubleshooting Guide: SQL Server Error 3985 – Transaction Context Change Failure

Why This Error Happens

Error 3985 typically occurs when SQL Server 2025 cannot allocate sufficient memory to switch transaction contexts, often during distributed transactions, linked server queries, or when using sp_getbindtoken and sp_bindsession. This is frequently triggered by memory pressure from the Buffer Pool being set too high relative to available system RAM, or by other processes on Windows Server 2025 competing for physical memory. In some cases, this error is a symptom of memory fragmentation within the SQL Server process rather than true system-wide memory exhaustion.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Configuration

  • Open SQL Server Management Studio (SSMS) and run: EXEC sp_configure 'max server memory'
  • Check if the value is set too close to the total physical RAM (leave at least 4-8 GB for the OS on Windows Server 2025).
  • Review current usage via: SELECT * FROM sys.dm_os_process_memory

Step 2: Adjust Max Server Memory Setting

  • Run the following to reconfigure, replacing <value> with an appropriate MB figure (e.g., leave 20% of RAM for the OS):
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'max server memory', <value>;
RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER for changes to take full effect.

Step 3: Check for Memory Leaks in Other Processes

  • Open Task Manager or Performance Monitor (perfmon.exe) on Windows Server 2025.
  • Monitor the counter Memory\Available MBytes; if it consistently drops below 500 MB, identify and close competing processes (e.g., antivirus scans, backup agents).
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for recurring Out-Of-Memory (OOM) warnings correlating with Error 3985.

Step 4: Review Linked Server and Distributed Transaction Settings

  • If the error occurs during cross-database or linked server queries, verify the MSDTC (Distributed Transaction Coordinator) service is running: services.msc → check “Distributed Transaction Coordinator”.
  • Ensure linked server memory-intensive queries are optimized or broken into smaller batches to reduce simultaneous context switches.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the update and reboot the server, as this error has known fixes related to memory handling in earlier builds.

Alternative or Verification Steps

  • To verify the fix, re-run the failing transaction/query and monitor sys.dm_os_memory_clerks to confirm memory allocation stabilizes without triggering Error 3985.
  • If the issue persists, consider adding physical RAM to the Windows Server 2025 host or migrating to a dedicated SQL Server instance with reduced concurrent workloads.

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

Troubleshooting Guide: Error 3984 – Cannot Acquire Database Lock During Transaction Change

Why This Error Happens

Error 3984 typically occurs when the database engine is unable to obtain the necessary lock on a resource (row, page, or table) because the transaction log is unable to mark a log sequence number (LSN) as part of an active checkpoint or recovery operation. This is most commonly caused by a corrupted or inconsistent transaction log file, insufficient memory allocated to the Lock Manager, or a long-running blocking transaction that has exhausted available lock resources. In some cases, this error surfaces after an improper shutdown or storage-level I/O interruption on Windows Server 2025 that leaves the database in a transitional state.

Step-by-Step Resolution Guide

Step 1: Verify Database and Transaction Log Integrity

  • Open SQL Server Management Studio (SSMS) and run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORS;
  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for related corruption warnings.
  • If corruption is found, restore from the latest clean backup before proceeding further.

Step 2: Identify and Terminate Blocking Transactions

  • Run the following query to identify blocking sessions: SELECT * FROM sys.dm_tran_locks WHERE request_status = 'WAIT';
  • Cross-reference blocking session IDs using EXEC sp_who2 'active';
  • If a session is confirmed as an orphaned or long-running blocker, terminate it using KILL <session_id>;

Step 3: Increase Lock Resources and Adjust Memory Configuration

  • Open SSMS, right-click the server instance, and go to Properties > Memory.
  • Ensure “Maximum server memory” is not set too restrictively (recommended: leave at least 20% of system RAM for the OS on Windows Server 2025).
  • If using locked pages, verify the SQL Server service account has the “Lock Pages in Memory” policy enabled via secpol.msc under Local Policies > User Rights Assignment.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER for changes to take effect.

Step 4: Rebuild or Repair the Transaction Log (If Required)

  • If the log file is flagged as suspect, set the database to emergency mode: ALTER DATABASE YourDatabaseName SET EMERGENCY;
  • Run ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE; followed by DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);
  • Revert to multi-user mode: ALTER DATABASE YourDatabaseName SET MULTI_USER;

Alternative or Verification Steps

  • Re-run the original transaction that triggered Error 3984 and monitor sys.dm_os_wait_stats for LCK_M_* wait types to confirm locks are being released properly.
  • If the issue persists, failover to a secondary replica (if using Always On Availability Groups) and perform a full consistency check on the primary node before reintroducing it to the cluster.

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

Troubleshooting Guide: SQL Server Error 3983 – “Session Is Not Single Threaded”

Why This Error Happens

Error 3983 occurs when a transaction attempts to run a parallel (multi-threaded) operation while simultaneously participating in a marked transaction or distributed transaction that requires MARS (Multiple Active Result Sets) or single-threaded execution context. This typically happens when a session enlisted in a distributed transaction (via BEGIN DISTRIBUTED TRANSACTION or MSDTC) tries to execute a query that the Query Optimizer decides to parallelize across multiple schedulers. SQL Server 2025 enforces strict thread affinity for transactional consistency, so it blocks the operation rather than risk corrupting the transaction state.

Step-by-Step Resolution Guide

Step 1: Force Single-Threaded Execution via Query Hint

  • Add the OPTION (MAXDOP 1) hint to the specific query causing the failure.
  • Example:
  UPDATE dbo.YourTable
  SET Column1 = 'Value'
  WHERE ID = 1
  OPTION (MAXDOP 1);
  • This forces the Query Optimizer to skip parallel plan generation for that specific statement, bypassing the conflict with the active transaction session.

Step 2: Adjust Server-Level MAXDOP Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to check current configuration:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max degree of parallelism';
  • If the value is 0 (unlimited) and distributed transactions are common in your workload, set it to a fixed low value to reduce parallel plan generation:
  EXEC sp_configure 'max degree of parallelism', 1;
  RECONFIGURE WITH OVERRIDE;
  • Note: This is a server-wide change and may impact performance on other non-transactional workloads—apply with caution on production servers.

Step 3: Review and Refactor Distributed Transaction Code

  • Open the stored procedure or application code that initiates the transaction.
  • Look for BEGIN DISTRIBUTED TRANSACTION or linked server calls combined with complex joins/aggregations.
  • Refactor the code to separate the distributed transaction logic from heavy parallel-eligible queries. Run bulk/parallel-friendly operations before or after the transaction scope rather than inside it.

Step 4: Verify MSDTC Service Configuration (Windows Server 2025 / Windows 11)

  • Open Component Services (dcomcnfg.exe) on the host machine.
  • Navigate to Component Services > Computers > My Computer > Distributed Transaction Coordinator > Local DTC.
  • Right-click Local DTC, select Properties, and ensure Network DTC Access is enabled if transactions span multiple servers.
  • Restart the Distributed Transaction Coordinator service via services.msc to apply changes.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original transaction/query that threw Error 3983. Check the SQL Server Error Log (Management > SQL Server Logs in SSMS) to confirm no recurrence of Event ID 3983.
  • Alternative Fix: If refactoring code is not feasible, wrap the specific parallel-triggering statement in its own local transaction scope outside the distributed transaction block, committing it independently before the distributed transaction begins.

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

Troubleshooting Guide: SQL Server Error 3982

Why This Error Happens

Error 3982 occurs when a session attempts to start a new local or distributed transaction while an existing transaction—managed either by the Microsoft Distributed Transaction Coordinator (MSDTC) or a bound session—is still active and has not been committed or rolled back. This typically happens due to improperly closed application connections, a misconfigured MSDTC service that fails to clean up orphaned transactions, or application code that attempts to nest incompatible transaction types (e.g., mixing BEGIN DISTRIBUTED TRANSACTION with an active local transaction). In Windows Server 2025 environments, this is often exacerbated by stricter security defaults requiring explicit DTC network access configuration.

Step-by-Step Resolution Guide

Step 1: Verify and Restart the MSDTC Service

  • Open Services.msc on the Windows Server 2025/Windows 11 machine.
  • Locate Distributed Transaction Coordinator, right-click, and select Restart.
  • Alternatively, use PowerShell: Restart-Service -Name MSDTC -Force
  • This clears any “stuck” transaction states that are blocking new sessions.

Step 2: Check Active Transactions in SQL Server

  • Open SQL Server Management Studio (SSMS) and run the following query to identify blocking sessions:
DBCC OPENTRAN;
SELECT * FROM sys.dm_tran_active_transactions;
  • Identify the transaction_id and associated session_id that is holding the lock.
  • Kill the offending session using KILL [session_id] if it is safe to do so.

Step 3: Reconfigure MSDTC Security Settings

  • Navigate to Component Services (dcomcnfg.exe) > Computers > My Computer > Distributed Transaction Coordinator > Local DTC.
  • Right-click Local DTC and select Properties, then go to the Security tab.
  • Ensure Network DTC Access, Allow Inbound/Outbound, and Enable XA Transactions (if applicable) are checked.
  • Click OK and restart the MSDTC service to apply the new security context.

Step 4: Audit Application Transaction Logic

  • Review the application code (e.g., .NET TransactionScope or JDBC connections) to ensure transactions are explicitly committed or rolled back in a finally block.
  • Ensure connection pooling settings are not reusing a connection that still has an enlisted transaction from a previous request.
  • Verify that SET XACT_ABORT ON is used in stored procedures to ensure transactions are rolled back immediately upon error.

Alternative or Verification Steps

  • Verification: After restarting the DTC service, run Get-Service MSDTC in PowerShell to confirm the status is “Running,” then attempt the failed transaction again to ensure Error 3982 no longer appears.
  • Alternative: If the error persists specifically in a clustered environment, verify that the MSDTC resource is online in Failover Cluster Manager and is not pointing to a corrupted CLB (Clustered Log Base) resource, which may require recreating the DTC resource group entirely.

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

Troubleshooting Guide: SQL Server Error 3981

“The transaction operation cannot be performed because there are pending requests working on this transaction.”

Why This Error Happens

This error occurs when SQL Server attempts to commit, rollback, or close a transaction while another session, worker thread, or asynchronous request still holds an active reference to it. This is commonly triggered by overlapping Multiple Active Result Sets (MARS) connections, orphaned batches, or a client-side timeout that disconnects before the server-side transaction fully completes. It can also surface when linked server calls or distributed transactions leave residual locks on the transaction context due to network interruption or driver-level connection pooling issues.

Step-by-Step Resolution Guide

Step 1: Identify Blocking Sessions and Pending Requests

  • Open SQL Server Management Studio (SSMS) and run the following query to check for active requests tied to the problematic transaction:
  SELECT session_id, status, command, wait_type, last_wait_type, transaction_id
  FROM sys.dm_exec_requests
  WHERE transaction_id = (SELECT transaction_id FROM sys.dm_tran_current_transaction);
  • Note any session_id values showing SUSPENDED or SLEEPING status, as these are likely holding the transaction open.

Step 2: Disable or Audit MARS on the Connection String

  • If your application uses Multiple Active Result Sets, inspect the connection string (typically in web.config, app.config, or ODBC DSN settings under C:\Windows\System32\odbcad32.exe).
  • Temporarily set MultipleActiveResultSets=False; to confirm if MARS concurrency is the root cause.
  • Restart the application pool or service in IIS Manager (inetmgr.exe) to apply the connection string change.

Step 3: Terminate Orphaned Sessions Safely

  • Use the session IDs gathered in Step 1 to safely kill orphaned connections:
  KILL <session_id>;
  • Avoid killing system session IDs (below 50), as these are reserved for internal SQL Server processes.

Step 4: Update SQL Server Native Client and Drivers

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 / Windows 11.
  • Verify that the SQL Server Native Client (or Microsoft ODBC Driver 18+) is updated to the latest build, as older drivers mishandle asynchronous transaction completion signals.
  • Reboot the application server after updating to clear cached driver handles.

Step 5: Review Distributed Transaction Coordinator (MSDTC) Settings

  • Open dcomcnfg.exe (Component Services) and navigate to Component Services > Computers > My Computer > Distributed Transaction Coordinator.
  • Ensure Network DTC Access is enabled under Security Configuration, specifically allowing Inbound/Outbound transactions if linked servers are involved.
  • Restart the MSDTC service via services.msc to clear stale transaction locks.

Alternative or Verification Steps

  • Re-run the original transaction/stored procedure in isolation using SET XACT_ABORT ON; at the beginning of the script to ensure immediate rollback on error rather than leaving pending requests.
  • If the error persists under heavy load, check sys.dm_os_waiting_tasks for wait_type = 'TRANSACTION_MUTEX', which confirms a concurrency deadlock requiring application-level logic changes to serialize transaction commits.

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

Troubleshooting Guide: SQL Server Error 3980

Why This Error Happens

Error 3980 (“The request failed to run because the batch is aborted”) typically occurs during backup or restore operations within a transaction when a prior statement in the same batch encounters a fatal error, forcing SQL Server to terminate the entire batch. This is commonly triggered by marked transactions (WITH MARK) failing due to insufficient log space, a corrupted backup chain, or conflicting session states. It can also surface when permissions are revoked mid-transaction or when the backup/restore target file is locked or unreachable, causing SQL Server to abort rather than risk data inconsistency.

Step-by-Step Resolution Guide

Step 1: Verify the Transaction Log and Disk Space

  • Check available disk space on the drive hosting your .ldf log file and backup destination.
  • Run DBCC SQLPERF(LOGSPACE); to confirm the transaction log isn’t full.
  • If space is low, expand the log file via SQL Server Management Studio (SSMS) > Database Properties > Files, or run:
  ALTER DATABASE [YourDB] MODIFY FILE (NAME = YourDB_log, SIZE = 5GB);

Step 2: Check for Blocking Sessions or Orphaned Transactions

  • Run DBCC OPENTRAN('YourDB'); to identify long-running or orphaned transactions.
  • Use sp_who2 or query sys.dm_exec_requests to locate blocking session IDs (SPIDs).
  • Kill any stuck sessions causing the abort with KILL <SPID>; if safe to do so.

Step 3: Validate Backup/Restore File Integrity and Permissions

  • Confirm the SQL Server service account has read/write access to the backup folder path (e.g., D:\SQLBackups\).
  • Right-click the folder > Properties > Security tab, and ensure NT SERVICE\MSSQLSERVER has Full Control.
  • Run RESTORE VERIFYONLY FROM DISK = 'D:\SQLBackups\YourDB.bak'; to check for corruption.

Step 4: Review SQL Server Error Logs for Root Cause

  • Open SSMS > Management > SQL Server Logs, or navigate to:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG
  • Search for the preceding error (e.g., Error 9002, 3041, or 5172) that triggered the 3980 abort.
  • Address the root error first, as 3980 is usually a secondary symptom.

Step 5: Rebuild the Transaction Using Isolated Batches

  • Break large multi-statement transactions into smaller, isolated batches separated by GO.
  • Re-run the operation using SET XACT_ABORT ON; at the start of the script to ensure cleaner rollback behavior on failure.

Alternative or Verification Steps

  • Verify the fix: Re-run the original backup/restore command and confirm it completes with “Processed X pages” success messages instead of aborting.
  • Alternative: If the issue persists on Windows Server 2025, run DBCC CHECKDB('YourDB') WITH NO_INFOMSGS; to rule out underlying database corruption as the root trigger.

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

Why This Error Happens

Error 3979 occurs when the SQL Server Transaction Manager (TM) — responsible for coordinating distributed transactions through MSDTC (Microsoft Distributed Transaction Coordinator) — fails to receive an acknowledgment from a participating resource manager within the expected internal timeout window. This is typically caused by network latency between nodes, a misconfigured or stalled MSDTC service, or blocking/locking contention that prevents the transaction log from flushing the commit record in time. In some cases, a corrupted MSDTC security configuration or outdated firewall rule silently drops the TM handshake packets, causing the request to be abandoned.

Step-by-Step Resolution Guide

Step 1: Verify and Restart the MSDTC Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate Distributed Transaction Coordinator, right-click, and select Restart.
  • Alternatively, run in an elevated PowerShell session:
  Restart-Service -Name MSDTC -Force
  • Confirm the service startup type is set to Automatic to prevent recurrence after reboot.

Step 2: Check Network and Firewall Configuration

  • Ensure TCP port 135 (RPC endpoint mapper) and the dynamic RPC port range are open between all nodes involved in the distributed transaction.
  • Run dtcping.exe between the SQL Server host and the remote TM to confirm two-way communication.
  • In Windows Defender Firewall with Advanced Security, verify inbound/outbound rules for “Distributed Transaction Coordinator” are enabled on both source and target servers.

Step 3: Review SQL Server Transaction Log and Blocking Sessions

  • Run the following query to identify long-running or blocked transactions tied to the TM request:
  SELECT session_id, blocking_session_id, wait_type, wait_time, status
  FROM sys.dm_exec_requests
  WHERE blocking_session_id <> 0;
  • If a session is holding locks for an extended period, terminate it safely using KILL <session_id>; after confirming it is not business-critical.
  • Check the transaction log file size and growth settings in SQL Server Management Studio (SSMS) under Database Properties > Files — ensure Autogrowth is not restrictively capped.

Step 4: Reconfigure MSDTC Security Settings

  • Open Component Services (dcomcnfg.exe) → Computers → My Computer → Distributed Transaction Coordinator → Local DTC → Properties → Security tab.
  • Enable Network DTC Access, Allow Inbound/Outbound, and Mutual Authentication Required (or Incoming Caller Authentication Required if operating in a mixed-trust environment).
  • Apply changes and restart the MSDTC service again to commit the new configuration.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Confirm your instance build number via:
  SELECT @@VERSION;
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as several TM timeout handling fixes are often bundled into servicing updates.
  • Reboot the server after installation to ensure the TM driver stack reloads cleanly.

Alternative or Verification Steps

  • Re-run the distributed transaction that originally failed and confirm Error 3979 no longer appears in the SQL Server Error Log or Windows Event Viewer (Application log).
  • If the issue persists, enable Trace Flag 3904 temporarily to capture verbose TM diagnostic logging, then review sys.dm_tran_active_transactions for transactions stuck in a PREPARED state before escalating to Microsoft Support.

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

Troubleshooting Guide: SQL Server Error 3978

Beginning a new transaction after rollback to save point is not allowed

Why This Error Happens

This error occurs when an application attempts to initiate a new transaction immediately after rolling back to a savepoint within the same batch, without properly committing or fully rolling back the parent transaction first. SQL Server 2025 enforces strict transaction state validation, and a rollback to a savepoint only reverts data changes — it does not close out the outer transaction context, leaving the connection in an ambiguous state. This is commonly triggered by poorly structured transaction logic in stored procedures, ORMs (like Entity Framework or Dapper), or application connection pooling where a prior transaction wasn’t fully disposed before a new one was opened on the same connection.

Step-by-Step Resolution Guide

Step 1: Review the Transaction Logic in the Source Code

  • Locate the stored procedure or application code throwing Error 3978 using SQL Server Profiler or Extended Events (xEvents) filtered on error_reported with error number 3978.
  • Check for a pattern like SAVE TRANSACTION, followed by ROLLBACK TRANSACTION SavepointName, and then immediately BEGIN TRANSACTION without an intervening COMMIT or full ROLLBACK.
  • Ensure every BEGIN TRANSACTION has a matching COMMIT TRANSACTION or a full ROLLBACK TRANSACTION (without a savepoint name) before starting a new one.

Step 2: Correct the Transaction Control Flow in T-SQL

  • Modify the procedure logic so that after ROLLBACK TRANSACTION SavepointName, you either continue work inside the same outer transaction or issue a full ROLLBACK TRANSACTION (no savepoint name) to close it out completely.
  • Example corrected pattern:
  BEGIN TRANSACTION;
  SAVE TRANSACTION MySavePoint;
  -- logic here
  ROLLBACK TRANSACTION MySavePoint;
  -- continue or commit the SAME transaction, do not start a new one here
  COMMIT TRANSACTION;
  • Avoid nesting a BEGIN TRANSACTION call directly after a savepoint rollback within the same @@TRANCOUNT scope.

Step 3: Audit Application-Level Connection and ORM Settings

  • On Windows Server 2025/Windows 11 hosts, check the application’s connection string for Enlist=true or pooling settings that may reuse a connection with a lingering transaction state.
  • For .NET apps, verify TransactionScope objects are disposed properly using using blocks and that nested scopes use TransactionScopeOption.Required correctly.
  • Restart the application pool (IIS) or the service host to clear any connections stuck in a bad transaction state:
  Restart-WebAppPool -Name "YourAppPoolName"

Step 4: Validate SQL Server Configuration and Patch Level

  • Confirm SQL Server 2025 is on the latest Cumulative Update via SQL Server Configuration Manager or SELECT @@VERSION;.
  • Check sys.dm_tran_active_transactions and sys.dm_tran_session_transactions DMVs to identify sessions stuck with uncommitted nested transactions.
  • If a session is orphaned, isolate and kill it using KILL <session_id>; after confirming it is safe to terminate.

Alternative or Verification Steps

  • Re-run the transaction/procedure in SQL Server Management Studio (SSMS) manually, checking @@TRANCOUNT before and after each COMMIT/ROLLBACK to confirm it returns to 0 cleanly.
  • If the error persists, wrap the entire logic in a TRY...CATCH block with XACT_STATE() checks to programmatically detect and fully roll back doomed transactions before allowing any new BEGIN TRANSACTION call.

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

Troubleshooting Guide: SQL Server Error 3977 — “The Savepoint Name Cannot Be NULL. The Batch Has Been Aborted.”

Why This Error Happens

This error occurs when a transaction attempts to roll back to a savepoint, but the savepoint name was never properly defined or was passed as a NULL value due to a scripting error or variable scope issue. It is commonly triggered by dynamically generated SQL, ORM frameworks (like Entity Framework or Hibernate), or stored procedures where a variable intended to hold the savepoint name was not initialized before the SAVE TRANSACTION or ROLLBACK TRANSACTION statement executed. In rare cases, this can also surface due to corrupted transaction log metadata in SQL Server 2025 following an improper shutdown.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Transact-SQL Code

  • Open SQL Server Management Studio (SSMS) and locate the stored procedure, trigger, or application code referenced in the error log.
  • Check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact batch that triggered Error 3977.
  • Search the code for SAVE TRANSACTION and ROLLBACK TRANSACTION statements that use a variable (e.g., @SavepointName) rather than a static string.

Step 2: Initialize and Validate the Savepoint Variable

  • Ensure the variable used for the savepoint name is explicitly declared and assigned a non-NULL value before the SAVE TRANSACTION call:
  DECLARE @SavepointName NVARCHAR(32) = 'MySavePoint';
  SAVE TRANSACTION @SavepointName;
  • If using an ORM (Entity Framework Core, NHibernate, etc.), verify that the application’s transaction-naming logic isn’t passing an empty string or null object reference during nested transaction calls.
  • Add a NULL check guard clause: IF @SavepointName IS NULL SET @SavepointName = 'DefaultSP';

Step 3: Update SQL Server 2025 Database Compatibility Level

  • Open a new query window in SSMS and run the following to confirm the compatibility level of the database:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is outdated (below 160), update it to align with SQL Server 2025 standards to ensure savepoint handling behaves as expected:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 4: Restart the SQL Server Service to Clear Session State

  • Open the Services console on Windows Server 2025 / Windows 11 by running services.msc.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to clear any lingering transaction contexts or cached execution plans.
  • Alternatively, run the following in PowerShell (as Administrator):
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the original batch or stored procedure in SSMS with SET NOCOUNT ON; and manually execute the SAVE TRANSACTION line in isolation to confirm the variable now holds a valid string value.
  • If the error persists despite code fixes, use SQL Server Profiler (or Extended Events) to trace the exact T-SQL batch sent by the application layer, as the NULL value may be originating from a parameterized query at the driver level (e.g., ODBC or JDBC connection string misconfiguration).

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

Troubleshooting Guide: Error 3976 – “The Transaction Name Has the Odd Length %d”

Why This Error Happens

This error occurs when SQL Server’s internal transaction logging mechanism receives a transaction name or savepoint name with an invalid byte length, typically caused by encoding mismatches between Unicode (NVARCHAR) and non-Unicode string handling in the transaction log stream. It frequently surfaces due to corrupted metadata in the transaction log cache, improperly terminated strings passed from client drivers (such as outdated ODBC or OLE DB providers), or low-level corruption in the syscommittab or internal log buffer structures. In rare cases, this is triggered by a mismatch between the SQL Server 2025 engine build and an incompatible client-side library attempting to mark a distributed transaction with a malformed name.

Step-by-Step Resolution Guide

Step 1: Verify and Update Client Connectivity Drivers

  • Check the application or script that initiates the transaction (e.g., BEGIN TRAN TransactionName WITH MARK) for improperly encoded strings.
  • Ensure the client is using the latest Microsoft ODBC Driver 18+ or OLE DB Driver 19+, as older drivers may pass ANSI strings where Unicode is expected.
  • On Windows Server 2025 / Windows 11, go to Control Panel > ODBC Data Sources (64-bit) and confirm the driver version listed matches the latest Microsoft release.

Step 2: Run Database Consistency Checks

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Execute DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption in system tables affecting transaction logging.
  • Review the output for any allocation or consistency errors tied to syscommittab or log sequence number (LSN) chains.

Step 3: Inspect and Sanitize Transaction Names in T-SQL Code

  • Search stored procedures, triggers, and application code for dynamically generated transaction names (e.g., concatenated strings with special characters or null terminators).
  • Replace any dynamically built transaction name strings with static, short, alphanumeric names (under 32 characters) to avoid encoding/length mismatches.
  • Example fix:
BEGIN TRAN MyCleanTransactionName;
-- instead of
BEGIN TRAN (@DynamicallyBuiltString);

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

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart.
  • This clears any transient in-memory log buffer corruption that may be causing the odd-length string error.

Step 5: Apply the Latest Cumulative Update (CU) for SQL Server 2025

  • Navigate to the Microsoft Download Center and verify your current build via:
SELECT @@VERSION;
  • Download and install the latest Cumulative Update for SQL Server 2025, as this issue has known fixes in post-RTM servicing releases related to transaction log string handling.

Alternative or Verification Steps

  • After applying fixes, re-run the original transaction or batch in SSMS and confirm no Error 3976 appears in the SQL Server Error Log (EXEC sp_readerrorlog;).
  • If the error persists, use SQL Server Profiler or Extended Events to trace the exact BEGIN TRAN statement and byte length being passed, then correct the offending application code at the source.

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

Troubleshooting Guide: Error 3975 – varchar(max) Not Supported for sp_getbindtoken

Why This Error Happens

This error occurs because sp_getbindtoken is used to create a bind token for distributed transactions across multiple connections, and this system procedure does not support large object (LOB) data types such as varchar(max), nvarchar(max), or varbinary(max). When a transaction context includes a session or query referencing these MAX data types while attempting to bind to another connection, SQL Server 2025 rejects the operation and aborts the batch. This is typically encountered in applications performing distributed or linked server transactions where large object variables are improperly passed between connections.

Step-by-Step Resolution Guide

Step 1: Identify the Query or Procedure Triggering the Bind

  • Review the application code or stored procedure that calls sp_getbindtoken or sp_bindsession.
  • Check SQL Server Profiler or Extended Events to capture the exact statement executing at the time of Error 3975.
  • Look specifically for variables or columns declared as varchar(max), nvarchar(max), or varbinary(max) within the transaction scope.

Step 2: Modify Data Types to Avoid MAX Types in Bound Transactions

  • Change varchar(max) columns/variables to a fixed-length equivalent (e.g., varchar(8000)) if the data size permits.
  • If large data truly exceeds 8000 characters, restructure the logic to process LOB data outside the bound transaction scope.
  • Update any affected table schemas using SQL Server Management Studio (SSMS) or via T-SQL:
  ALTER TABLE dbo.YourTable 
  ALTER COLUMN YourColumn VARCHAR(8000);

Step 3: Refactor Distributed Transaction Logic

  • Avoid passing MAX data types directly through sp_getbindtoken/sp_bindsession workflows.
  • Use a staging table or temporary table to hold LOB data separately, then join or merge results after the bound transaction completes.
  • Ensure MSDTC (Microsoft Distributed Transaction Coordinator) settings are correctly configured in Component Services (dcomcnfg.exe) under Windows Server 2025 if the issue is tied to distributed transactions.

Step 4: Apply Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Configuration Manager and verify the current build version.
  • Navigate to Microsoft’s official download center and install the latest Cumulative Update (CU) for SQL Server 2025.
  • Restart the SQL Server service via services.msc or run:
  Restart-Service -Name 'MSSQLSERVER'

Alternative or Verification Steps

  • Re-run the original transaction/query after applying the data type change — confirm Error 3975 no longer appears in the SQL Server error log (Error Logs folder under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\).
  • If the error persists, isolate the transaction without sp_getbindtoken entirely and use BEGIN DISTRIBUTED TRANSACTION directly, bypassing manual session binding as an alternative workaround.

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

Troubleshooting Guide: SQL Server Error 3974 – Exclusive Mode Database Limit Exceeded

Why This Error Happens

This error occurs when the number of databases opened in exclusive mode within a single workspace or session exceeds the internal threshold defined by SQL Server 2025’s resource governor. It is typically triggered by applications or scripts that open database handles without properly releasing locks, orphaned connections from crashed sessions, or a misconfigured workspace pooling setting that caps concurrent exclusive-mode database access. In some cases, corrupted tempdb metadata can also cause SQL Server to miscount active exclusive handles, falsely triggering the limit.

Step-by-Step Resolution Guide

Step 1: Identify Active Exclusive-Mode Sessions

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to list current sessions holding exclusive locks:
  SELECT request_session_id, resource_database_id, request_mode 
  FROM sys.dm_tran_locks 
  WHERE request_mode = 'X';
  • Note any session IDs (SPIDs) that appear stale or orphaned.

Step 2: Terminate Orphaned or Excessive Sessions

  • For each problematic SPID identified in Step 1, run:
  KILL <session_id>;
  • Alternatively, restart the SQL Server service via Services.msc on Windows Server 2025/Windows 11 to force-release all exclusive handles if KILL commands fail.

Step 3: Adjust Workspace Exclusive Mode Limit

  • Navigate to Computer Configuration > Administrative Templates > SQL Server > Workspace Settings in the Local Group Policy Editor (gpedit.msc), or edit the instance-level configuration directly.
  • Modify the max exclusive db handles setting using:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max worker threads', 0; -- allows auto-scaling
  RECONFIGURE;
  • Restart the SQL Server service for changes to take effect.

Step 4: Check and Repair tempdb Metadata

  • Run DBCC CHECKDB (tempdb) to rule out corruption affecting session counting.
  • If corruption is found, restart the instance to rebuild tempdb automatically, as tempdb is recreated on every SQL Server startup.

Alternative or Verification Steps

  • After applying fixes, re-run the application workload that originally triggered Error 3974 and monitor sys.dm_tran_locks to confirm exclusive-mode session counts stay below the configured threshold.
  • If the error persists, apply the latest Cumulative Update (CU) for SQL Server 2025, as workspace handle-counting bugs are occasionally addressed in servicing releases.

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

Troubleshooting Guide: Error 3972 — Incorrect TDS Protocol / Transaction Manager Event Length Mismatch

Why This Error Happens

Error 3972 occurs when the SQL Server Transaction Manager receives a Tabular Data Stream (TDS) packet whose declared event length does not match the actual byte length received, indicating protocol-level data corruption. This is typically caused by network-layer interference (such as a misconfigured firewall, proxy, or load balancer fragmenting packets), a mismatched or outdated network driver, or corrupted TDS packets resulting from an unstable connection between the client and the SQL Server instance. It can also surface after incomplete patching of SQL Server 2025 or when MS DTC (Distributed Transaction Coordinator) communication is interrupted mid-transaction.

Step-by-Step Resolution Guide

Step 1: Verify Network Integrity Between Client and Server

  • Run ping -t <ServerName> and tracert <ServerName> to check for packet loss or latency spikes during the error window.
  • Disable TCP Chimney Offload and TCP/IP Checksum Offload on the NIC, as these features are known to corrupt TDS packets on Windows Server 2025:
    Disable-NetAdapterChecksumOffload -Name "*" -TcpIPv4
  • Check Event Viewer under Applications and Services Logs > Microsoft > Windows > TCPIP for dropped packet warnings.

Step 2: Validate MS DTC Configuration

  • Open Component Services (comexp.msc) and navigate to Component Services > Computers > My Computer > Distributed Transaction Coordinator > Local DTC.
  • Right-click Local DTC, select Properties, and ensure Network DTC Access is enabled with both Allow Inbound and Allow Outbound checked.
  • Restart the MSDTC service:
    Restart-Service MSDTC -Force
  • Confirm the same DTC security settings are mirrored on both the application server and the SQL Server 2025 host.

Step 3: Update Network Drivers and SQL Native Client

  • Update the NIC driver via Device Manager (devmgmt.msc) or directly from the hardware vendor’s site (Intel/Broadcom/Mellanox drivers are common culprits).
  • Ensure the client application is using the latest Microsoft OLE DB Driver or ODBC Driver compatible with SQL Server 2025 (avoid legacy SQL Native Client 11.0 if still in use).
  • Apply the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as TDS parsing fixes are frequently shipped in CUs.

Step 4: Inspect and Reset the TCP/IP Stack

  • If the issue persists only on the Windows Server 2025 host, reset the TCP/IP stack to rule out stack-level corruption:
    netsh int ip reset
    netsh winsock reset
  • Reboot the server after running these commands, as a soft restart will not fully apply the reset.

Alternative or Verification Steps

  • To verify the fix, run a distributed transaction test query (e.g., BEGIN DISTRIBUTED TRANSACTION) from the client and confirm it commits without triggering Error 3972 in the SQL Server Error Log.
  • If the error persists after all steps, capture a network trace using Wireshark or Microsoft Network Monitor filtered on port 1433 to identify the exact packet where length mismatch occurs, then escalate to Microsoft Support with the trace file and PSSDIAG output.

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

Troubleshooting Guide: Error 3973 – Database In Use by Another Thread in Exclusive Mode

Why This Error Happens

This error occurs when an internal SQL Server operation, such as a database snapshot creation, DBCC CHECKDB, or a restore operation, attempts to acquire an exclusive lock on a database workspace that is already held by another concurrent thread or session. It is frequently triggered when maintenance tasks (like CHECKDB with data_purity or repair options) run simultaneously with other transactional activity against the same database. In some cases, this can also surface due to an improperly closed internal snapshot used by SQL Server to maintain transactional consistency during consistency checks.

Step-by-Step Resolution Guide

Step 1: Identify Conflicting Sessions and Processes

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance on your Windows Server 2025 / Windows 11 machine.
  • Run sp_who2 or query sys.dm_exec_requests and sys.dm_tran_locks to identify sessions holding locks on the database in question.
  • Look specifically for sessions with DbId matching your target database and a request_mode of X (exclusive).

Step 2: Terminate Blocking Sessions Safely

  • Once you identify the blocking session ID (SPID), verify it is not a critical system process before terminating it.
  • Use KILL <SPID> in a new query window to terminate the conflicting session.
  • If the issue stems from a DBCC CHECKDB operation, allow it to complete fully before re-running any other exclusive operations, as interrupting DBCC mid-process can cause further workspace conflicts.

Step 3: Check for Orphaned Internal Snapshots

  • Navigate to the default data directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\, and look for leftover snapshot files (usually named with a GUID pattern and .ss extension).
  • These orphaned snapshot files can occur if a previous DBCC operation was forcibly terminated.
  • Restart the SQL Server service via services.msc or run net stop MSSQLSERVER followed by net start MSSQLSERVER in an elevated Command Prompt to clear any stuck internal snapshot handles.

Step 4: Serialize Maintenance Operations

  • Reschedule maintenance jobs (DBCC CHECKDB, index rebuilds, backups) in SQL Server Agent so they do not overlap on the same database.
  • Open SQL Server Agent, navigate to Jobs, and adjust the Schedules tab to stagger execution times with at least a 15-30 minute buffer between jobs targeting the same database.

Step 5: Apply Latest Cumulative Update

  • Verify your current build version by running SELECT @@VERSION;.
  • If you are not on the latest Cumulative Update (CU) for SQL Server 2025, download and apply it from the Microsoft Update Catalog, as workspace locking issues are often addressed in service packs/CUs.

Alternative or Verification Steps

  • After applying the fixes, re-run the original operation (e.g., DBCC CHECKDB or backup/restore) during a low-activity window and confirm it completes without Error 3973 appearing in the SQL Server Error Log (ERRORLOG file in the MSSQL\LOG directory).
  • If the error persists, consider restarting the SQL Server instance entirely during a maintenance window to clear any lingering internal workspace locks that a simple service restart did not resolve.

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

Troubleshooting Guide: SQL Server Error 4336

Why This Error Happens

Error 4336 occurs during a piecemeal or file/filegroup restore operation when the restore sequence attempts to bring a filegroup online that has been previously dropped from the database. SQL Server retains metadata references to dropped filegroups in the backup history and transaction log chain, but since the physical filegroup no longer exists in the current database schema, it cannot be reconciled with an online restore. This typically happens when restoring a sequence of backups taken both before and after a DROP FILEGROUP operation was executed, or when attempting a partial restore against a database where the filegroup structure has changed since the backup was created.

Step-by-Step Resolution Guide

Step 1: Identify the Dropped Filegroup and Backup Timeline

  • Query msdb.dbo.backupfilegroup to determine when the filegroup was active and in which backup sets it appears.
  • Run the following to cross-reference backup history:
  SELECT bs.backup_start_date, bfg.filegroup_name 
  FROM msdb.dbo.backupset bs
  JOIN msdb.dbo.backupfilegroup bfg ON bs.backup_set_id = bfg.backup_set_id
  WHERE bs.database_name = 'YourDatabaseName';
  • Confirm whether the DROP FILEGROUP statement was executed before or after your target restore point.

Step 2: Restore the Full Database Offline Instead of Piecemeal

  • Avoid using WITH PARTIAL or RESTORE DATABASE ... FILEGROUP syntax if the filegroup was dropped at any point in the chain.
  • Perform a complete, non-piecemeal restore using:
  RESTORE DATABASE YourDatabaseName 
  FROM DISK = 'C:\SQLBackups\YourDatabase_Full.bak' 
  WITH NORECOVERY;
  • Continue restoring subsequent differential and transaction log backups in strict chronological order, ensuring you do not skip the backup taken immediately after the filegroup was dropped.

Step 3: Exclude the Dropped Filegroup from the Restore Plan

  • If performing a piecemeal restore, explicitly exclude the dropped filegroup using the READ_WRITE_FILEGROUPS clause rather than naming the obsolete filegroup directly.
  • Use SQL Server Management Studio (SSMS) 21 on Windows 11/Server 2025 to review the Files page under Database Properties to confirm the current active filegroup list before scripting the restore.
  • Re-run the restore sequence targeting only filegroups that exist in the final database state.

Step 4: Validate Backup Media Integrity

  • Run RESTORE VERIFYONLY FROM DISK = 'C:\SQLBackups\YourDatabase_Full.bak' to rule out corruption as a contributing factor.
  • Check the SQL Server error log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for corroborating I/O or backup chain warnings.

Alternative or Verification Steps

  • After restore completion, run RESTORE HEADERONLY and sp_helpfile against the recovered database to confirm all active filegroups are online and the dropped filegroup no longer appears in the file list.
  • If the error persists, consider restoring to a new database name first, then use DBCC CHECKDB and data export/import (via bcp or SSIS) to migrate only the required data, bypassing the problematic filegroup entirely.

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

Troubleshooting Guide: SQL Server Error 4337

Why This Error Happens

Error 4337 occurs when attempting to restore a data or log file that has been marked as “dropped” in the database’s metadata, meaning SQL Server no longer tracks it as a valid, restorable file within the current database structure. This typically happens when a file was removed from the database (via ALTER DATABASE ... REMOVE FILE) prior to the backup being taken, or the backup set is attempting to restore an out-of-sequence transaction log that references a file no longer part of the active filegroup topology. Attempting an online restore against this stale file reference causes SQL Server to reject the operation to maintain database consistency.

Step-by-Step Resolution Guide

Step 1: Verify the Backup and File History

  • Open SSMS and run RESTORE HEADERONLY FROM DISK = 'path_to_backup.bak' to inspect the backup set contents.
  • Cross-reference with RESTORE FILELISTONLY FROM DISK = 'path_to_backup.bak' to identify which files are flagged in the backup metadata.
  • Check sys.master_files and sys.database_files on the target instance to confirm if the file in question still exists in the current database schema.

Step 2: Exclude the Dropped File from the Restore Sequence

  • Use the WITH MOVE clause to explicitly map only the active, valid files during restore—do not attempt to map the dropped file.
  • Run a restore command similar to:
  RESTORE DATABASE [YourDB] FROM DISK = 'path_to_backup.bak' 
  WITH MOVE 'LogicalDataFile' TO 'C:\SQLData\YourDB.mdf', 
  NORECOVERY;
  • If performing a log restore, ensure the LSN (Log Sequence Number) chain does not include the point where the file was dropped; skip that specific log backup if necessary using CONTINUE_AFTER_ERROR cautiously, or restore up to the point just before the drop using STOPAT.

Step 3: Repair the Filegroup Metadata (If Restore Fails)

  • If the error persists because the online database still references the old file path, take the specific filegroup offline first: ALTER DATABASE [YourDB] MODIFY FILEGROUP [FG_Name] OFFLINE.
  • Re-attempt the restore targeting only the primary filegroup and valid secondary filegroups, excluding the corrupted/dropped reference.
  • Verify Windows Server 2025 folder permissions at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ to ensure the SQL Server service account has Full Control, which can sometimes mask as a 4337 error if the service cannot validate the dropped file’s ghost record due to access denial.

Alternative or Verification Steps

  • Verification: After the restore completes, run DBCC CHECKDB('YourDB') WITH NO_INFOMSGS to ensure no corruption exists and that the filegroup structure is consistent with the metadata.
  • Alternative: If the file cannot be excluded easily via GUI, use a Tail-Log Backup strategy: back up the tail of the log with NO_TRUNCATE, then perform the restore sequence again, explicitly stopping right before the transaction that dropped the file (STOPBEFOREMARK).

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

Troubleshooting Guide: Error 4335 – “The Specified STOPAT Time Is Too Early”

Why This Error Happens

This error occurs when performing a point-in-time restore (RESTORE DATABASE … WITH STOPAT) and the specified timestamp predates the earliest available transaction in the backup chain being applied. SQL Server 2025 tracks the LSN (Log Sequence Number) chain during restore operations, and if the STOPAT value falls before the first transaction recorded in the current differential or transaction log backup file, the engine cannot roll the database forward to that point. This typically happens due to incorrect time zone assumptions, a misunderstanding of backup sequence order, or attempting to apply a log backup that starts later than the requested recovery point.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Timestamp of Your Backup Chain

  • Run the following query against the msdb database to inspect backup history:
  SELECT backup_start_date, backup_finish_date, database_name, type 
  FROM msdb.dbo.backupset 
  WHERE database_name = 'YourDatabaseName' 
  ORDER BY backup_start_date;
  • Confirm whether your target STOPAT time falls within the range of backup_start_date and backup_finish_date for the relevant differential or log backup.
  • Check for time zone mismatches between your restore script and the SQL Server instance (SQL Server uses server local time, not UTC, by default).

Step 2: Identify the Correct Full or Differential Base Backup

  • Ensure you are restoring from the full backup (or differential) that was taken before your desired STOPAT time, not after it.
  • Use RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDB.bak' to inspect the backup set metadata and confirm BackupStartDate and BackupFinishDate values.
  • If using Windows Server 2025 storage paths, confirm the backup file sequence in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\ matches the chronological order expected by your restore script.

Step 3: Adjust the STOPAT Value to a Valid Window

  • Modify your restore command to use a timestamp that falls strictly within the available log backup range:
  RESTORE DATABASE YourDatabaseName
  FROM DISK = 'C:\Backups\YourDB_Full.bak'
  WITH NORECOVERY;

  RESTORE LOG YourDatabaseName
  FROM DISK = 'C:\Backups\YourDB_Log1.trn'
  WITH STOPAT = '2025-01-15T14:30:00', RECOVERY;
  • If the exact time is unknown, use STOPATMARK or STOPBEFOREMARK with a named transaction mark instead of a hardcoded timestamp for greater precision.

Step 4: Rebuild the Restore Sequence If Chain Is Broken

  • If no valid backup file contains the desired STOPAT window, you must restore an earlier full backup and reapply subsequent differential/log backups in the correct order with WITH NORECOVERY until reaching the correct log file.
  • Delete and restart the restore sequence entirely if intermediate NORECOVERY states were committed incorrectly, as partial recovery chains cannot be reversed.

Alternative or Verification Steps

  • After a successful restore, run SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Status') to confirm the database is now ONLINE and query recent table data to verify the recovery point is accurate.
  • If STOPAT continues to fail, consider using RESTORE LOG ... WITH STANDBY mode to incrementally apply logs and manually inspect data state between each log restore until the correct point is isolated.

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

Why This Error Happens

Error 4334 occurs when a RESTORE LOG or RESTORE DATABASE command uses the STOPATMARK or STOPBEFOREMARK clause with a mark name that cannot be located in the msdb.dbo.logmarkhistory table or within the transaction log being restored. This typically happens because the named transaction was never committed with WITH MARK, the marked transaction occurred on a different database than the one being restored, or the backup chain being restored does not actually contain the LSN range where that mark was recorded. Database corruption in the msdb system database or a mismatch between the source and target server’s log mark history can also trigger this error.

Step-by-Step Resolution Guide

Step 1: Verify the Mark Name Exists and Is Correct

  • Run SELECT * FROM msdb.dbo.logmarkhistory WHERE name = 'YourMarkName' on the source instance to confirm the mark was actually recorded.
  • Check for typos, case sensitivity, or extra whitespace in the mark name used in your RESTORE statement.
  • Confirm the transaction was committed using BEGIN TRANSACTION YourMarkName WITH MARK 'description' followed by a COMMIT.

Step 2: Confirm the Mark Belongs to the Correct Database and Log Chain

  • Check the database_name column in msdb.dbo.logmarkhistory to ensure the mark was logged against the same database you are restoring.
  • Verify that the backup files being restored (full, differential, and log backups) span the LSN range containing the mark, using RESTORE HEADERONLY and RESTORE LOG ... WITH NORECOVERY in sequence.
  • Ensure no log backups are missing from the restore sequence — a gap in the log chain will cause the LSN to never appear.

Step 3: Restore Using LSN or Time-Based Alternative Instead of Mark Name

  • If the mark cannot be validated, switch to STOPAT = 'yyyy-mm-dd hh:mm:ss' to restore to a known point in time instead.
  • Alternatively, use STOPBEFOREMARK = 'YourMarkName' AFTER 'datetime' to help SQL Server disambiguate marks with duplicate names across multiple transactions.
  • Example command: RESTORE LOG YourDB FROM DISK = 'E:\Backups\YourDB_log.trn' WITH STOPAT = '2025-01-15T14:30:00', RECOVERY.

Step 4: Rebuild or Repair the msdb Marked Transaction Table (If Corrupted)

  • Run DBCC CHECKDB('msdb') to rule out corruption in the system database on both source and target instances.
  • If corruption is found, restore msdb from a known-good backup or run DBCC CHECKDB('msdb', REPAIR_ALLOW_DATA_LOSS') in single-user mode as a last resort.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after repairs on Windows Server 2025/Windows 11.

Alternative or Verification Steps

  • After restoring, run RESTORE HEADERONLY FROM DISK = 'YourBackupFile' and confirm the LastLSN and FirstLSN values bracket the LSN logged in logmarkhistory for your mark name.
  • If the marked transaction restore still fails, bypass marks entirely and restore to the latest available point using WITH RECOVERY without any STOPAT/STOPATMARK clause, then manually verify data integrity with DBCC CHECKDB on the restored database.

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

Troubleshooting Guide: SQL Server Error 4333 — “Database Cannot Be Recovered Because the Log Was Not Restored”

Why This Error Happens

Error 4333 occurs when SQL Server attempts to bring a database online but detects that the required transaction log restore sequence was never completed, leaving the database in a state where it cannot reconcile data file LSNs (Log Sequence Numbers) with the log file. This is most commonly caused by an interrupted restore chain (e.g., restoring a full backup without applying subsequent differential or log backups before issuing RESTORE DATABASE ... WITH RECOVERY), a missing or corrupted .ldf file, or a mismatched backup sequence where files were restored out of order. It can also occur if the log file was manually deleted or moved while the database was in a RESTORING state.

Step-by-Step Resolution Guide

Step 1: Verify the Current Restore State of the Database

  • Run the following query to check if the database is still in NORECOVERY or RESTORING mode:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If state_desc shows RESTORING, the database is mid-sequence and still expects additional log files.
  • Check the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact point of failure in the restore chain.

Step 2: Reapply the Correct Backup Restore Sequence

  • Identify the last successful full backup and all subsequent differential/log backups using:
  RESTORE HEADERONLY FROM DISK = 'D:\Backups\YourDatabase_Full.bak';
  • Restore the full backup with NORECOVERY:
  RESTORE DATABASE YourDatabaseName 
  FROM DISK = 'D:\Backups\YourDatabase_Full.bak' 
  WITH NORECOVERY;
  • Apply all transaction log backups in chronological order (do not skip any .trn files), ending with the final log file using WITH RECOVERY:
  RESTORE LOG YourDatabaseName 
  FROM DISK = 'D:\Backups\YourDatabase_Log1.trn' 
  WITH NORECOVERY;

  RESTORE LOG YourDatabaseName 
  FROM DISK = 'D:\Backups\YourDatabase_Log_Final.trn' 
  WITH RECOVERY;

Step 3: Check File Permissions and Path Integrity on Windows Server 2025

  • Navigate to the SQL Server data directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) and confirm the .ldf file exists and is not flagged as Read-Only.
  • Ensure the SQL Server service account (visible in SQL Server Configuration Manager) has Full Control NTFS permissions on both the DATA and backup folders.
  • If the log file is missing or corrupted, and you have no valid log backup, you may need to force the database into emergency mode as a last resort:
  ALTER DATABASE YourDatabaseName SET EMERGENCY;
  DBCC CHECKDB(YourDatabaseName, REPAIR_ALLOW_DATA_LOSS);

Step 4: Rebuild the Transaction Log (If No Backups Are Recoverable)

  • If Step 2 and Step 3 fail due to permanently lost log backups, detach the database and attempt a log rebuild:
  ALTER DATABASE YourDatabaseName REBUILD LOG ON 
  (NAME=YourDatabaseName_log, FILENAME='D:\Data\YourDatabaseName_log.ldf');
  • Immediately run DBCC CHECKDB afterward, as this action breaks the transaction log chain and may result in data loss.

Alternative or Verification Steps

  • After recovery, confirm the database is online and accessible by running SELECT state_desc FROM sys.databases WHERE name = 'YourDatabaseName'; — it should return ONLINE.
  • If the issue persists, use SQL Server Management Studio (SSMS) to right-click the database, select Tasks > Restore > Database, and use the GUI timeline feature to visually verify no backup files are missing from the restore plan before retrying.

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

Troubleshooting Guide: RESTORE LOG Error 4332 in SQL Server 2025

Why This Error Happens

Error 4332 occurs when SQL Server detects a break in the Log Sequence Number (LSN) chain, meaning the transaction log backup being restored does not logically follow the last restored backup. This typically happens when a log backup is skipped, restored out of order, or when the database recovery path has been interrupted by an intervening full backup taken outside the restore sequence. It can also occur if the backup file itself is corrupted or was truncated during transfer to the Windows Server 2025 host.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Sequence and LSN Chain

  • Open SQL Server Management Studio (SSMS) and run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourFile.trn' to inspect FirstLSN and LastLSN values.
  • Compare these values against the RedoStartLSN of your last successfully restored backup using RESTORE HEADERONLY on the prior file in the chain.
  • Confirm there are no missing .trn files between the full backup and the log backup you are attempting to restore.

Step 2: Restart the Restore Sequence from a Valid Full Backup

  • Drop the partially restored database or use RESTORE DATABASE [YourDB] WITH RECOVERY only if you intend to stop the sequence here permanently.
  • If continuing, start over with RESTORE DATABASE [YourDB] FROM DISK = 'C:\Backups\Full.bak' WITH NORECOVERY, REPLACE.
  • Apply each subsequent differential and log backup in strict chronological order using WITH NORECOVERY until the final file.

Step 3: Check File Integrity and Transfer Method

  • Validate the backup file was not corrupted during copy by running RESTORE VERIFYONLY FROM DISK = 'C:\Backups\YourFile.trn'.
  • If files were moved between Windows Server 2025 and another host, re-copy using robocopy with the /J flag to avoid buffering corruption: robocopy D:\Source D:\Dest YourFile.trn /J.
  • Confirm NTFS permissions on the backup folder grant the SQL Server service account (e.g., NT Service\MSSQLSERVER) at least Read access.

Step 4: Rebuild the Maintenance Plan or Script Order

  • If using a SQL Agent Job or Maintenance Plan, inspect the step history in SSMS under SQL Server Agent > Jobs > View History to confirm log backups ran on schedule without gaps.
  • Correct any job scheduling overlap where a new full backup job may have fired before all log backups were applied downstream.
  • Re-sequence the restore script manually if automated tools (like Ola Hallengren’s scripts) skipped a file due to a locked path.

Alternative or Verification Steps

  • After completing the restore chain, run RESTORE DATABASE [YourDB] WITH RECOVERY and confirm the database state changes to ONLINE via SELECT state_desc FROM sys.databases WHERE name = 'YourDB'.
  • If the LSN chain is unrecoverable due to a missing log file, your only alternative is to restore from the last known good full or differential backup and accept data loss up to that point, then immediately start a new backup chain going forward.

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

Troubleshooting Guide: SQL Server Error 4331 – Inconsistent Restore Points

Why This Error Happens

Error 4331 occurs when a database restore sequence (full, differential, and transaction log backups) is applied out of order or with mismatched LSNs (Log Sequence Numbers), leaving the data and log files in two different points in time. This commonly happens when a differential backup is restored against the wrong full backup baseline, or when log backups are applied without the NORECOVERY option during intermediate steps. File-level corruption or manually copied .mdf/.ldf files from different backup sets can also trigger this inconsistency.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain Integrity

  • Run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDB.bak' to inspect the LSN values (FirstLSN, LastLSN, CheckpointLSN) of each backup file.
  • Confirm that the Full backup’s DatabaseBackupLSN matches the baseline expected by your Differential and Log backups.
  • Discard any backup files where the BackupStartDate does not align sequentially.

Step 2: Restart the Restore Sequence from a Clean Baseline

  • Drop the partially restored database if it exists: DROP DATABASE YourDB;
  • Restore the Full backup first with NORECOVERY:
  RESTORE DATABASE YourDB 
  FROM DISK = 'C:\Backups\YourDB_Full.bak' 
  WITH NORECOVERY, MOVE 'YourDB' TO 'D:\SQLData\YourDB.mdf', 
  MOVE 'YourDB_log' TO 'D:\SQLLogs\YourDB_log.ldf';
  • Apply the Differential backup (if used) with NORECOVERY, then apply Transaction Log backups in exact chronological order.

Step 3: Finalize Recovery and Validate File Consistency

  • Once the last log backup is applied, run the final restore command with WITH RECOVERY to bring the database online.
  • Check sys.master_files to ensure the state_desc for both data and log files shows ONLINE.
  • If Windows Server 2025 File History or VSS snapshots were used instead of native SQL backups, ensure the snapshot captured both .mdf and .ldf files in the exact same transaction, as asynchronous disk snapshots are a frequent cause of this error.

Step 4: Check for Underlying Storage/Permission Issues

  • Verify the SQL Server service account (NT Service\MSSQLSERVER) has full control permissions on the D:\SQLData and D:\SQLLogs directories.
  • Use Get-Acl in PowerShell to audit folder permissions if the restore fails due to access denial during the file-move phase.

Alternative or Verification Steps

  • Verification: Run DBCC CHECKDB('YourDB') WITH NO_INFOMSGS, ALL_ERRORMSGS; after recovery to confirm there is no lingering physical corruption from the inconsistent restore.
  • Alternative: If the backup chain is unrecoverable, restore the Full backup alone using WITH RECOVERY (accepting data loss up to that point) rather than attempting to force a broken differential/log chain.

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

Troubleshooting Guide: SQL Server Error 4330 – Inconsistent Recovery Path

Why This Error Happens

Error 4330 occurs when SQL Server attempts to restore a transaction log or differential backup that does not logically follow the last restored backup in the sequence. This typically happens because the LSN (Log Sequence Number) chain has been broken, often due to an intervening backup taken outside the restore sequence, a missing differential/log backup, or restoring files out of chronological order. SQL Server strictly enforces this chain to guarantee transactional consistency, so any gap or mismatch in the backup lineage will immediately halt the restore process.

Step-by-Step Resolution Guide

Step 1: Verify the Full Backup Chain

  • Query the msdb database on the source server to list all backups taken for the database:
  SELECT backup_set_id, database_name, backup_start_date, type, first_lsn, last_lsn, checkpoint_lsn
  FROM msdb.dbo.backupset
  WHERE database_name = 'YourDatabaseName'
  ORDER BY backup_start_date;
  • Confirm that the first_lsn of the log/differential backup you are applying matches the last_lsn (or checkpoint_lsn) of the previously restored backup.
  • Identify any gaps where a backup may be missing from the sequence.

Step 2: Restore Using the Correct Sequence and NORECOVERY

  • Always restore the Full backup first with NORECOVERY:
  RESTORE DATABASE YourDatabaseName
  FROM DISK = 'C:\Backups\Full.bak'
  WITH NORECOVERY;
  • Apply the most recent Differential backup (if available) next, also with NORECOVERY:
  RESTORE DATABASE YourDatabaseName
  FROM DISK = 'C:\Backups\Diff.bak'
  WITH NORECOVERY;
  • Apply Transaction Log backups strictly in chronological order (do not skip files), using NORECOVERY until the final file.

Step 3: Check for Broken Log Chains or Unlogged Operations

  • Look for any instance where the Recovery Model was switched from FULL to SIMPLE and back, as this breaks the log chain permanently.
  • Check the Windows Server 2025 Event Viewer under Applications and Services Logs > MSSQLSERVER for any “BULK_LOGGED” operations that might conflict with point-in-time recovery.
  • If a log backup is missing or corrupted, you cannot skip it; you must locate the specific .trn file or start the restore sequence over from a Full backup taken after the gap.

Step 4: Re-initialize the Restore Sequence

  • If the backup file order cannot be reconciled, discard the current partial restore.
  • Drop the database (if it is in a “Restoring” state and causing locks) and start the restore process from the earliest available Full backup to rebuild a clean, unbroken LSN chain.

Alternative or Verification Steps

  • Verification: After the final log restore, run RESTORE DATABASE YourDatabaseName WITH RECOVERY;. If the database transitions to “Online” status in SQL Server Management Studio (SSMS) without errors, the LSN chain was successfully validated.
  • Alternative: If the chain is permanently broken (e.g., a backup file was deleted), use RESTORE HEADERONLY FROM DISK = 'PathToFile.bak' to inspect individual file metadata and manually map the correct sequence using the first_lsn and last_lsn columns before retrying the restore.

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

Why This Error Happens

Error 4329 occurs when SQL Server 2025 detects that the transaction log file you are attempting to restore contains log sequence number (LSN) records that predate the LSN mark already applied from a previous restore operation. This typically happens when log backups are applied out of sequence, when a log backup chain has a gap due to a missing intermediate file, or when the wrong backup file is selected during a point-in-time recovery. The database engine intentionally leaves the database in the RESTORING state to prevent data corruption until the correct, sequential log file is supplied.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain Sequence

  • Query the msdb database to confirm the correct order of log backups using: SELECT backup_start_date, first_lsn, last_lsn, database_backup_lsn FROM msdb.dbo.backupset WHERE database_name = 'YourDB' ORDER BY backup_start_date;
  • Cross-reference the first_lsn and last_lsn values to identify any gaps or overlaps in the chain.
  • Confirm you are not attempting to reapply a log file that was already restored in a prior RESTORE LOG command.

Step 2: Identify the Correct Starting Point

  • Run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDB_log.trn' to inspect the FirstLSN and LastLSN values embedded in the file header.
  • Compare this against the LSN currently applied to the database (visible via sys.database_recovery_status or the last successful restore output).
  • Discard any log backup file whose LastLSN is lower than the database’s current recovery LSN, as this is the root cause of the 4329 error.

Step 3: Restart the Restore Sequence from a Valid Full Backup

  • If the chain is broken beyond repair, restore a fresh Full Backup with WITH NORECOVERY to reset the baseline LSN.
  • Reapply subsequent Differential and Log backups in strict chronological order, ensuring each uses WITH NORECOVERY except the final file.
  • Store backup files in a clearly timestamped folder structure (e.g., C:\SQLBackups\YourDB\Logs\) to prevent future sequencing confusion on Windows Server 2025.

Step 4: Finalize the Recovery

  • Once the correct, sequential log file is identified and applied successfully, execute RESTORE DATABASE YourDB WITH RECOVERY to bring the database online.
  • Confirm there are no pending transactions required by checking the output message for “RESTORE DATABASE successfully processed.”

Alternative or Verification Steps

  • Verify the fix by running SELECT state_desc FROM sys.databases WHERE name = 'YourDB';—the status should return ONLINE rather than RESTORING.
  • If the correct log file is missing or corrupted, use SQL Server Management Studio’s (SSMS) Restore Database > Timeline visual tool to automatically detect and select the valid backup chain, bypassing manual LSN tracking entirely.

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

Troubleshooting Guide: Error 4327 — Point-in-Time Recovery Inhibited by Bulk-Logged Changes

Why This Error Happens

This error occurs because the transaction log backup contains one or more bulk-logged operations (such as BULK INSERT, SELECT INTO, or index rebuilds) that were performed while the database recovery model was set to Bulk-Logged. Under the Bulk-Logged recovery model, SQL Server minimally logs these operations, meaning only the extent allocations are recorded rather than the full row-by-row changes. Because the actual data changes are not fully captured in the log, SQL Server cannot guarantee a consistent state at an arbitrary point in time, so it refuses the STOPAT request and instead rolls the database forward to the end of the available log.

Step-by-Step Resolution Guide

Step 1: Verify the Recovery Model History

  • Check the current recovery model using:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Review your maintenance scripts or SSIS/Agent jobs to identify when the model was switched to BULK_LOGGED.
  • Confirm the timeframe of the bulk operation by cross-referencing job history in SQL Server Agent or the Windows Event Viewer (Applications and Services Logs > Microsoft > SQL Server).

Step 2: Switch to the Full Recovery Model Immediately

  • Change the recovery model back to FULL as soon as the bulk operation window closes:
  ALTER DATABASE YourDatabaseName SET RECOVERY FULL;
  • Immediately take a differential or full backup to re-establish a clean log chain:
  BACKUP DATABASE YourDatabaseName TO DISK = 'E:\SQLBackups\YourDatabaseName_Full.bak';
  • This prevents future bulk-logged backups from blocking point-in-time recovery within the same log chain.

Step 3: Restore Using an Available Recovery Point

  • Since STOPAT cannot be used within a bulk-logged backup, restore to the nearest valid full or log backup that falls before the bulk-logged transaction log file.
  • Use the following syntax to identify valid boundaries:
  RESTORE HEADERONLY FROM DISK = 'E:\SQLBackups\YourDatabaseName_Log.trn';
  • Apply the restore sequence, stopping before the log file containing minimal logging:
  RESTORE LOG YourDatabaseName 
  FROM DISK = 'E:\SQLBackups\YourDatabaseName_Log_Previous.trn' 
  WITH NORECOVERY;

Step 4: Adjust SQL Server Agent Jobs to Prevent Recurrence

  • Modify any scheduled jobs on Windows Server 2025 that toggle the recovery model for bulk loads.
  • Add a step to automatically revert to FULL recovery immediately after the bulk task completes, using SQL Server Agent > Job Steps > Advanced > On Success Action.
  • Ensure a dedicated log backup job runs immediately after this job step to seal the bulk-logged transaction.

Alternative or Verification Steps

  • Verify the fix: After restoring, run RESTORE DATABASE YourDatabaseName WITH RECOVERY; and check sys.databases to confirm the database is ONLINE and the recovery model is FULL.
  • Alternative: If point-in-time recovery to the exact second is mandatory, avoid BULK_LOGGED entirely for mission-critical databases and use FULL recovery with batched BULK INSERT statements to retain granular log detail.

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

Troubleshooting Guide: SQL Server Error 4328 – Missing File During Roll Forward

Why This Error Happens

Error 4328 occurs when SQL Server attempts to restore a transaction log backup sequence but cannot locate a file (typically a differential or log backup file) that was referenced during the original backup chain. This commonly happens when a backup file has been deleted, moved, renamed, or corrupted between the time it was created and when the restore sequence attempts to use it. It can also occur if backup files are restored out of order, or if a backup set spans multiple files and one volume is missing from a multi-file backup device.

Step-by-Step Resolution Guide

Step 1: Verify the Backup File Chain Integrity

  • Check the exact file path referenced in the error message (the “%ls” placeholder will show the actual missing filename).
  • Navigate to your backup directory, typically C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Backup\, and confirm whether the file physically exists.
  • Run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourFile.trn' in SQL Server Management Studio to validate file metadata and LSN ranges.

Step 2: Reconstruct the Correct Restore Sequence

  • Query msdb.dbo.backupset and msdb.dbo.backupmediafamily to list all backups taken for the database in chronological order.
  • Confirm the LSN values align sequentially: the first_lsn of the next log backup must match the last_lsn of the previous one.
  • Identify whether a log backup between the two mentioned LSNs was skipped, overwritten, or never captured.

Step 3: Restore from an Alternate or Redundant Backup Source

  • Check secondary backup locations such as network shares, Azure Blob Storage, or tape archives for a copy of the missing file.
  • If using Windows Server 2025 Volume Shadow Copy Service (VSS), check vssadmin list shadows for a recoverable snapshot.
  • Restore the missing .trn or .diff file to the original backup folder path expected by SQL Server before re-running the RESTORE LOG command.

Step 4: Rebuild the Backup Chain if File Is Permanently Lost

  • If the file cannot be recovered, use RESTORE DATABASE ... WITH RECOVERY at the last successfully applied LSN to bring the database online, accepting data loss up to that point.
  • Immediately take a fresh full backup afterward to establish a new, uninterrupted backup chain.
  • Update your backup job (SQL Agent job or Maintenance Plan) to prevent future gaps, ensuring backup retention policies don’t purge files prematurely.

Alternative or Verification Steps

  • Run RESTORE VERIFYONLY FROM DISK = 'C:\Backups\YourFile.trn' after restoring the correct file to confirm it is readable and not corrupted before applying it to the database.
  • If the issue persists, check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for correlating I/O or antivirus interference errors that may have caused the file deletion in the first place.

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

Troubleshooting Guide: Error 4326 – “The log in this backup set terminates at LSN %.*ls”

Why This Error Happens

This error occurs when attempting to restore a transaction log backup that does not logically connect to the LSN (Log Sequence Number) chain of the previously restored backup. This typically happens when a log backup is applied out of order, a log backup in the sequence is skipped or missing, or a new full backup was taken between the last restore and the current log backup, effectively breaking the chain. SQL Server enforces strict LSN continuity to guarantee transactional consistency, so any gap in the sequence will trigger this failure.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain and LSN Sequence

  • Open SQL Server Management Studio (SSMS) and run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDB.bak' to inspect FirstLSN, LastLSN, and CheckpointLSN values for each file.
  • Compare the LastLSN of the previously restored backup against the FirstLSN of the log backup you are trying to apply; they must align exactly.
  • Identify if a full or differential backup occurred between your last restore point and the failing log backup, as this resets the chain.

Step 2: Restore Backups in the Correct Order

  • Start fresh with the most recent full backup using RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\Full.bak' WITH NORECOVERY.
  • Apply any differential backup (if available) using RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\Diff.bak' WITH NORECOVERY.
  • Sequentially apply each transaction log backup in chronological order using RESTORE LOG YourDB FROM DISK = 'C:\Backups\Log1.trn' WITH NORECOVERY, ensuring no file in the sequence is skipped.

Step 3: Check for Missing or Corrupted Log Files

  • Navigate to the backup storage path (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\) and confirm all .trn files referenced in your backup job history exist.
  • If a log backup file is missing or corrupted, the chain is permanently broken from that point forward, and you must restart the restore sequence from the last valid full backup.
  • Review SQL Server Agent Job History (via SSMS under SQL Server Agent > Jobs) to confirm log backups ran successfully and without interruption on schedule.

Step 4: Finalize the Restore

  • Once all log backups are applied in order, bring the database online using RESTORE DATABASE YourDB WITH RECOVERY.
  • Confirm the database status changes from “Restoring” to “Online” in SSMS under Databases.

Alternative or Verification Steps

  • Run SELECT name, state_desc FROM sys.databases WHERE name = 'YourDB'; to confirm the database shows an ONLINE state after recovery.
  • If the log chain is unrecoverable due to a permanently missing file, take a new full backup immediately after recovery and establish a fresh log backup chain going forward to prevent recurrence.

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

Troubleshooting Guide: SQL Server Error 4323 – Database Left in Damaged State After CONTINUEAFTERERROR

Why This Error Happens

This error occurs when a previous RESTORE operation was executed with the CONTINUE_AFTER_ERROR option and encountered corruption, causing SQL Server to flag the database as being in a “Restoring” or suspect state with potentially unreadable pages. SQL Server 2025 blocks further restore sequence operations (like restoring subsequent differential or log backups) because it cannot guarantee the integrity of the data already applied. This typically stems from a corrupted backup file, damaged storage media, or an interrupted I/O operation during the initial restore.

Step-by-Step Resolution Guide

Step 1: Verify the Current State of the Database

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the following query to check the database status:
SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm if the state is RESTORING or SUSPECT, which validates the Error 4323 behavior.

Step 2: Restart the Restore Sequence From a Clean Full Backup

  • Do not attempt to resume the damaged restore chain; it cannot be safely continued.
  • Drop the corrupted database shell using:
DROP DATABASE YourDatabaseName;
  • Restore from a known-good Full backup file located in your backup directory (e.g., D:\SQLBackups\YourDatabase_FULL.bak) using WITH NORECOVERY to allow subsequent log restores:
RESTORE DATABASE YourDatabaseName FROM DISK = 'D:\SQLBackups\YourDatabase_FULL.bak' WITH NORECOVERY;

Step 3: Validate Backup File Integrity Before Re-Applying

  • Before restoring differential or transaction log files, run RESTORE VERIFYONLY to check for corruption in the files themselves:
RESTORE VERIFYONLY FROM DISK = 'D:\SQLBackups\YourDatabase_LOG.trn';
  • If verification fails, locate an alternative backup copy, ideally from a secondary storage location or offsite backup repository.

Step 4: Check Underlying Storage and Hardware Health

  • Open Event Viewer on Windows Server 2025 and navigate to Windows Logs > System to check for disk-related errors (Event ID 7 or 11) that may have caused the original corruption.
  • Run chkdsk D: /f (replace D: with your SQL data/backup drive) during a maintenance window to repair underlying file system issues.
  • Ensure antivirus or backup agent software is not locking .bak or .trn files during the restore process.

Step 5: Complete the Restore Sequence

  • Once the Full backup is restored with NORECOVERY, sequentially apply valid differential and log backups.
  • Finish the sequence with WITH RECOVERY to bring the database online:
RESTORE DATABASE YourDatabaseName WITH RECOVERY;

Alternative or Verification Steps

  • Verify Success: Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm there is zero allocation or consistency errors post-restore.
  • Alternative Fix: If no clean backup chain exists, attempt RESTORE DATABASE ... WITH RECOVERY directly on the damaged database to bring it online in a “repair-only” state, then immediately run DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS option as a last resort to salvage accessible data.

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

Troubleshooting Guide: Error 4322 in Microsoft SQL Server 2025

Why This Error Happens

Error 4322 occurs when performing a point-in-time restore where the specified STOPAT time precedes the log records contained in the backup set being restored. This typically happens when transaction log backups are applied out of sequence, or when the recovery chain is broken because a differential or full backup was skipped. SQL Server refuses to roll forward because applying these log records would violate the logical consistency of the point-in-time requested, leaving the database in RESTORING state to prevent data corruption.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain Sequence

  • Query msdb.dbo.backupset to review backup_start_date, backup_finish_date, and database_backup_lsn for all backups involved.
  • Run: SELECT database_name, backup_start_date, first_lsn, last_lsn, backup_type FROM msdb.dbo.backupset WHERE database_name = 'YourDB' ORDER BY backup_start_date;
  • Confirm that the full backup, differential (if any), and log backups form an unbroken LSN chain leading up to your desired restore point.

Step 2: Restore in the Correct Order with Proper STOPAT Value

  • Restore the full backup first using WITH NORECOVERY.
  • Example: RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\YourDB_Full.bak' WITH NORECOVERY;
  • Apply differential backup (if present) before any log backups: RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\YourDB_Diff.bak' WITH NORECOVERY;
  • Restore log backups sequentially in chronological order, adjusting the STOPAT clause to a timestamp that falls within the range covered by the log backup you are currently applying, not before it: RESTORE LOG YourDB FROM DISK = 'C:\Backups\YourDB_Log1.trn' WITH NORECOVERY, STOPAT = '2025-01-15T14:30:00';

Step 3: Correct the STOPAT Timestamp if Misaligned

  • Cross-check the STOPAT value against the first_lsn and last_lsn timestamps retrieved in Step 1.
  • If the specified time is earlier than the backup set’s log range, adjust STOPAT to a valid time within the correct log file, or omit STOPAT entirely on earlier log restores and only apply it on the final log file.
  • Re-run the restore sequence from the full backup if the database was already left in an inconsistent RESTORING state.

Step 4: Finalize Recovery

  • Once all correct log backups are applied with the right STOPAT time, issue the final recovery command: RESTORE DATABASE YourDB WITH RECOVERY;
  • Confirm no further restore operations are pending before executing this step, as it will bring the database online and end the restore sequence.

Alternative or Verification Steps

  • Verify success by checking sys.databases for the database state: SELECT name, state_desc FROM sys.databases WHERE name = 'YourDB'; — it should read ONLINE.
  • If the chain cannot be repaired due to a missing or corrupted log backup file, restore from the last known good full or differential backup and accept the nearest valid recovery point instead of the originally intended STOPAT time.

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

Troubleshooting Guide: SQL Server Error 4319 – Interrupted Restore Sequence

Why This Error Happens

Error 4319 occurs when SQL Server detects that a previous RESTORE operation using WITH NORECOVERY was stopped before it could fully apply all the necessary transaction log or differential files to the database. This typically happens when a restore sequence is broken mid-process—for example, if a script fails, a connection drops, or a file in the sequence is skipped or applied out of order. Because the database is left in a “restoring” state expecting a specific Log Sequence Number (LSN), SQL Server blocks further restores until the sequence is corrected to prevent data corruption.

Step-by-Step Resolution Guide

Step 1: Verify the Current Database State

  • Open SSMS or run a query against the sys.databases system view to check the state of the target database.
  • Run the following T-SQL command to confirm the status:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm the status reads RESTORING. If it does, the sequence is indeed paused and waiting for the correct file.

Step 2: Identify the Correct LSN and Backup Chain

  • Determine the exact Log Sequence Number (LSN) where the restore stopped by querying the backup history.
  • Use the RESTORE HEADERONLY command on your backup files to check the FirstLSN and LastLSN values:
  RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDatabase_log.trn';
  • Ensure the backup file you intend to restore next starts exactly where the last successful restore left off.

Step 3: Restart the Restore Sequence from the Full Backup

  • Since the sequence integrity is broken, you generally cannot simply “resume” the interrupted file; you must restart the entire sequence.
  • Drop the current database or use WITH REPLACE to overwrite the existing files.
  • Re-run the restore starting from the Full backup, followed by the Differential (if applicable), ensuring every step except the final one uses WITH NORECOVERY:
  RESTORE DATABASE YourDatabaseName 
  FROM DISK = 'C:\Backups\YourDatabase_full.bak' 
  WITH NORECOVERY, REPLACE;

Step 4: Check File System and Storage Integrity

  • If the sequence continues to fail even after restarting, verify that the backup file (%ls referenced in the error) is not corrupted or locked by another process.
  • Check the Windows Server 2025 Event Viewer under Windows Logs > Application for any underlying disk I/O errors (Event ID 7 or 9) that might indicate the physical backup file is damaged.
  • Ensure the SQL Server service account has full Read/Write permissions on the backup folder path.

Alternative or Verification Steps

  • Verification: Once the final log file is restored using WITH RECOVERY, query sys.databases again to confirm the state_desc has changed from RESTORING to ONLINE.
  • Alternative: If the specific transaction log file is permanently lost or corrupted, you cannot proceed with an un-broken chain; you must restart the restore process using only the Full and Differential backups (bringing the DB online via WITH RECOVERY at that point), accepting the loss of transactions made after that differential backup.

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

Troubleshooting Guide: SQL Server Error 4320

Why This Error Happens

Error 4320 occurs when SQL Server detects that a data file is being restored out of sequence, typically because an earlier differential or transaction log backup in the restore chain was skipped or applied incorrectly. This commonly happens when a NORECOVERY restore sequence is broken, a backup file is corrupted, or the Log Sequence Number (LSN) chain between the full backup and subsequent files does not match. It can also surface when a file was previously restored using WITH RECOVERY prematurely, locking the database out of further restore operations.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain Integrity

  • Run RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourFile.bak' to inspect the LSN values (FirstLSN, LastLSN, CheckpointLSN).
  • Confirm that the DatabaseBackupLSN of your differential or log backup matches the CheckpointLSN of the full backup used as the base.
  • Cross-reference timestamps in msdb.dbo.backupset to ensure no backup files are missing from the sequence.

Step 2: Restart the Restore Sequence with Correct Syntax

  • Drop the partially restored database if it is stuck in a “Restoring” state: DROP DATABASE YourDB;
  • Restore the full backup fresh using the NORECOVERY clause:
    RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\Full.bak' WITH NORECOVERY;
  • Apply each differential and log backup strictly in chronological order, keeping NORECOVERY on every file except the final one.

Step 3: Check File System and Storage Health

  • Navigate to the backup directory (e.g., D:\SQLBackups\) and verify the .bak or .trn files are not flagged as “corrupted” or zero-byte by running CHECKSUM during the backup process in the future.
  • Use RESTORE VERIFYONLY FROM DISK = 'C:\Backups\YourFile.bak' to validate the specific file causing the 4320 error.
  • If using Windows Server 2025 Storage Spaces or SMB shares, check Event Viewer under Windows Logs > System for disk I/O errors that may have truncated the backup file during the write process.

Step 4: Finalize the Recovery

  • Once all transaction logs are applied in order, issue the final recovery command to bring the database online:
    RESTORE DATABASE YourDB WITH RECOVERY;
  • Ensure no backup files in the sequence were skipped between the first and last LSN numbers identified in Step 1.

Alternative or Verification Steps

  • Verify the Fix: Query SELECT state_desc FROM sys.databases WHERE name = 'YourDB'; to confirm the status reads ONLINE rather than RESTORING.
  • Alternative Solution: If the backup chain is unrecoverable due to a missing log file, you may need to accept data loss up to the last valid full/differential backup by terminating the recovery with RESTORE DATABASE YourDB WITH RECOVERY immediately after the last successfully applied file, bypassing the corrupted log segment.

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

Troubleshooting Guide: SQL Server Error 4318 — “File Has Been Rolled Forward to LSN”

Why This Error Happens

Error 4318 occurs when SQL Server attempts to apply a transaction log backup that is out of sequence with the database’s current recovery state, meaning the database has already been rolled forward past the point where this specific log file begins. This typically happens when a log backup is restored out of order, a backup in the restore chain is skipped or missing, or the LSN (Log Sequence Number) chain has been broken due to a manual log truncation or a mismatched backup set. In essence, SQL Server is detecting a gap or overlap in the continuity required to replay transaction logs correctly.

Step-by-Step Resolution Guide

Step 1: Verify the Restore Sequence and LSN Chain

  • Open SQL Server Management Studio (SSMS) or run a query using RESTORE HEADERONLY against each backup file to inspect FirstLSN, LastLSN, and CheckpointLSN values.
  • Confirm backups are being restored strictly in chronological order: Full → Differential (if any) → Transaction Logs in sequence.
  • Use the following query to check the current recovery LSN of the target database:
  SELECT name, redo_start_lsn, differential_base_lsn 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');

Step 2: Restart the Restore Chain from the Last Valid Full Backup

  • Drop or restore the database WITH REPLACE using the most recent full backup to reset the baseline LSN.
  • Example command:
  RESTORE DATABASE YourDatabaseName 
  FROM DISK = 'C:\Backups\YourDatabase_Full.bak' 
  WITH NORECOVERY, REPLACE;
  • Reapply differential and log backups strictly in the correct order without skipping any file in the sequence.

Step 3: Identify and Exclude the Mismatched or Duplicate Log File

  • Check the specific log backup referenced in the error message (the file path shown in %ls) and compare its FirstLSN against the database’s current redo_start_lsn.
  • If the log file’s starting LSN is lower than the current rolled-forward LSN, it is redundant — skip it and move to the next sequential log file in the chain.
  • Locate backup history in msdb.dbo.backupset to rebuild an accurate timeline:
  SELECT backup_start_date, first_lsn, last_lsn, type 
  FROM msdb.dbo.backupset 
  WHERE database_name = 'YourDatabaseName' 
  ORDER BY backup_start_date;

Step 4: Validate Backup Integrity and Storage Path

  • On Windows Server 2025 / Windows 11, confirm the backup files haven’t been corrupted or truncated during transfer (check file size and CHECKSUM if enabled during backup).
  • Verify the backup storage path (e.g., D:\SQLBackups\TransactionLogs\) is accessible and not subject to permission issues or antivirus interference that could lock/alter files mid-restore.
  • Run RESTORE VERIFYONLY FROM DISK = 'PathToFile.trn' to confirm backup file integrity before reattempting the restore.

Step 5: Reapply Logs Using STOPAT or NORECOVERY Correctly

  • Ensure every restore command except the final one uses WITH NORECOVERY to keep the database in a restoring state.
  • Only the last transaction log in the sequence should use WITH RECOVERY to bring the database online.
  • Example:
  RESTORE LOG YourDatabaseName 
  FROM DISK = 'D:\SQLBackups\Log_02.trn' 
  WITH NORECOVERY;

Alternative or Verification Steps

  • After completing the restore chain, run DBCC CHECKDB('YourDatabaseName') to confirm database consistency and that no corruption resulted from the interrupted restore sequence.
  • If the LSN chain is irreparably broken (e.g., a required log backup is permanently lost), the only alternative is to restore from the last known good full/differential backup and accept data loss up to that point, then re-establish a new log backup chain going forward.

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

Troubleshooting Guide: SQL Server Error 4315 – “Some Files Still Require More Restore Steps”

Why This Error Happens

Error 4315 occurs when an online restore sequence is incomplete because the database contains filegroups or files that have not yet had all required differential or transaction log backups applied. This typically happens when a RESTORE DATABASE…WITH RECOVERY statement is issued prematurely, before every file marked as “restoring” has received its full chain of backups. It can also occur if a filegroup was taken offline mid-sequence and the backup chain for that specific file was broken or skipped.

Step-by-Step Resolution Guide

Step 1: Verify the Current Restore State of All Files

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a new query window.
  • Run the following query to identify files still pending restoration:
SELECT name, physical_name, state_desc 
FROM sys.master_files 
WHERE database_id = DB_ID('YourDatabaseName');
  • Look specifically for a state_desc value of RESTORING, which confirms the file has not completed its sequence.

Step 2: Apply the Missing Backup Files in the Correct Order

  • Locate the specific differential or log backup files in your backup directory (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\).
  • Execute the restore command using the WITH NORECOVERY clause to keep the database in a loading state until the sequence is fully complete:
RESTORE LOG YourDatabaseName 
FROM DISK = 'C:\Backup\YourDatabase_Log1.trn' 
WITH NORECOVERY;
  • Repeat this process sequentially for every log or differential backup taken after the initial full backup.

Step 3: Finalize the Restore Sequence

  • Once all files show a consistent recovery LSN (Log Sequence Number) and no pending files remain, issue the final recovery command.
  • Run the command without specifying a backup file to bring the database online:
RESTORE DATABASE YourDatabaseName WITH RECOVERY;
  • Check the SQL Server Error Log (via SSMS or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm the recovery process finished without further warnings.

Step 4: Check for File-Specific Corruption or Permissions Issues

  • If Step 2 fails repeatedly for a specific file, verify the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read/Write permissions on the backup folder.
  • Navigate to the folder properties via File Explorer, select the Security tab, and ensure the service account is not restricted.

Alternative or Verification Steps

  • Verification: Run RESTORE HEADERONLY FROM DISK = 'path_to_backup_file' to confirm the BackupStartDate and BackupFinishDate align sequentially with no gaps in the LSN chain.
  • Alternative: If a specific log backup file is corrupted and cannot be applied, you may need to restore the database using WITH RECOVERY at the last known good restore point, accepting potential data loss for transactions occurring after that specific backup.

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

Why This Error Happens

Error 4314 occurs when SQL Server attempts to restore a transaction log backup that does not align with the Log Sequence Number (LSN) chain of the database. This typically happens because a differential or log backup was taken out of order, a full backup was restored without the NORECOVERY option, or the backup chain was broken by an intermediate operation (such as a manual log truncation or a switch to the SIMPLE recovery model). In legacy environments migrating to SQL Server 2025, this symptom is often flagged as “obsolete” because the specific backup set referenced in the error no longer exists in the current backup history, making automated remediation scripts fail silently.

Step-by-Step Resolution Guide

Step 1: Verify the Backup Chain Integrity

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025.
  • Run the following query to inspect the LSN chain: RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDB.bak'.
  • Confirm that FirstLSN and LastLSN values are sequential across your Full, Differential, and Log backups.

Step 2: Restore the Full Backup with NORECOVERY

  • Ensure the initial restore is not finalized prematurely:
RESTORE DATABASE YourDB 
FROM DISK = 'C:\Backups\YourDB_Full.bak' 
WITH NORECOVERY;
  • If the database is already online (recovered), you must start the restore process over, as you cannot apply logs to a recovered database.

Step 3: Apply Logs Sequentially and Recover

  • Apply only the log backups that fall within the valid LSN range identified in Step 1.
  • Use the final log restore command with the RECOVERY option to bring the database online:
RESTORE LOG YourDB 
FROM DISK = 'C:\Backups\YourDB_Log.trn' 
WITH RECOVERY;

Step 4: Check for Obsolete Backup History Entries

  • If the error persists due to “obsolete” metadata, clean the MSDB history tables.
  • Navigate to the msdb database and execute EXEC msdb.dbo.sp_delete_backuphistory @oldest_date = 'YYYY-MM-DD'; to purge stale references that might be confusing the restore sequence calculation.

Alternative or Verification Steps

  • Verification: After the database recovers, run SELECT state_desc FROM sys.databases WHERE name = 'YourDB'; and confirm the status reads ONLINE rather than RESTORING.
  • Alternative: If the LSN chain is irrecoverably broken (e.g., due to a missing differential backup), you must restart the recovery process using only the Full backup followed immediately by WITH RECOVERY, accepting the loss of transactions that occurred after the full backup was taken.

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

Troubleshooting Guide: SQL Server Error 4313 (Obsolete Backup/Media Marker)

Why This Error Happens

Error 4313 occurs when SQL Server 2025 attempts to read a backup set or media header that is flagged as obsolete, meaning the Log Sequence Number (LSN) chain is broken or the media header does not match what the restore sequence expects. This typically happens due to corrupted backup files, an interrupted backup write operation, or attempting to restore a differential/log backup out of sequence after a full backup was marked obsolete by a newer backup operation. In some cases, this is triggered by mismatched backup software versions interacting with the Windows Server 2025 Volume Shadow Copy Service (VSS) writer for SQL.

Step-by-Step Resolution Guide

Step 1: Verify the Integrity of the Backup Media

  • Run RESTORE VERIFYONLY FROM DISK = 'C:\Backups\YourFile.bak' in SQL Server Management Studio (SSMS) to check if the file is physically corrupted.
  • Check the physical storage path (local disk or network share) for connectivity drops that may have truncated the file during the backup write.
  • Inspect the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for accompanying I/O errors (such as Error 823 or 824) that often precede a 4313 obsolete marker.

Step 2: Rebuild the Backup Sequence Chain

  • Do not attempt to restore the differential or transaction log backup directly if the preceding Full backup is marked obsolete.
  • Take a fresh, immediate Full backup of the database to establish a new, valid starting point for the LSN chain:
  • BACKUP DATABASE [YourDB] TO DISK = 'C:\Backups\NewFull.bak' WITH INIT
  • If this is a Log Shipping or Always On Availability Group scenario, re-initialize the secondary replica from this new full backup rather than attempting to patch the old chain.

Step 3: Check VSS Writer and Permissions on Windows Server 2025

  • Open Command Prompt as Administrator and run vssadmin list writers to ensure the “SqlServerWriter” status reads as “No error” (stable state).
  • If the writer shows a failed state, restart the SQL Server VSS Writer service via services.msc by locating “SQL Server VSS Writer” and selecting Restart.
  • Ensure the service account running SQL Server has explicit Read/Write NTFS permissions on the backup destination folder to prevent the OS from locking or corrupting the file mid-write.

Step 4: Update SQL Server Cumulative Updates

  • Navigate to the Microsoft Update Catalog and verify you are running the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the update via the standalone installer to patch any known backup/restore engine bugs related to media set validation.
  • Reboot the Windows Server 2025 instance to ensure the SQL Server binaries are fully refreshed.

Alternative or Verification Steps

  • Verification: After creating the new Full backup in Step 2, immediately attempt a test restore to a different database name (e.g., YourDB_Test) using RESTORE DATABASE... WITH MOVE to confirm the chain is no longer obsolete.
  • Alternative: If the native backup file remains unusable, utilize a third-party repair tool specifically designed for .bak file header reconstruction, or restore from an older, verified valid backup set and accept the data loss gap between the corrupted backup and the last known good state.

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

Troubleshooting Guide: Error 4311 — RESTORE PAGE Not Allowed from Earlier SQL Server Backup Versions

Why This Error Happens

Error 4311 occurs because SQL Server 2025 enforces strict version compatibility checks for page-level restores, and the backup file being restored was generated by an older SQL Server engine version (such as SQL Server 2019 or 2022) that lacks the metadata structure required for granular page restores. This typically happens when backup files are migrated or copied from legacy instances without being revalidated against the newer backup format introduced in SQL Server 2025. Essentially, the backup’s internal version stamp doesn’t meet the minimum threshold SQL Server 2025 requires to perform a RESTORE PAGE operation, as opposed to a full database restore.

Step-by-Step Resolution Guide

Step 1: Verify the Backup’s Origin Version

  • Run the following T-SQL command to inspect backup header metadata:
  RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDatabase.bak'
  • Check the SoftwareVersionMajor and SoftwareVersionMinor columns in the result set.
  • Confirm if the backup originated from a version earlier than SQL Server 2022 (Major version 16) or SQL Server 2025 (Major version 17).

Step 2: Perform a Full Database Restore Instead of Page Restore

  • Since page-level restore is blocked, restore the full database first using:
  RESTORE DATABASE YourDatabase 
  FROM DISK = 'C:\Backups\YourDatabase.bak' 
  WITH REPLACE, RECOVERY
  • This bypasses the granular page restore limitation entirely by rehydrating the full database in one operation.

Step 3: Take a Fresh Full Backup on SQL Server 2025

  • Once the database is successfully attached/restored on the new instance, immediately generate a new backup using the current engine:
  BACKUP DATABASE YourDatabase 
  TO DISK = 'C:\Backups\YourDatabase_2025.bak' 
  WITH INIT, COMPRESSION
  • This new backup file will carry the correct 2025 version stamp, making it eligible for future RESTORE PAGE operations.

Step 4: Re-Attempt the RESTORE PAGE Operation

  • Using the newly created 2025-version backup file, retry the specific page restore command:
  RESTORE DATABASE YourDatabase PAGE = '1:258' 
  FROM DISK = 'C:\Backups\YourDatabase_2025.bak' 
  WITH NORECOVERY
  • Confirm the command processes without triggering Error 4311.

Step 5: Check Server Configuration for Compatibility Level

  • Open SQL Server Management Studio (SSMS) and verify the database compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase'
  • If the level is below 160 (SQL Server 2022) or 170 (SQL Server 2025), update it using:
  ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170

Alternative or Verification Steps

  • To verify the fix, run RESTORE HEADERONLY again on the new backup file and confirm the SoftwareVersionMajor column now reflects version 17.x (SQL Server 2025).
  • If RESTORE PAGE still fails after creating a new backup, use the Full Database Restore + Differential Backup approach as a workaround instead of relying on page-level restores for legacy data sources.

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

Troubleshooting Guide: SQL Server Error 4312 – Log Chain Gap Detected

Why This Error Happens

This error occurs when SQL Server detects a discontinuity in the transaction log sequence, typically caused by a missing differential or transaction log backup between the last full backup and the log you’re attempting to restore. It can also happen if a database was switched from SIMPLE to FULL recovery model without taking a new full backup afterward, which resets the log chain. Additionally, an intervening backup taken by another tool or process (such as a third-party agent) that truncated the log without your knowledge can silently break the chain.

Step-by-Step Resolution Guide

Step 1: Verify the Current Log Chain Status

  • Run the following query against the msdb database to review backup history:
  • SELECT database_name, backup_start_date, type, is_copy_only FROM msdb.dbo.backupset WHERE database_name = 'YourDBName' ORDER BY backup_start_date;
  • Look for type = 'D' (full), 'I' (differential), and 'L' (log) entries to identify where the gap begins.
  • Confirm the last_lsn of your most recent restored backup matches the first_lsn of the next log file in sequence.

Step 2: Take a Fresh Full Backup to Reset the Chain

  • Since the existing chain is broken, perform a new full backup immediately to establish a new baseline:
  • BACKUP DATABASE [YourDBName] TO DISK = 'C:\Backups\YourDBName_Full.bak' WITH INIT, COMPRESSION;
  • Ensure the database recovery model is set to FULL (not SIMPLE) via SSMS: Right-click Database > Properties > Options > Recovery Model.
  • Schedule subsequent differential and log backups immediately after to avoid recreating the gap.

Step 3: Restore Using the Correct Sequence

  • Restore the new full backup with NORECOVERY to allow subsequent logs to be applied:
  • RESTORE DATABASE [YourDBName] FROM DISK = 'C:\Backups\YourDBName_Full.bak' WITH NORECOVERY;
  • Apply any differential backups taken after the full backup, followed by transaction logs in strict chronological order.
  • Finish with RESTORE DATABASE [YourDBName] WITH RECOVERY; only after all available logs have been applied.

Step 4: Audit for External Interference

  • Check Windows Event Viewer (Applications and Services Logs > SQL Server) for unexpected BACKUP LOG operations around the time of the gap.
  • Disable or reconfigure any third-party backup agents (e.g., Veeam, Commvault) that may be issuing log truncation commands outside your maintenance plan.

Alternative or Verification Steps

  • Verify success by running RESTORE HEADERONLY FROM DISK = 'YourLogFile.trn' and confirming the FirstLSN aligns with the LastLSN of the previously restored file with no gaps.
  • If a valid log sequence cannot be reconstructed, consider accepting data loss up to the last full/differential backup point and restoring with WITH RECOVERY directly after the differential, bypassing the broken log segment entirely.

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

Troubleshooting Guide: Error 4310 – “RESTORE PAGE is not allowed on file because the file is not online”

Why This Error Happens

This error occurs when SQL Server 2025 attempts a page-level restore on a data file that is currently in an OFFLINE, RESTORING, or RECOVERY PENDING state rather than the required ONLINE state. Page-level restores are designed to be an online operation, meaning the database must be accessible and the specific file’s metadata in sys.master_files must reflect an operational status before SQL Server will apply the restored page. This is frequently caused by a prior failed restore sequence, a file left in a suspect state due to underlying storage corruption, or an incomplete transaction log chain that prevented the file from transitioning back to an online state.

Step-by-Step Resolution Guide

Step 1: Verify the Current State of the Database File

  • Open SQL Server Management Studio (SSMS) or a query window connected to the instance.
  • Run the following query to check file status:
  SELECT name, state_desc, physical_name 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');
  • Confirm whether the file shows OFFLINE, RECOVERY_PENDING, or SUSPECT instead of ONLINE.

Step 2: Check the Windows Storage Layer for File Accessibility

  • Navigate to the physical file path (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) and confirm the .mdf or .ndf file is not locked, moved, or missing.
  • On Windows Server 2025 / Windows 11, check Event Viewer under Windows Logs > System for any Disk or NTFS corruption warnings (Event ID 7 or 55) that may have forced the file offline.
  • If using Storage Spaces Direct or a SAN, verify the volume is mounted and not in a degraded state via Get-Volume in PowerShell.

Step 3: Bring the File Back Online Before Retrying the Restore

  • Attempt to bring the specific file online using:
  ALTER DATABASE YourDatabaseName 
  MODIFY FILE (NAME = YourLogicalFileName, OFFLINE = FALSE);
  • If the file remains unresponsive, restore the full file (not just the page) from the last known good full backup to reset its state:
  RESTORE DATABASE YourDatabaseName 
  FILE = 'YourLogicalFileName' 
  FROM DISK = 'C:\Backups\YourDatabase_Full.bak' 
  WITH NORECOVERY;

Step 4: Rebuild the Restore Sequence

  • Once the file is online, re-issue the RESTORE PAGE command targeting the specific corrupted page ID(s) identified in the SQL Server Error Log.
  • Follow immediately with a transaction log restore to roll the page forward and bring it current with the rest of the database:
  RESTORE LOG YourDatabaseName 
  FROM DISK = 'C:\Backups\YourDatabase_Log.trn' 
  WITH RECOVERY;

Alternative or Verification Steps

  • Verify the fix: Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm the page is no longer marked as corrupt and the file reports a clean bill of health.
  • Alternative solution: If the file cannot be brought online due to irreparable hardware failure, perform a full database restore to a new storage volume rather than attempting an isolated page restore.

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

Troubleshooting Guide: SQL Server Error 4309 – Page Restore Prevented by File State

Why This Error Happens

Error 4309 occurs because SQL Server 2025 requires a file to be in a stable, fully recovered state (ONLINE or previously part of a complete backup chain) before it will allow granular page-level restores. This typically happens when the file is marked as OFFLINE, RECOVERY_PENDING, or SUSPECT due to a broken backup chain, an incomplete differential/log sequence, or corruption at the file level rather than the page level. Because SQL Server cannot guarantee transactional consistency for just a few pages when the underlying file itself is in an unstable state, it forces a full file restore instead.

Step-by-Step Resolution Guide

Step 1: Verify the Current State of the Database File

  • Open SQL Server Management Studio (SSMS) 21 or run a query against sys.database_files and sys.master_files to check the state_desc column.
  • Run the following T-SQL to confirm file status:
  SELECT name, physical_name, state_desc 
  FROM sys.master_files 
  WHERE database_id = DB_ID('YourDatabaseName');
  • Look specifically for OFFLINE, RECOVERY_PENDING, or SUSPECT states, as these confirm why page restore is blocked.

Step 2: Review the Backup Chain for Gaps

  • Open Windows Terminal (Admin) or SSMS and query msdb.dbo.backupset to ensure there is an unbroken chain of Full → Differential → Transaction Log backups.
  • Check backup history using:
  RESTORE HEADERONLY FROM DISK = 'C:\Backups\YourDatabase.bak';
  • If a Full or Differential backup is missing from the sequence, page-level restore will remain unavailable until the chain is repaired or a new Full backup is taken.

Step 3: Perform a Full File Restore Instead of a Page Restore

  • Since SQL Server is explicitly blocking page restores, execute a full file-level restore using WITH NORECOVERY to keep the database in a restoring state for subsequent log application.
  • Example command:
  RESTORE DATABASE [YourDatabaseName] 
  FILE = 'YourDataFile' 
  FROM DISK = 'C:\Backups\YourDatabase_Full.bak' 
  WITH NORECOVERY;
  • Apply all subsequent transaction log backups in sequence to bring the file back online.

Step 4: Check File System and Storage Health

  • Navigate to the file path (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) and confirm the .mdf/.ndf file is not flagged as read-only or locked by antivirus/EDR software.
  • Run chkdsk C: /f on the Windows Server 2025 volume hosting the data files to rule out underlying disk corruption that may have triggered the file state change.

Alternative or Verification Steps

  • After completing the full file restore and applying logs, re-run RESTORE DATABASE ... WITH RECOVERY and confirm the database state changes to ONLINE via sys.databases.
  • If the issue persists, use DBCC CHECKDB on a restored copy of the database to rule out deeper corruption that may require a full DBCC CHECKDB WITH REPAIR_ALLOW_DATA_LOSS on a non-production instance first.

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

Why This Error Happens

Error 4308 typically surfaces during a piecemeal (online) restore sequence in SQL Server 2025 when a filegroup is brought online before all required transaction log backups have been applied. The message “The online restore is complete” is misleading—it indicates that an individual restore step finished, but the overall recovery chain is still broken because a subsequent log file is missing, corrupted, or was restored out of order. This commonly occurs when backup files sit on a network share with inconsistent NTFS/share permissions for the SQL Server service account, or when a backup set was truncated during copy.

Step-by-Step Resolution Guide

Step 1: Verify the Restore Sequence

  • Run RESTORE HEADERONLY FROM DISK = 'path\to\backup.trn' against every log backup in the chain to confirm LSNs are contiguous.
  • Check sys.master_files and msdb.dbo.restorehistory to identify which filegroup is still flagged as RESTORING.
  • Confirm no log backup is missing between the full backup and the point of failure.

Step 2: Validate File and Share Permissions

  • Ensure the SQL Server service account (visible in SQL Server Configuration Manager) has Read and Read & Execute NTFS permissions on the backup folder, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\.
  • If backups are on a network share, confirm the share permissions match the NTFS permissions exactly (no “Everyone = Read” mismatches).
  • Restart the SQL Server (MSSQLSERVER) service after any permission change via services.msc or Restart-Service MSSQLSERVER in PowerShell.

Step 3: Re-run the Restore with NORECOVERY

  • Re-issue the restore command explicitly specifying WITH NORECOVERY for all intermediate logs:
  RESTORE LOG [YourDB] FROM DISK = 'D:\Backups\log1.trn' WITH NORECOVERY;
  • Only use WITH RECOVERY on the final log in the chain to bring the filegroup fully online.
  • If a backup file is confirmed corrupted (via RESTORE VERIFYONLY), source a fresh copy from the backup repository before resuming.

Step 4: Check Windows Server 2025 File System Health

  • Run chkdsk D: /f (replace D: with the backup drive) during a maintenance window to rule out underlying disk corruption affecting the .bak/.trn files.
  • Review Event Viewer > Windows Logs > System for disk or storage controller errors around the time of the restore.

Alternative or Verification Steps

  • After completing the sequence, run RESTORE DATABASE [YourDB] WITH RECOVERY; and confirm the database state changes from RESTORING to ONLINE via SELECT state_desc FROM sys.databases WHERE name = 'YourDB';.
  • If error 4308 persists, perform a full STANDBY restore instead of NORECOVERY to inspect the database state without fully committing, then replay logs one at a time to isolate the corrupted file.

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

Troubleshooting Guide: SQL Server Error 4307 — Online Restore Failure

Why This Error Happens

Error 4307 occurs when SQL Server 2025 cannot complete a restore operation while the database remains online, typically because the restore sequence involves a file or filegroup that is required for database coherency but is left in an inconsistent or offline state. This often happens when attempting a page-level or file-level online restore on a database using the Simple Recovery Model, or when the primary filegroup itself is the target of the restore. Since online restores require transaction log backups to roll the database forward to a consistent state, missing log backups or an incompatible recovery model will trigger this failure.

Step-by-Step Resolution Guide

Step 1: Verify the Database Recovery Model

  • Open SSMS, right-click the database, select Properties > Options, and check the Recovery Model field.
  • Online restores of individual files/pages require Full or Bulk-Logged recovery model; Simple Recovery Model does not support this.
  • Run the following T-SQL to confirm via script:
  SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'YourDatabaseName';

Step 2: Check Whether the Primary Filegroup Is Involved

  • Online restores cannot be performed if the restore operation includes the primary filegroup while the database is online.
  • Identify which filegroup/file is being restored using:
  RESTORE FILELISTONLY FROM DISK = 'C:\Backups\YourBackup.bak';
  • If the primary filegroup is involved, an offline restore is mandatory — proceed to Step 3.

Step 3: Perform an Offline Restore (Forced)

  • Take the database offline manually or let SQL Server force it:
  RESTORE DATABASE YourDatabaseName
  FILE = 'YourDataFile'
  FROM DISK = 'C:\Backups\YourBackup.bak'
  WITH NORECOVERY, REPLACE;
  • Ensure no active connections are locking the database by running:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Complete the restore sequence with subsequent log backups, then run RESTORE DATABASE YourDatabaseName WITH RECOVERY;.

Step 4: Validate File and Folder Permissions

  • On Windows Server 2025/Windows 11, confirm the SQL Server service account has Full Control on the backup folder (e.g., C:\Backups\) and the data/log file directories (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Use icacls "C:\Backups" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)F to reset permissions if corruption or access denial is suspected.

Alternative or Verification Steps

  • After recovery, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; to confirm database consistency and that no corruption remains.
  • If the online restore is still required for uptime purposes, ensure the database is in Full Recovery Model with uninterrupted log backup chains, and restore only secondary (non-primary) filegroups while the rest of the database remains online.

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

Troubleshooting Guide: SQL Server Error 4303 — Roll Forward Start Point Incomplete

Why This Error Happens

This error occurs when SQL Server detects that the restore sequence is incomplete because the transaction log chain has a gap between the current roll forward LSN and the LSN required to bring the database to a consistent state. This is typically caused by restoring log backups out of order, skipping a required differential or log backup in the sequence, or attempting to recover the database (using WITH RECOVERY) before all necessary backups have been applied. It can also result from a missing or corrupted log backup file that breaks the continuity of the LSN chain.

Step-by-Step Resolution Guide

Step 1: Verify the Complete Backup Chain

  • Query msdb.dbo.backupset to list all full, differential, and log backups in chronological order for the affected database.
  • Run: SELECT backup_start_date, type, first_lsn, last_lsn, database_backup_lsn FROM msdb.dbo.backupset WHERE database_name = 'YourDB' ORDER BY backup_start_date
  • Confirm there are no missing log backup files between the last restored LSN and the target recovery point.

Step 2: Restart the Restore Sequence with NORECOVERY

  • Begin again from the most recent full backup using RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\YourDB_Full.bak' WITH NORECOVERY.
  • Apply any differential backup using RESTORE DATABASE YourDB FROM DISK = 'C:\Backups\YourDB_Diff.bak' WITH NORECOVERY.
  • Restore every subsequent transaction log backup in exact chronological order, each WITH NORECOVERY, ensuring none are skipped.

Step 3: Locate and Apply Any Missing Log Backups

  • Check the backup file storage location (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\) for any .trn files that were not included in the restore script.
  • If a log backup file is missing or corrupted, check for a secondary copy on a backup server, Azure Blob Storage, or third-party backup tool repository.
  • Re-run the RESTORE LOG command for the missing LSN range once the file is located.

Step 4: Finalize Recovery

  • Once all log backups up to and including the required LSN are applied, run RESTORE DATABASE YourDB WITH RECOVERY to bring the database online.
  • Confirm no further “additional roll forward” messages appear in the SQL Server Error Log or Windows Event Viewer under Event ID 4303.

Alternative or Verification Steps

  • Verify success by checking the database state with SELECT name, state_desc FROM sys.databases WHERE name = 'YourDB'; it should report ONLINE.
  • If a required log backup is permanently lost, your only alternative is to restore to the last consistent point using WITH STOPAT set just before the gap, accepting data loss up to that LSN.

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

Why This Error Happens

Error 4305 occurs when SQL Server attempts to apply a transaction log backup that does not align sequentially with the last restored log file, meaning the Log Sequence Number (LSN) chain is broken. This typically happens because a differential or full backup was restored out of order, an intermediate log backup file is missing, or the database was taken out of “RESTORING” state (recovered) before all logs were applied. It can also occur if a new full backup was taken on the source database, resetting the LSN chain, while the restore sequence on the target still expects logs from the old chain.

Step-by-Step Resolution Guide

Step 1: Verify the LSN Chain Sequence

  • Query the backup history on the source server using RESTORE HEADERONLY against each .trn file to check FirstLSN and LastLSN values.
  • Confirm that the LastLSN of the previously restored file matches the FirstLSN of the next file in sequence.
  • Identify any gaps where a .trn file might be missing from the folder (e.g., D:\Backups\Logs\).

Step 2: Restart the Restore Sequence from the Last Full Backup

  • Drop or rename the existing database if it is stuck in a “Restoring” state via SSMS or DROP DATABASE [YourDB].
  • Restore the most recent Full Backup using WITH NORECOVERY.
  • Apply the Differential Backup (if available) immediately after, also using WITH NORECOVERY.
  • Example command: RESTORE DATABASE [YourDB] FROM DISK = 'D:\Backups\Full.bak' WITH NORECOVERY

Step 3: Apply Log Backups in Correct Order

  • Manually script out the restore commands for every single .trn file in the exact chronological order they were created.
  • Do not skip files even if you believe the data is redundant; SQL Server requires every LSN link to be intact.
  • Use WITH NORECOVERY for every log file except the very last one in the chain.

Step 4: Finalize the Recovery

  • Once all available logs are applied, run the final restore command using WITH RECOVERY to bring the database online.
  • Example command: RESTORE DATABASE [YourDB] WITH RECOVERY

Alternative or Verification Steps

  • To verify success, check the SQL Server Error Log or run SELECT state_desc FROM sys.databases WHERE name = 'YourDB'; to confirm the status reads “ONLINE” rather than “RESTORING.”
  • If a log file is permanently corrupted or missing and cannot be recovered, you must start the restore process over using only the Full Backup and accept data loss up to the point of that specific backup, as the LSN chain cannot be artificially bypassed.

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

Why This Error Happens

Error 4302 occurs when a RESTORE DATABASE or RESTORE LOG statement combines the WITH ONLINE option with another option that SQL Server’s online restore engine cannot process simultaneously, such as NORECOVERY, STANDBY, REPLACE, or certain MOVE configurations used during a piecemeal restore. Online restore requires the primary filegroup to remain accessible while secondary filegroups are restored, and options like NORECOVERY force the entire database offline, which directly contradicts that requirement. This is typically a syntax/logic conflict in the T-SQL script rather than a permissions or corruption issue, often introduced by automated backup/restore scripts that were not updated for online restore scenarios.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Option in the Restore Script

  • Open the T-SQL script or SQL Server Agent job step that triggered the error.
  • Look for WITH ONLINE paired with NORECOVERY, STANDBY, or REPLACE in the same RESTORE statement.
  • Check SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact %ls value substituted into the message — this tells you precisely which option conflicted.

Step 2: Remove or Replace the Conflicting Option

  • If performing a piecemeal/online restore, remove NORECOVERY and allow the restore to default to RECOVERY for the primary filegroup, since ONLINE already keeps the database partially available.
  • If you intended to leave the database in a non-recovered state for further log restores, drop the ONLINE keyword instead and perform the restore offline.
  • Example corrected syntax:
RESTORE DATABASE SalesDB
FILEGROUP = 'FG_Secondary'
FROM DISK = 'D:\Backups\SalesDB_FG.bak'
WITH ONLINE;

Step 3: Re-Sequence Multi-Step Restores

  • If your script restores multiple filegroups or logs in sequence, ensure only the final statement in the chain uses RECOVERY (implicit default) and intermediate steps use NORECOVERY without the ONLINE keyword.
  • Separate the online filegroup restore commands from any command requiring NORECOVERY/STANDBY.

Step 4: Reissue the Command and Monitor

  • Run the corrected script in SQL Server Management Studio (SSMS) connected to the Windows Server 2025 / Windows 11 instance.
  • Watch the Messages tab for confirmation: RESTORE DATABASE successfully processed X pages...
  • Confirm no Error 4302 or related errors (4303, 3015) appear in the output.

Alternative or Verification Steps

  • Run SELECT state_desc, is_in_standby FROM sys.databases WHERE name = 'SalesDB'; to confirm the database is in ONLINE or appropriate RESTORING state after the fix.
  • If the conflict persists, perform the restore fully offline (drop ONLINE entirely) during a maintenance window, then bring the database back online manually with ALTER DATABASE SalesDB SET ONLINE; once all filegroups are recovered.

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

Troubleshooting Guide: Error 4223 — Log Backup Fails with MAXVLFCOUNT Option on Hadron Secondaries

Why This Error Happens

Error 4223 occurs because the MAX_VLF_COUNT option for BACKUP LOG is only valid when executed against the primary replica of an Always On Availability Group (internally referred to as “Hadron” in SQL Server). When this backup option is issued against a secondary replica, SQL Server 2025 rejects the command because VLF (Virtual Log File) count enforcement logic requires write access to transaction log metadata that secondaries do not own. This is a design limitation rather than a corruption or permissions issue — it stems from attempting to pair a primary-only option with a read-only replica backup operation.

Step-by-Step Resolution Guide

Step 1: Identify Where the Backup Job Is Running

  • Open SQL Server Management Studio (SSMS) and connect to the Availability Group listener or the specific replica instance.
  • Run the following query to confirm replica role:
  SELECT role_desc FROM sys.dm_hadr_availability_replica_states 
  WHERE is_local = 1;
  • If the result returns SECONDARY, this confirms the root cause of Error 4223.

Step 2: Remove MAXVLFCOUNT from Secondary Backup Scripts

  • Edit the backup job step (via SQL Server Agent or maintenance plan) running on the secondary replica.
  • Remove the MAX_VLF_COUNT = n clause from the BACKUP LOG statement, for example:
  BACKUP LOG [YourDatabase] 
  TO DISK = 'D:\Backups\YourDatabase_log.trn';
  • Save and redeploy the job on all secondary-hosted backup schedules.

Step 3: Relocate MAXVLFCOUNT Logic to the Primary Replica

  • If VLF count control is required, schedule a separate job that runs BACKUP LOG ... WITH MAX_VLF_COUNT exclusively against the primary replica.
  • Use sys.fn_hadr_backup_is_preferred_replica to dynamically route backup jobs only when the current node is primary:
  SELECT sys.fn_hadr_backup_is_preferred_replica('YourDatabase');
  • Wrap the MAX_VLF_COUNT logic in a conditional check so it only executes when this function returns 1 and the replica role is PRIMARY.

Step 4: Validate Backup Preference Routing in the Availability Group

  • Open SSMS → Availability Groups → Properties → Backup Preferences.
  • Confirm the “Backup Preference” setting (e.g., Primary, Secondary only, or Prefer Secondary) aligns with where your MAX_VLF_COUNT jobs are configured to run.
  • Adjust routing so VLF-count-enforced backups always target the primary, regardless of AG failover state.

Alternative or Verification Steps

  • Re-run the backup job manually on the primary replica using BACKUP LOG ... WITH MAX_VLF_COUNT and confirm it completes without Error 4223.
  • If failovers are frequent, implement a wrapper stored procedure that checks replica role at runtime and conditionally omits MAX_VLF_COUNT when executing on a secondary, ensuring uninterrupted log backups during automatic failover events.

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

Troubleshooting Guide: Error 4221 – Login to Read-Secondary Failed Due to Row Versioning Timeout

Why This Error Happens

This error occurs because the secondary replica was restarted or recycled while transactions were still in-flight on the primary, leaving a gap in the persisted version store required for snapshot isolation reads. SQL Server 2025 requires the replica to rebuild and align its row versioning chain (HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING) before it can safely serve read-only connections, and until that transition completes, logins are blocked. This is commonly triggered by aggressive failover automation, delayed redo on the secondary, or insufficient tempdb/version store capacity to catch up quickly.

Step-by-Step Resolution Guide

Step 1: Confirm the Replica Health and Wait Type

  • Run the following on the secondary replica to confirm the wait type is active:
  SELECT * FROM sys.dm_os_waiting_tasks WHERE wait_type = 'HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING';
  • Check sys.dm_hadr_database_replica_states for synchronization_state and is_primary_replica to confirm the replica is in SYNCHRONIZED or SYNCHRONIZING state.
  • Validate redo queue size via redo_queue_size column — large values indicate the replica is still catching up.

Step 2: Increase Tempdb and Version Store Capacity

  • Navigate to SQL Server Configuration Manager > SQL Server Services > confirm tempdb data files are on fast storage (NVMe/SSD).
  • Increase tempdb file count to match logical CPU cores (edit via SSMS or):
  ALTER DATABASE tempdb ADD FILE (NAME = tempdev2, FILENAME = 'D:\SQLData\tempdb2.ndf', SIZE = 2048MB, FILEGROWTH = 512MB);
  • Monitor sys.dm_tran_version_store_space_usage to ensure version store isn’t being starved by long-running transactions on the primary.

Step 3: Adjust Connection Retry and Read-Only Routing Settings

  • In your application connection string, increase Connect Timeout and enable retry logic to tolerate the versioning transition window (typically 30–120 seconds).
  • On Windows Server 2025, verify the Always On Availability Group listener settings using:
  Get-ClusterResource | Where-Object {$_.ResourceType -eq "SQL Server Availability Group"}
  • Avoid forcing immediate reads on a freshly restarted secondary — delay application-level read redirection until the replica reports HEALTHY in sys.dm_hadr_availability_replica_states.

Step 4: Restart the Secondary Replica Cleanly (If Stuck)

  • If the wait persists beyond 5–10 minutes with no progress, manually suspend and resume data movement for the affected database:
  ALTER DATABASE [YourDB] SET HADR SUSPEND;
  ALTER DATABASE [YourDB] SET HADR RESUME;
  • This forces SQL Server to reinitialize the version store transition cleanly rather than waiting indefinitely.

Alternative or Verification Steps

  • Verify the fix by running a test read-only connection against the secondary using ApplicationIntent=ReadOnly in the connection string and confirming successful login without delay.
  • If the issue recurs frequently, consider disabling automatic failover temporarily and switching to manual failover mode via SSMS > Availability Group Properties > Failover Mode, to prevent replica recycling during high transaction load.

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

Troubleshooting Guide: Error 4222 – Log Backup Fails with MAXVLFCOUNT Option

Why This Error Happens

This error occurs when the MAX_VLF_COUNT option specified in the BACKUP LOG statement is lower than the actual number of Virtual Log Files (VLFs) currently present in the transaction log, preventing SQL Server from honoring the constraint. It typically happens after periods of heavy transactional activity, infrequent log backups, or improper autogrowth settings (small, frequent growth increments) that cause excessive VLF fragmentation. SQL Server 2025 enforces this threshold strictly to prevent backup operations from masking underlying log file health issues.

Step-by-Step Resolution Guide

Step 1: Check the Current VLF Count

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to the instance.
  • Run the following query to inspect the actual VLF count for the database in question:
SELECT COUNT(*) AS VLF_Count 
FROM sys.dm_db_log_info(DB_ID('YourDatabaseName'));
  • Compare this number against the MAX_VLF_COUNT value used in your backup script.

Step 2: Adjust the MAXVLFCOUNT Value or Remove It Temporarily

  • If the VLF count is only slightly above your threshold, increase the MAX_VLF_COUNT value in the backup command to a realistic number (e.g., from 1000 to 5000):
BACKUP LOG [YourDatabaseName] 
TO DISK = 'D:\Backups\YourDatabaseName_log.trn' 
WITH MAX_VLF_COUNT = 5000;
  • If immediate backup is required regardless of VLF count, temporarily omit the MAX_VLF_COUNT option to allow the backup to proceed while you plan remediation.

Step 3: Reduce VLF Fragmentation via Log File Maintenance

  • Perform a manual log backup (without the VLF restriction) to clear the inactive portion of the log.
  • Shrink the transaction log file to remove excess VLFs:
DBCC SHRINKFILE (YourDatabaseName_Log, 1);
  • Regrow the log file in fewer, larger increments to create a healthier VLF structure:
ALTER DATABASE [YourDatabaseName] 
MODIFY FILE (NAME = YourDatabaseName_Log, SIZE = 8192MB);

Step 4: Correct Log File Growth Settings

  • Navigate to SSMS > Database Properties > Files, or use T-SQL to set a fixed, appropriately sized growth increment (avoid percentage-based growth):
ALTER DATABASE [YourDatabaseName] 
MODIFY FILE (NAME = YourDatabaseName_Log, FILEGROWTH = 512MB);
  • This prevents future rapid VLF accumulation caused by small, frequent autogrowth events.

Alternative or Verification Steps

  • Re-run the original BACKUP LOG command with your intended MAX_VLF_COUNT value to confirm it now completes successfully.
  • If the error persists, run DBCC LOGINFO('YourDatabaseName') to audit individual VLF status and identify long-running active VLFs blocking truncation, then address any open transactions or replication/CDC consumers delaying log reuse.

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

Troubleshooting Guide: SQL Server Error 4219 – Log Backup Chain Broken

Why This Error Happens

This error occurs when the transaction log backup chain has been invalidated, most commonly because the database recovery model was switched from FULL (or BULK_LOGGED) to SIMPLE and back again, which truncates the log and breaks continuity. It can also happen after a database restore operation that doesn’t align with the existing log sequence number (LSN), or if a log backup file in the chain was deleted, corrupted, or never taken after the database was first set to FULL recovery. SQL Server 2025 requires an unbroken LSN sequence to apply log backups, so any gap forces a new chain to be started with a full backup.

Step-by-Step Resolution Guide

Step 1: Confirm the Recovery Model and Current Chain Status

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to check the recovery model and last log backup LSN:
  SELECT name, recovery_model_desc, log_reuse_wait_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • Verify log_reuse_wait_desc isn’t showing NOTHING while backups are failing, which confirms the chain is indeed broken.

Step 2: Perform a New Full Database Backup

  • Since the old chain is invalid, you must start a new one.
  • Run a full backup using T-SQL (adjust path for Windows Server 2025 storage):
  BACKUP DATABASE [YourDatabaseName] 
  TO DISK = N'C:\SQLBackups\YourDatabaseName_Full.bak' 
  WITH INIT, COMPRESSION, STATS = 10;
  • Ensure the SQL Server service account has write permissions to the C:\SQLBackups\ folder on Windows Server 2025.

Step 3: Re-Verify the Recovery Model Setting

  • Ensure the database is set to FULL recovery model (not SIMPLE) to prevent immediate re-breakage of the chain.
  • Run this command if needed:
  ALTER DATABASE [YourDatabaseName] SET RECOVERY FULL;
  • If using SQL Server Agent jobs or Maintenance Plans, confirm no step is set to “Shrink Database” or switching recovery models mid-job, as this is a common silent cause on Windows Server environments.

Step 4: Take an Immediate Log Backup

  • With the full backup complete and recovery model confirmed, take the first log backup to re-establish the chain.
  • Run:
  BACKUP LOG [YourDatabaseName] 
  TO DISK = N'C:\SQLBackups\YourDatabaseName_Log.trn' 
  WITH INIT, COMPRESSION;
  • Schedule subsequent log backups via SQL Server Agent to run at your standard interval (e.g., every 15 minutes).

Alternative or Verification Steps

  • Verify the fix: Run RESTORE HEADERONLY FROM DISK = 'C:\SQLBackups\YourDatabaseName_Log.trn' to confirm the backup is valid and chained correctly to the full backup’s LSN.
  • Alternative solution: If scheduled jobs continue to break the chain, check the SQL Server Agent Job History in SSMS for any conflicting “DBCC SHRINKFILE” or third-party backup software (like Veeam or Azure Backup) that may be issuing independent, non-SQL-native log truncations outside of your maintenance plan.