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

Why This Error Happens

This error occurs when a T-SQL query specifies index hints (e.g., WITH (INDEX(...))) more than once for the same table reference within a single SELECT, UPDATE, or DELETE statement. SQL Server 2025’s query parser strictly enforces that only one hint list per table alias is valid per statement scope. This typically happens due to copy-paste errors in complex joins, dynamically generated SQL, or legacy queries migrated from older schema versions that duplicated hint syntax across subqueries referencing the same table alias.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance.
  • Check the SQL Server Error Log via EXEC sp_readerrorlog or Event Viewer under Applications and Services Logs > MSSQLSERVER to locate the exact query batch tied to Error 1068.
  • Note the table name and alias flagged in the error message text.

Step 2: Review and Consolidate Index Hints

  • Open the query in a text editor or SSMS query window.
  • Search for repeated WITH (INDEX(...)), WITH (FORCESEEK), or WITH (NOLOCK, INDEX(...)) clauses applied to the same table alias.
  • Merge duplicate hints into a single WITH (...) block per table reference, e.g.: SELECT * FROM Orders AS o WITH (INDEX(IX_Orders_Date), NOLOCK).
  • Remove any redundant or conflicting hint lists for the same alias.

Step 3: Validate Dynamic SQL Generation

  • If the query is generated dynamically (via stored procedures, ORM tools, or application code), inspect the string-building logic in your application layer.
  • Check for loops or conditional blocks that may be appending hint clauses twice to the same table variable.
  • Rebuild the dynamic SQL string so hints are appended only once per table reference.

Step 4: Test the Corrected Query

  • Run the revised query in isolation using SSMS or Azure Data Studio against a test database.
  • Confirm no syntax errors are returned and execution plan generation completes successfully.

Alternative or Verification Steps

  • Use SET SHOWPLAN_TEXT ON or check the Execution Plan tab in SSMS to confirm the query compiles and the intended index is being used.
  • If the error persists in stored procedures, run sp_helptext '<ProcedureName>' to extract the full procedure definition and manually audit every table reference for duplicate hint lists.

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

Troubleshooting Guide: Error 1069 – “Index Hints Are Only Allowed in a FROM or OPTION Clause”

Why This Error Happens

This error occurs when a T-SQL query attempts to apply an index hint (such as WITH (INDEX(...))) outside of its valid placement within a FROM clause or as part of a query-level OPTION clause. SQL Server 2025’s parser strictly validates hint placement during query compilation, and syntax that was loosely tolerated in legacy applications or ORM-generated queries will now fail validation. This is typically a query authoring issue rather than a server configuration problem, often surfacing after an upgrade from an older SQL Server version with more permissive parsing behavior.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Windows Event Viewer (Event ID 1069) under Applications and Services Logs > MSSQLSERVER for the exact statement or stored procedure that triggered the error.
  • Use SQL Server Profiler or Extended Events (sqlserver.error_reported) to capture the full query text in real time.
  • Note the application, linked server, or ORM (Entity Framework, Hibernate, etc.) that generated the query.

Step 2: Correct the Index Hint Placement in the Query

  • Ensure the hint is attached directly to a table reference inside the FROM clause, e.g.:
    SELECT * FROM dbo.Orders WITH (INDEX(IX_Orders_CustomerID)) WHERE CustomerID = 10;
  • Remove any index hints mistakenly placed in WHERE, JOIN ON, or subquery filter conditions.
  • If the hint is meant to apply query-wide, move it to an OPTION clause instead, e.g.:
    OPTION (TABLE HINT(dbo.Orders, INDEX(IX_Orders_CustomerID)));

Step 3: Update ORM or Application-Generated SQL Templates

  • Review dynamic SQL generation logic in application code (C#, Java, .NET Core, etc.) for hardcoded hint strings.
  • Update stored procedures located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ deployment scripts if hints were embedded during a migration script.
  • Regenerate ORM mapping files or disable custom SQL hint injection in the data access layer until syntax is corrected.

Step 4: Validate Compatibility Level Settings

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the database compatibility level.
  • If recently upgraded, test whether setting compatibility level back temporarily (e.g., ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 160;) isolates the issue, then re-apply SQL Server 2025’s level after fixing queries.

Alternative or Verification Steps

  • Re-run the corrected query in SQL Server Management Studio (SSMS) or Azure Data Studio and confirm execution completes without Error 1069, then check the Messages tab for a clean “Command completed successfully.”
  • If the error persists in a third-party application, enable SQL trace logging via SQL Server Configuration Manager > MSSQLSERVER Properties > Startup Parameters to capture the exact malformed query string before it reaches the engine.

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

Troubleshooting Guide: SQL Server Error 1067 – “SET SHOWPLAN statements must be the only statements in the batch”

Why This Error Happens

This error occurs when a client application or script attempts to execute a SET SHOWPLAN_ALL, SET SHOWPLAN_TEXT, or SET SHOWPLAN_XML statement in the same batch as other T-SQL commands. SQL Server 2025 strictly enforces that SHOWPLAN directives must be isolated because they alter the connection’s execution mode rather than executing queries directly. This commonly surfaces when tools like SSMS, third-party BI connectors, or ORM-generated queries bundle diagnostic commands with application logic in a single GO batch.

Step-by-Step Resolution Guide

Step 1: Isolate the SHOWPLAN Statement

  • Open the offending script in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Ensure the SET SHOWPLAN_XML ON; (or SHOWPLAN_ALL / SHOWPLAN_TEXT) line is placed in its own batch, separated by a GO statement from any subsequent queries.
  • Example correct structure:
  SET SHOWPLAN_XML ON;
  GO
  SELECT * FROM dbo.YourTable;
  GO
  SET SHOWPLAN_XML OFF;
  GO

Step 2: Check the Application/Driver Configuration

  • If the error originates from an application (not manual SSMS execution), inspect the connection string or ORM configuration (e.g., Entity Framework, JDBC, ODBC) for settings that auto-inject SHOWPLAN commands alongside queries.
  • On Windows Server 2025, verify the driver version under C:\Program Files\Microsoft SQL Server\Client SDK\ and update to the latest ODBC 18+ driver, as older drivers sometimes mishandle batch separation.

Step 3: Review Dynamic SQL and Stored Procedures

  • Search stored procedures or dynamic SQL blocks using:
  SELECT OBJECT_NAME(object_id), definition
  FROM sys.sql_modules
  WHERE definition LIKE '%SHOWPLAN%';
  • Refactor any procedure that concatenates SET SHOWPLAN with other executable statements into separate EXEC calls.

Step 4: Restart the Query Session

  • Close and reopen the query window in SSMS to clear any residual session-level SET options.
  • Re-run the corrected script to confirm the batch separation resolves the parser-level validation.

Alternative or Verification Steps

  • Verify the fix by running the isolated SET SHOWPLAN_XML ON; batch independently and confirming the execution plan output displays without triggering Error 1067.
  • If the issue persists in automated jobs, check SQL Server Agent job steps under SQL Server Management Studio → SQL Server Agent → Jobs → Step Properties to ensure SHOWPLAN commands aren’t concatenated with task-specific queries in the same step.

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

Troubleshooting Guide: SQL Server Error 1066 — Obsolete Option Warning

Why This Error Happens

This warning occurs when T-SQL scripts, stored procedures, or application code contain syntax options that were deprecated in earlier SQL Server versions and have since been fully retired in SQL Server 2025’s query processor. The parser still recognizes these legacy keywords (such as old SET options, deprecated query hints, or legacy index creation syntax) for backward compatibility purposes, but silently ignores them during execution since they no longer map to any functional behavior. This typically surfaces after migrating databases or scripts from older SQL Server instances (2016/2017) or restoring compatibility-level databases onto a modern engine without updating the underlying code.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Option Triggering the Warning

  • Open SQL Server Management Studio (SSMS) and re-run the script with “Include Actual Execution Plan” disabled to isolate parser-only warnings.
  • Note the exact line number (%d) and option name (%ls) reported in the Messages tab.
  • Cross-reference the flagged option against Microsoft’s “Deprecated Database Engine Features” documentation for SQL Server 2025.

Step 2: Locate and Edit the Source Script or Object Definition

  • Use sp_helptext 'YourProcedureName' to extract the full definition of the affected stored procedure, trigger, or function.
  • Search the codebase (including .sql deployment files in your repo or C:\Scripts\SQLDeploy\) for the obsolete keyword using a text search tool like grep or VS Code’s workspace search.
  • Remove or replace the obsolete option — for example, strip out legacy SET ANSI_NULLS OFF toggles or deprecated WITH RECOMPILE syntax variants no longer supported.

Step 3: Update Database Compatibility Level and Rebuild Affected Objects

  • Check current compatibility level: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • Update it if needed: ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • Drop and recreate any stored procedures or views that contained the obsolete syntax using CREATE OR ALTER to ensure the new definition is cleanly compiled.

Step 4: Clear Cached Execution Plans and Recompile

  • Run DBCC FREEPROCCACHE on the affected database (in a maintenance window, not production hours) to force SQL Server to recompile all plans.
  • Alternatively, target a single object: EXEC sp_recompile 'YourProcedureName';

Alternative or Verification Steps

  • Re-execute the original script or stored procedure call and confirm the Messages pane in SSMS no longer returns the “Line %d: option ‘%ls’ is obsolete” warning.
  • If the warning persists across multiple objects, run the SQL Server 2025 Upgrade Advisor tool against the full database to generate a consolidated report of all remaining deprecated syntax instances for batch remediation.

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

Troubleshooting Guide: SQL Server Error 1065 — NOLOCK/READUNCOMMITTED Lock Hints Not Allowed on INSERT Target Tables

Why This Error Happens

This error occurs because SQL Server 2025 explicitly disallows the NOLOCK or READUNCOMMITTED lock hints on the target table of an INSERT statement, since these hints are designed for read operations and have no valid semantic meaning when writing data. The query optimizer rejects the statement at parse time because applying a dirty-read isolation hint to a table being modified would create undefined locking behavior. This typically surfaces after application code, ORM-generated queries, or migrated T-SQL scripts carry over NOLOCK hints from SELECT statements into INSERT ... SELECT patterns where the hint is mistakenly attached to the insert target rather than the source table.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing statement using SQL Server Profiler, Extended Events, or the application’s query log.
  • Look specifically for syntax like INSERT INTO TableName WITH (NOLOCK) or INSERT INTO TableName WITH (READUNCOMMITTED).
  • Check stored procedures, views, and dynamically generated SQL from ORMs (Entity Framework, Hibernate, etc.) that may auto-append hints.

Step 2: Remove the Lock Hint from the Target Table

  • Edit the query so the WITH (NOLOCK) or WITH (READUNCOMMITTED) clause is deleted from the INSERT INTO clause entirely.
  • If the hint was intended for a source table in an INSERT ... SELECT pattern, relocate it to the SELECT portion instead:
  • Correct: INSERT INTO TargetTable SELECT * FROM SourceTable WITH (NOLOCK)
  • Incorrect: INSERT INTO TargetTable WITH (NOLOCK) SELECT * FROM SourceTable

Step 3: Update Stored Procedures and Deployment Scripts

  • Search all .sql deployment files and stored procedure definitions using SSMS “Find in Files” or sys.sql_modules queries for NOLOCK near INSERT INTO.
  • Run this diagnostic query to locate affected objects:
  • SELECT OBJECT_NAME(object_id), definition FROM sys.sql_modules WHERE definition LIKE '%INSERT%NOLOCK%'
  • Redeploy corrected procedures to all environments (Dev, QA, Production) to prevent recurrence.

Step 4: Adjust Application-Level Query Generation

  • If using an ORM or query builder, check configuration settings or interceptors that globally append NOLOCK hints to all table references.
  • Add exclusion logic so hints are only applied to SELECT statements, not INSERT targets.
  • Restart the application pool or service in IIS/Windows Server 2025 after configuration changes to ensure cached query plans are cleared.

Step 5: Clear Cached Execution Plans (If Needed)

  • Run DBCC FREEPROCCACHE on the affected database to remove any cached invalid plans tied to the old query text.
  • Confirm no other sessions are relying on the cached plan before clearing it in a production environment.

Alternative or Verification Steps

  • Re-run the corrected INSERT statement in SSMS or Azure Data Studio and confirm it executes without raising Error 1065.
  • As an alternative to NOLOCK for reducing contention on source tables, consider using READ COMMITTED SNAPSHOT isolation level at the database level (ALTER DATABASE [YourDB] SET READ_COMMITTED_SNAPSHOT ON) instead of hint-based dirty reads.

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

Why This Error Happens

Error 1064 occurs when a T-SQL statement (typically CREATE DATABASE, ALTER DATABASE, or CREATE TABLE/CREATE INDEX with filestream/partitioning options) attempts to assign a LOG ON clause to a filegroup instead of directly to a physical log file definition. SQL Server strictly separates data storage (filegroups, which hold .mdf/.ndf files) from the transaction log (which uses .ldf files and has no filegroup concept), so mixing the two syntaxes triggers this parser-level validation failure. This is almost always caused by a scripting error, a migrated/legacy script from another RDBMS, or a copy-paste mistake in a DDL template.

Step-by-Step Resolution Guide

Step 1: Review the Offending T-SQL Script

  • Open the script that generated Error 1064 in SSMS (SQL Server Management Studio 21 or later, compatible with SQL Server 2025).
  • Locate the LOG ON clause and check whether it references a FILEGROUP keyword or a named filegroup (e.g., LOG ON [PRIMARY] or LOG ON [FG_LOGS]).
  • Confirm the exact line number from the error message in the Messages pane.

Step 2: Correct the Syntax to Separate Data and Log Definitions

  • Rewrite the LOG ON clause to use only (NAME = ..., FILENAME = ...) pairs, without any FILEGROUP reference.
  • Example corrected syntax:
  CREATE DATABASE SalesDB
  ON PRIMARY
  (NAME = SalesDB_Data, FILENAME = 'C:\SQLData\SalesDB.mdf')
  LOG ON
  (NAME = SalesDB_Log, FILENAME = 'C:\SQLData\SalesDB_log.ldf');
  • Ensure the FILEGROUP keyword appears only in the ON clause (for data files), never in LOG ON.

Step 3: Validate File Paths and Permissions on Windows Server 2025 / Windows 11

  • Confirm the target directory (e.g., C:\SQLData\) exists and the SQL Server service account has Write/Modify NTFS permissions via Properties > Security.
  • Check for path conflicts using PowerShell: Test-Path "C:\SQLData\SalesDB_log.ldf".
  • Re-run the corrected script in a new query window.

Step 4: Check for Legacy or Migrated Scripts

  • If the script was imported from SQL Server 2017/2019 or another platform, scan for deprecated multi-filegroup log syntax using Ctrl+Shift+F (Find in Files) in SSMS across the project folder.
  • Update any automation templates (PowerShell DSC, Azure Data Studio notebooks, or dbatools scripts) that may still reference the invalid pattern.

Alternative or Verification Steps

  • Verify the fix by running SELECT name, type_desc, physical_name FROM sys.master_files WHERE database_id = DB_ID('SalesDB'); — the log file should show type_desc = 'LOG' with no filegroup association.
  • If the error persists on ALTER DATABASE, drop and recreate the log file definition using ALTER DATABASE ... REMOVE FILE followed by ALTER DATABASE ... ADD LOG FILE instead of modifying it in place.

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

Troubleshooting Guide: Error 1063 – Filegroup Cannot Be Added Using ALTER DATABASE ADD FILE

Why This Error Happens

Error 1063 occurs when a T-SQL statement attempts to add a new filegroup using the ALTER DATABASE <db> ADD FILE syntax without first declaring the filegroup itself. SQL Server 2025 requires a strict two-step process: the filegroup container must exist before a file can be assigned to it. This is typically caused by migrated scripts, legacy automation tools, or manually written DDL that conflates the ADD FILE and ADD FILEGROUP clauses into a single incorrect statement.

Step-by-Step Resolution Guide

Step 1: Identify the Faulty T-SQL Statement

  • Locate the exact script or job that triggered Error 1063 (check SQL Server Agent job history or SSMS query window).
  • Look for syntax similar to this incorrect pattern:
  ALTER DATABASE MyDatabase 
  ADD FILE (NAME = 'MyFile', FILENAME = 'C:\Data\MyFile.ndf') 
  TO FILEGROUP MyNewFileGroup;
  • Confirm that MyNewFileGroup does not already exist by running:
  SELECT name FROM sys.filegroups WHERE name = 'MyNewFileGroup';

Step 2: Create the Filegroup Before Adding Files

  • Execute the ADD FILEGROUP command first to register the logical filegroup name in the database.
  ALTER DATABASE MyDatabase 
  ADD FILEGROUP MyNewFileGroup;
  • Verify the filegroup path is accessible on Windows Server 2025 (ensure the SQL Server service account has write permissions to the target directory, e.g., D:\SQLData\).

Step 3: Add the File to the Newly Created Filegroup

  • Once the filegroup exists, run the ADD FILE command to associate a physical .ndf file with it.
  ALTER DATABASE MyDatabase 
  ADD FILE (NAME = 'MyFile', FILENAME = 'D:\SQLData\MyFile.ndf', SIZE = 5MB) 
  TO FILEGROUP MyNewFileGroup;
  • Ensure the file path does not already exist to avoid Error 5170 (file already exists).

Step 4: Update Automation Scripts and Deployment Pipelines

  • If the error originated from an automated deployment (DACPAC, SSDT, or PowerShell script), update the source templates to always separate filegroup creation from file addition.
  • Check DevOps/CI pipelines for hardcoded legacy scripts that may need refactoring for SQL Server 2025 compliance.

Alternative or Verification Steps

  • Run SELECT name, type_desc FROM sys.filegroups; to confirm the new filegroup appears in the database metadata before re-attempting the file addition.
  • If the error persists despite correct syntax, check for a naming collision with an existing system filegroup (e.g., PRIMARY) using sp_helpfilegroup, as SQL Server will reject duplicate names even if the error message does not explicitly state this.

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

Troubleshooting Guide: SQL Server Error 1062 – TOP N WITH TIES Without ORDER BY

Why This Error Happens

This error occurs because the TOP N WITH TIES clause is syntactically dependent on an ORDER BY clause to determine which rows are considered “tied” with the last row in the result set. SQL Server’s query parser rejects the statement during compilation because, without an explicit sort order, there is no deterministic way to evaluate tie conditions. This is typically caused by a coding oversight, a migrated script from an older application, or a dynamically generated SQL statement that strips out the ORDER BY clause.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Query

  • Identify the exact T-SQL statement throwing Error 1062 using SQL Server Management Studio (SSMS) or the application’s query log.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER on Windows Server 2025 for the full stack trace containing the query context.
  • Search your codebase or stored procedures for the string WITH TIES to find all instances that may be affected.

Step 2: Add a Valid ORDER BY Clause

  • Modify the query to include an ORDER BY clause that logically defines the sort order for the “tie” comparison.
  • Example fix:
  SELECT TOP 5 WITH TIES ProductID, Sales
  FROM dbo.SalesData
  ORDER BY Sales DESC;
  • Ensure the column used in ORDER BY is indexed for performance, especially on large tables in SQL Server 2025.

Step 3: Check Dynamic SQL and ORM Frameworks

  • If the query is generated by an ORM (e.g., Entity Framework, Dapper) or built via dynamic SQL in a stored procedure, verify that the query-building logic is not accidentally omitting the ORDER BY clause during string concatenation.
  • Inspect any sp_executesql calls or application-layer query builders for conditional logic that might strip sorting parameters.
  • Rebuild and redeploy the stored procedure or application binary after the fix:
  EXEC sp_recompile 'dbo.YourStoredProcedureName';

Step 4: Validate Compatibility Level Settings

  • Confirm the database compatibility level is appropriately set for SQL Server 2025 features by running:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If necessary, update it to the latest level to ensure query parsing aligns with current T-SQL syntax rules:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Re-run the corrected query in SSMS or Azure Data Studio and confirm it executes without throwing Error 1062, then check the Messages tab for a clean “Query executed successfully” result.
  • If the error persists in a complex view or nested subquery, isolate the TOP...WITH TIES logic into a separate Common Table Expression (CTE) with its own explicit ORDER BY to ensure the parser correctly scopes the sort order.

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

Troubleshooting Guide: SQL Server Error 1061 — “The text/ntext/image constants are not yet implemented”

Why This Error Happens

This error occurs because SQL Server’s query engine encounters a direct literal constant assignment for deprecated text, ntext, or image data types within a T-SQL statement, which the parser cannot resolve without an intermediate conversion step. It is typically triggered by legacy scripts, linked server queries, or ORM-generated SQL that was written for older SQL Server versions and never migrated to use varchar(max), nvarchar(max), or varbinary(max). Since Microsoft SQL Server 2025 continues to phase out backward compatibility shims for these deprecated types, the underlying execution plan generator rejects the raw constant before it ever reaches the storage engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and reproduce the error by running the query from the Activity Monitor or Extended Events trace.
  • Check the query plan cache using:
  SELECT text, query_plan FROM sys.dm_exec_cached_plans
  CROSS APPLY sys.dm_exec_sql_text(plan_handle)
  WHERE text LIKE '%text%' OR text LIKE '%ntext%' OR text LIKE '%image%';
  • Note any INSERT, UPDATE, or WHERE clauses that assign a direct string/binary literal to a text, ntext, or image column.

Step 2: Convert the Data Type in the Script

  • Replace all instances of text with varchar(max), ntext with nvarchar(max), and image with varbinary(max) in the affected stored procedures or application code.
  • Example fix:
  -- Before (fails with Error 1061)
  UPDATE dbo.Documents SET Content = 'Sample Text' WHERE DocID = 5;

  -- After
  ALTER TABLE dbo.Documents ALTER COLUMN Content varchar(max);
  UPDATE dbo.Documents SET Content = CAST('Sample Text' AS varchar(max)) WHERE DocID = 5;
  • Update any linked application connection strings or Entity Framework/Dapper models referencing the legacy types.

Step 3: Update Compatibility Level and Server Configuration

  • In SSMS, right-click the database → Properties → Options, and set the Compatibility Level to SQL Server 2025 (170).
  • Alternatively, run:
  ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025/Windows 11, or run:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Re-Deploy Affected Stored Procedures and Triggers

  • Script out all stored procedures, functions, and triggers referencing the old data types using the Generate Scripts wizard in SSMS.
  • Search-and-replace deprecated type declarations in the generated .sql file, then re-execute the script against the target database.
  • Validate that no compile-time warnings remain by checking Messages tab output after redeployment.

Alternative or Verification Steps

  • Run the original failing query again and confirm Error 1061 no longer appears in the SQL Server Error Log (Management → SQL Server Logs in SSMS).
  • If the error persists, use sp_help 'TableName' to confirm no residual columns still use text, ntext, or image, and check linked server drivers (OLE DB/ODBC) for outdated type mappings that may still inject legacy literals.

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

Troubleshooting Guide: Error 1060 – “The number of rows provided for a TOP or FETCH clauses row count parameter must be an integer”

Why This Error Happens

This error occurs when a T-SQL query uses a TOP (n) or OFFSET...FETCH NEXT n ROWS clause where the value n is a non-integer data type, such as DECIMAL, FLOAT, or a VARCHAR string that cannot be implicitly converted. SQL Server 2025’s parser strictly validates that the row count expression resolves to an exact integer type (INT, BIGINT, SMALLINT, or TINYINT) before execution begins. This commonly surfaces after migrating legacy queries, using calculated variables, or passing parameters from an application layer (like a .NET or Java app) that defaults to a different numeric type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log or Windows Event Viewer (Event ID 1060) to locate the exact timestamp and session ID of the failure.
  • Run SELECT * FROM sys.dm_exec_requests WHERE session_id = <id> to capture the sql_handle if the session is still active.
  • Review the application’s source code or stored procedure definition for TOP or FETCH NEXT usage.

Step 2: Correct the Variable Declaration

  • Locate the variable used in the clause (e.g., DECLARE @RowCount DECIMAL(10,2) = 10.00;).
  • Change the declaration to an integer type: DECLARE @RowCount INT = 10;.
  • If the value originates from a calculation (e.g., @RowCount = @Total / @Pages), wrap it explicitly: SET @RowCount = CAST(@Total / @Pages AS INT);.

Step 3: Fix Application-Layer Parameter Binding

  • If the query is parameterized from an external application (C#, Python, PowerShell), verify the parameter type being passed to the TOP (@p1) placeholder.
  • In .NET, ensure the SqlParameter is explicitly set to SqlDbType.Int rather than Decimal or Float.
  • Example fix: cmd.Parameters.Add("@RowCount", SqlDbType.Int).Value = 10;

Step 4: Patch and Restart the SQL Service

  • Ensure SQL Server 2025 is updated to the latest Cumulative Update (CU) via Windows Update or the SQL Server Update Center, as early builds had stricter type-coercion bugs with linked server queries.
  • Open Services.msc on Windows Server 2025 or Windows 11, locate SQL Server (MSSQLSERVER), and restart the service to clear any cached execution plans.
  • Alternatively, run DBCC FREEPROCCACHE; to purge old plans without a full restart.

Alternative or Verification Steps

  • Re-run the corrected query in SQL Server Management Studio (SSMS) and confirm it executes without raising Error 1060; check Messages tab for a clean completion.
  • If the error persists with dynamic SQL, wrap the row count variable in an explicit CONVERT(INT, @Variable) directly inside the TOP() or FETCH NEXT syntax as a fallback safeguard.

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

Troubleshooting Guide: SQL Server Error 1059 — Cannot Set or Reset ‘PARSEONLY’ Option Within a Procedure or Function

Why This Error Happens

Error 1059 occurs because the SET PARSEONLY option is explicitly disallowed inside stored procedures, functions, and triggers by SQL Server’s engine design. This restriction exists because PARSEONLY only validates T-SQL syntax without executing it, which conflicts with the compiled execution plan model used by precompiled database objects. In most cases, this error surfaces when a legacy script or migrated codebase (often ported from an older SQL Server version to SQL Server 2025) attempts to toggle this session-level setting inside a procedural body instead of at the connection/session level.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Code Block

  • Open the stored procedure, function, or trigger definition using SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Search the object definition for SET PARSEONLY ON or SET PARSEONLY OFF statements:
  sp_helptext 'YourProcedureName';
  • Confirm the statement is located inside the BEGIN...END block of the procedure/function rather than in a standalone batch.

Step 2: Remove the SET PARSEONLY Statement from the Procedural Body

  • Edit the procedure using ALTER PROCEDURE or ALTER FUNCTION and delete the SET PARSEONLY line(s) entirely.
  • If the intent was to validate syntax only, move that logic to a separate ad-hoc script executed outside the procedure, such as:
  SET PARSEONLY ON;
  GO
  -- validation query here
  GO
  SET PARSEONLY OFF;
  GO
  • Save and redeploy the corrected object using ALTER PROCEDURE [SchemaName].[ProcedureName] AS ....

Step 3: Check for Compatibility Level Conflicts

  • Run the following to check the database compatibility level, since legacy scripts migrated from SQL Server 2014/2016 may reference deprecated session settings:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If necessary, update compatibility level to 170 (SQL Server 2025) using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-test the procedure execution after updating compatibility settings.

Step 4: Clear Cached Execution Plans (Windows Server 2025 / Windows 11 Hosts)

  • On the SQL Server host, open an elevated PowerShell or Command Prompt session.
  • Clear the procedure cache to eliminate stale compiled plans that may still reference the invalid SET PARSEONLY call:
  DBCC FREEPROCCACHE;
  • Restart the SQL Server service via Services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Verify the fix by recompiling and executing the procedure manually: EXEC YourProcedureName; — it should run without returning Error 1059.
  • If the error persists, use SQL Server Profiler or Extended Events to trace the exact batch/line number triggering the error, as nested or dynamically generated SQL (via EXEC or sp_executesql) may be hiding a secondary SET PARSEONLY call inside dynamic strings.

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

Troubleshooting Guide: SQL Server Error 1058 – Conflicting Cursor Read-Only Specification

Why This Error Happens

This error occurs because the Transact-SQL cursor declaration syntax contains redundant, conflicting keywords specifying the same read-only behavior twice. Specifically, the DECLARE CURSOR statement includes both the ISO-standard FOR READ ONLY clause and the SQL Server extension READ_ONLY keyword within the same statement, which the parser rejects as contradictory. This is purely a T-SQL syntax authoring issue—usually introduced by copy-pasted code, ORM-generated scripts, or migration scripts—rather than a server configuration, permissions, or port-related problem.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Cursor Declaration

  • Open the stored procedure, script, or application code that triggered Error 1058 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Search for DECLARE statements containing the word CURSOR using Ctrl+F.
  • Identify lines that include both READ_ONLY and FOR READ ONLY together, for example:
  DECLARE cur_data CURSOR READ_ONLY FOR SELECT * FROM Sales.Orders FOR READ ONLY;

Step 2: Remove the Duplicate Keyword

  • Decide which syntax style to keep—typically READ_ONLY (T-SQL extended cursor syntax) is preferred for SQL Server-specific code.
  • Delete the redundant FOR READ ONLY clause if using READ_ONLY, or vice versa.
  • Corrected example:
  DECLARE cur_data CURSOR READ_ONLY FOR SELECT * FROM Sales.Orders;

Step 3: Validate Syntax Using SET PARSEONLY

  • Run the corrected script in SSMS with SET PARSEONLY ON; before execution to confirm the T-SQL compiles without error.
  • Toggle SET PARSEONLY OFF; afterward to allow normal execution.
  • Check the Messages tab for confirmation that no syntax errors (including Error 1058) appear.

Step 4: Re-deploy and Test the Stored Procedure

  • If the cursor is inside a stored procedure or function, use ALTER PROCEDURE or ALTER FUNCTION to redeploy the corrected object.
  • Execute the procedure manually with sample parameters to confirm the cursor opens, fetches, and closes without triggering Error 1058.
  • Check SQL Server Error Logs via EXEC sp_readerrorlog 0, 1, 'Error: 1058' to confirm the error no longer appears after redeployment.

Alternative or Verification Steps

  • Run SELECT * FROM sys.dm_exec_cursors(0); after execution to confirm the cursor was created successfully and is using the expected read-only cursor type.
  • If the error persists across multiple scripts, use a global search-and-replace (via SSMS “Find in Files” or PowerShell Select-String) across your script repository to catch all instances of READ_ONLY.*FOR READ ONLY patterns in one pass.

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

Why This Error Happens

Error 1057 occurs because SQL Server’s IDENTITY() function has a structural limitation: it cannot be used in a SELECT INTO statement when that statement includes a UNION, UNION ALL, INTERSECT, or EXCEPT operator. This happens because SQL Server cannot deterministically generate and seed a single identity column across multiple combined result sets at the same time. The engine requires a single, unambiguous source table definition to properly allocate identity seed and increment values, which a UNION query inherently violates.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact SELECT INTO statement in your script or stored procedure that references IDENTITY(data_type, seed, increment).
  • Check if the query contains a UNION, UNION ALL, INTERSECT, or EXCEPT clause combined with the IDENTITY function in the column list.
  • Use SQL Server Management Studio (SSMS) 21 query history or the Activity Monitor to pinpoint the exact line number flagged by Error 1057.

Step 2: Restructure the Query Using a Temporary Table

  • Rewrite the logic by first creating a standard table using CREATE TABLE with an explicit IDENTITY(1,1) column definition.
  • Run the UNION query as a standard INSERT INTO... SELECT statement targeting the newly created table, rather than using SELECT INTO directly.
  • Example syntax:
  CREATE TABLE #TempResults (ID INT IDENTITY(1,1), ColumnA VARCHAR(50));
  INSERT INTO #TempResults (ColumnA)
  SELECT ColumnA FROM TableA
  UNION ALL
  SELECT ColumnA FROM TableB;

Step 3: Isolate the UNION Logic into a Subquery

  • If restructuring the table is not feasible, wrap the UNION statement inside a derived table or a Common Table Expression (CTE).
  • Apply the IDENTITY function or ROW_NUMBER() function to the outer query selecting from that derived table, rather than applying it directly to the raw union results.
  • Ensure the SELECT INTO clause targets the outer query result, not the inner combined dataset.

Step 4: Validate Database Compatibility Level

  • Open SSMS and right-click the target database, navigating to Properties > Options.
  • Confirm the Compatibility Level is set to SQL Server 2025 (170) to ensure the query optimizer handles row-generation logic consistently with the new engine updates.
  • Restart the SQL Server Engine service via services.msc on Windows Server 2025 if you change this setting to clear the cached execution plans.

Alternative or Verification Steps

  • To verify the fix, execute the modified script in a test environment and check the Messages tab in SSMS for a “Command(s) completed successfully” confirmation instead of Error 1057.
  • As an alternative to IDENTITY(), use the ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) window function directly within the SELECT INTO statement; this bypasses the identity restriction entirely and works natively with UNION operators.

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

Troubleshooting Guide: SQL Server Error 1056 – Select List Element Limit Exceeded

Why This Error Happens

This error occurs when a single SELECT statement references more columns or expressions than the SQL Server query engine is architecturally permitted to process, which is capped at 4,096 elements per select list. It is typically triggered by auto-generated queries, ORM tools (like Entity Framework or Hibernate), or dynamically constructed SQL that pivots, unions, or joins excessively wide datasets. The root cause is almost always a query design flaw rather than a server configuration or permissions issue, as this limit is a hard-coded constraint within the SQL Server relational engine.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log via SSMS (Management > SQL Server Logs) or Event Viewer on Windows Server 2025 to capture the exact query text or stored procedure name throwing Error 1056.
  • If the query is generated dynamically (e.g., via PIVOT or an ORM), enable SQL Server Profiler or Extended Events to trace the exact batch text being sent to the server.
  • Look specifically for wildcard expansions (SELECT *) combined with wide JOIN operations across multiple large tables.

Step 2: Refactor the Select List

  • Break the single massive query into smaller batches using temporary tables (#TempTable) or table variables to stage intermediate results.
  • Replace SELECT * with explicit, limited column lists to ensure you are only pulling necessary data points.
  • If the query involves a PIVOT or UNPIVOT operation creating excessive columns, consider restructuring the output using an “unpivoted” (long format) result set instead of a wide (short format) one.

Step 3: Adjust ORM or Application Configuration

  • If using Entity Framework Core or Hibernate on a .NET application running on Windows 11/Server 2025, check the DbContext configuration for excessive “Eager Loading” (.Include() chains) that cause the ORM to merge too many columns into one SQL projection.
  • Modify the application logic to use “Split Queries” (available in EF Core via .AsSplitQuery()) to force the ORM to generate multiple smaller SELECT statements instead of one large one.
  • Restart the IIS Application Pool or the Windows Service hosting the application to ensure the updated query logic takes effect: iisreset or Restart-Service -Name "YourServiceName".

Step 4: Validate Server-Side Views or Procedures

  • If the error originates from a Stored Procedure, open it in SSMS and check for recursive UNION ALL statements that might be compounding the column count.
  • Update the procedure using ALTER PROCEDURE to consolidate redundant selections before deploying the fix to production.

Alternative or Verification Steps

  • Verification: Re-run the modified query directly in SSMS connected to your Windows Server 2025 instance; a successful execution without Error 1056 confirms the column count is now under the 4,096 limit.
  • Alternative: If refactoring the query is not immediately feasible, use sp_executesql to break the logic into sequential batches that aggregate results into a temporary table, effectively bypassing the single-statement limit.

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

Troubleshooting Guide: SQL Server Error 1055 – Invalid Object Name (NULL or Invalid Unicode Character)

Why This Error Happens

This error occurs when SQL Server 2025 receives a Data Definition Language (DDL) statement containing an object name (table, column, or database) with an embedded NULL character (\x00) or an unpaired/invalid Unicode surrogate character. This is typically caused by corrupted client-side encoding during string concatenation, a faulty ORM mapping layer generating malformed T-SQL, or copy-pasted scripts containing hidden control characters. Because SQL Server 2025 enforces stricter UTF-8 and Unicode validation at the parser level than previous versions, strings that were previously tolerated may now trigger a hard failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Query

  • Check the SQL Server Error Log for the exact query batch associated with Error 1055.
  • Open SQL Server Management Studio (SSMS) and re-run the failing script in a new query window with Query > SQLCMD Mode disabled.
  • Use SELECT OBJECT_DEFINITION or review the application’s generated SQL (via SQL Profiler or Extended Events) to isolate the exact string being passed.

Step 2: Scan and Clean the Input String

  • Export the suspect script to a plain text editor like VS Code or Notepad++.
  • Enable View > Render Whitespace and View > Control Characters to visually detect NULL bytes or stray Unicode markers (e.g., Zero Width Joiners, BOM markers at mid-string).
  • Run a PowerShell validation command to detect non-printable characters in the source .sql file:
  Get-Content "C:\Scripts\migration.sql" -Raw | Select-String "[\x00-\x1F]"
  • Remove any flagged characters and re-save the file using UTF-8 (without BOM) encoding.

Step 3: Validate Application Connection String Encoding

  • If the error originates from an application (not a manual script), check the connection string in web.config or appsettings.json for incorrect Charset or Encoding parameters.
  • Ensure the client driver (ODBC 18+, OLE DB, or Microsoft.Data.SqlClient) is updated to the latest version compatible with Windows Server 2025, as older drivers may mishandle UTF-16LE surrogate pairs.
  • Update NuGet/driver packages:
  Update-Package Microsoft.Data.SqlClient

Step 4: Rebuild the Query with Parameterization

  • Avoid direct string concatenation for dynamic SQL; replace it with parameterized queries using sp_executesql.
  • Example fix:
  EXEC sp_executesql N'CREATE TABLE [dbo].[@TableName] (...)', N'@TableName NVARCHAR(128)', @TableName = N'ValidName';
  • This prevents malformed Unicode injection from user input or dynamically generated object names.

Alternative or Verification Steps

  • Verify the Fix: Re-execute the corrected script in SSMS and confirm the object (table/column) is created successfully without Error 1055 appearing in the SQL Server Logs (Object Explorer > Management > SQL Server Logs).
  • Alternative Solution: If the issue persists in a legacy application, implement a server-side trigger or CHECK constraint using PATINDEX('%[^ -~]%', ColumnName) to reject NULL/invalid Unicode characters before they reach the DDL layer.

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

Troubleshooting Guide: Error 1054 — Syntax Not Allowed in Schema-Bound Objects

Why This Error Happens

This error occurs when a view, function, or stored procedure created with SCHEMABINDING uses a T-SQL construct that SQL Server 2025 does not permit in schema-bound definitions, such as non-deterministic functions, SELECT *, outer joins with certain syntax, or references to system functions like GETDATE(). SQL Server enforces stricter parsing rules for schema-bound objects because they must guarantee deterministic, reproducible results for indexing and dependency tracking. This typically surfaces after a migration, an upgrade from an older SQL Server version, or when a T-SQL script written for a different compatibility level is deployed against SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object and Statement

  • Open SQL Server Management Studio (SSMS) and locate the exact object named in the error message (view, function, or procedure).
  • Run the following to pull the object definition:
  SELECT OBJECT_DEFINITION(OBJECT_ID('YourSchema.YourObjectName'));
  • Review the definition for disallowed syntax: SELECT *, non-deterministic functions (GETDATE(), NEWID(), RAND()), or TOP without ORDER BY in certain contexts.

Step 2: Rewrite the Object to Remove Unsupported Syntax

  • Replace SELECT * with explicit column names.
  • Replace non-deterministic functions with deterministic equivalents, or remove SCHEMABINDING if determinism isn’t required.
  • Example fix:
  ALTER VIEW YourSchema.YourObjectName
  WITH SCHEMABINDING
  AS
  SELECT ColumnA, ColumnB
  FROM YourSchema.YourTable;
  • Save the corrected script to C:\SQLScripts\Fixes\ for version control before deploying.

Step 3: Validate Compatibility Level Settings

  • Check the database compatibility level, since newer syntax rules may be tied to it:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If the compatibility level is outdated (e.g., below 160 for SQL Server 2025 features), update it:
  ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • Re-run the object creation script to confirm the syntax now parses correctly under the current engine rules.

Step 4: Deploy and Refresh Dependent Objects

  • Execute sp_refreshsqlmodule 'YourSchema.YourObjectName'; to refresh metadata after altering the object.
  • If other views or indexes depend on this schema-bound object, drop and recreate them in the correct dependency order (dependents first, then the base object).

Alternative or Verification Steps

  • Verify the fix by querying sys.sql_modules to confirm the object compiles without error: SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('YourSchema.YourObjectName'); and attempt a test SELECT against it.
  • If rewriting the syntax isn’t feasible, remove the SCHEMABINDING option entirely as a fallback, understanding this sacrifices the ability to create indexed views or enforce base-table change protection.

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

Troubleshooting Guide: Error 1053 — “For DROP STATISTICS” Failure in SQL Server 2025

Why This Error Happens

Error 1053 occurs when SQL Server 2025 cannot complete a DROP STATISTICS operation because the specified statistics object is either tied to an index that cannot have its statistics dropped independently, or the referenced table/column no longer matches the statistics metadata stored in the system catalog. This frequently happens due to schema binding conflicts, orphaned statistics left behind after a failed index rebuild, or insufficient ALTER permissions on the parent table. In some cases, corrupted metadata in sys.stats following an abrupt service shutdown (logged under Windows Event ID 1053, indicating a service control timeout) can also trigger this failure.

Step-by-Step Resolution Guide

Step 1: Verify the Statistics Object and Its Dependency Type

  • Run SELECT * FROM sys.stats WHERE object_id = OBJECT_ID('YourTableName'); to confirm the statistics name and its auto_created or user_created flag.
  • Check if the statistic is auto-generated by an index — index-linked statistics cannot be dropped via DROP STATISTICS and require DROP INDEX instead.
  • Confirm there are no active transactions locking the object using sp_who2 or sys.dm_tran_locks.

Step 2: Check and Correct Permissions

  • Ensure your login has ALTER permission on the schema or table: GRANT ALTER ON OBJECT::YourTableName TO [YourUser];
  • Verify you’re not running the command under a restricted service account tied to the Windows Server 2025 SQL Server service.
  • Re-run the command using a sysadmin-level login to rule out permission scoping issues.

Step 3: Restart the SQL Server Service Cleanly

  • Open Services.msc on Windows Server 2025 / Windows 11 and locate SQL Server (MSSQLSERVER).
  • Right-click and select Restart; if the service hangs, check Event Viewer > Windows Logs > System for the corresponding Event ID 1053 timeout entry.
  • Increase the service control timeout via registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServicesPipeTimeout (set value in milliseconds, e.g., 60000) if the service consistently times out during stop/start operations.

Step 4: Rebuild Corrupted Statistics Metadata

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to detect catalog corruption.
  • If corruption is confirmed, use UPDATE STATISTICS YourTableName WITH FULLSCAN; to regenerate clean statistics before attempting the drop again.
  • As a last resort, script out the table, drop and recreate it, then reapply statistics manually.

Alternative or Verification Steps

  • After applying fixes, re-run DROP STATISTICS YourTableName.YourStatName; and confirm success with no error output.
  • If the issue persists, use sp_helpstats 'YourTableName'; to cross-check remaining statistics objects and ensure the target wasn’t already removed by a prior cascading DROP INDEX operation.

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

Troubleshooting Guide: SQL Server Error 1052 — “Conflicting %ls options”

Why This Error Happens

Error 1052 occurs when a T-SQL statement, command-line invocation, or configuration call includes two or more mutually exclusive options within the same command. This typically happens during CREATE/ALTER operations (such as index creation, database configuration, or backup commands) where options like ONLINE = ON and RESUMABLE = ON, or ENCRYPTION and COMPRESSION flags conflict with one another based on the edition or context. It can also surface when automated deployment scripts, ORM-generated SQL, or third-party tools pass redundant or legacy switches that Microsoft SQL Server 2025 no longer allows to coexist.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Conflicting Options

  • Open the full error message in SQL Server Management Studio (SSMS) or the SQL Server Error Log — the %ls placeholders will be populated with the actual option names (e.g., “ONLINE” and “RESUMABLE”).
  • Locate the failing statement using SQL Server Profiler, Extended Events, or by checking the application/job that submitted the command.
  • Cross-reference the options against the official syntax documentation for the specific command (e.g., CREATE INDEX, ALTER DATABASE, BACKUP DATABASE).

Step 2: Edit the Offending Script or Command

  • Open the script in SSMS or Azure Data Studio and locate the clause containing both conflicting keywords.
  • Remove or comment out one of the conflicting options — for example, change:
  CREATE INDEX IX_Test ON dbo.Orders(OrderID) WITH (ONLINE = ON, RESUMABLE = ON, MAXDOP = 1);

to:

  CREATE INDEX IX_Test ON dbo.Orders(OrderID) WITH (ONLINE = ON, MAXDOP = 1);
  • If the script is auto-generated (by an ORM, migration tool, or backup utility), check the tool’s configuration file or template for hardcoded default flags and disable the redundant one.

Step 3: Check Server and Database Configuration Defaults

  • Run SELECT * FROM sys.configurations WHERE name LIKE '%resumable%'; or equivalent to see if a server-level default is forcing an option that conflicts with your statement.
  • Inspect Database Scoped Configurations via SELECT * FROM sys.database_scoped_configurations; in SQL Server 2025 to ensure no conflicting session-level override is set.
  • Adjust using ALTER DATABASE SCOPED CONFIGURATION SET <OPTION> = OFF; if a scoped default is causing the clash.

Step 4: Re-run the Corrected Statement

  • Execute the modified script in a test/staging environment first.
  • Confirm the command completes without raising Error 1052.
  • If deploying via automation (DACPAC, Flyway, Liquibase, etc.), update the source migration file and redeploy through your pipeline rather than patching production directly.

Alternative or Verification Steps

  • Verify the fix by re-running the exact statement in SSMS and confirming a successful completion message (e.g., “Command(s) completed successfully”) with no Error 1052 in the Messages tab or Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • If the conflict persists and the source is unclear, strip the command down to its minimal required options, execute successfully, then reintroduce additional options one at a time to isolate the exact incompatible pair.

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

Why This Error Happens

This error occurs when a stored procedure definition declares a cursor-type parameter but omits the mandatory OUTPUT and VARYING keywords required by T-SQL syntax rules. SQL Server 2025 enforces strict parameter validation for cursor variables because cursors are reference types that must be passed back to the calling scope, not just passed in by value. This is typically a code-level syntax issue rather than a server configuration problem, often introduced during manual script edits, ORM-generated procedures, or migration from older T-SQL codebases that used deprecated or incomplete cursor syntax.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Stored Procedure

  • Open SQL Server Management Studio (SSMS) and connect to the instance throwing Error 1051.
  • Check the Messages tab for the exact procedure name referenced in the error output.
  • Run the following to pull the procedure definition for review:
EXEC sp_helptext 'YourProcedureName';

Step 2: Correct the Cursor Parameter Declaration

  • Locate the parameter declared with a CURSOR data type in the CREATE PROCEDURE or ALTER PROCEDURE statement.
  • Ensure it includes both OUTPUT and VARYING — SQL Server will reject the cursor parameter without both keywords.
  • Example of the corrected syntax:
CREATE PROCEDURE dbo.GetDataCursor
    @MyCursor CURSOR VARYING OUTPUT
AS
BEGIN
    SET @MyCursor = CURSOR FOR
        SELECT ColumnA, ColumnB FROM dbo.SourceTable;
    OPEN @MyCursor;
END

Step 3: Redeploy the Procedure

  • Drop and recreate the procedure (or use ALTER PROCEDURE) with the corrected cursor syntax.
  • Save the updated script to your source control repository (e.g., Git) to prevent regression on the next deployment.
  • Re-run the deployment pipeline or execute the script manually in SSMS against the target database.

Step 4: Update Calling Code

  • Check any client application code (C#, PowerShell, or other T-SQL callers) that invokes this procedure.
  • Ensure the calling script also declares the cursor variable with OUTPUT when executing the procedure:
DECLARE @ResultCursor CURSOR;
EXEC dbo.GetDataCursor @ResultCursor OUTPUT;
FETCH NEXT FROM @ResultCursor;

Alternative or Verification Steps

  • Verify the fix by executing the procedure directly in SSMS and confirming no Error 1051 appears in the Messages pane, then fetch a row from the cursor to confirm data returns correctly.
  • If modifying the cursor syntax isn’t feasible due to legacy dependencies, consider refactoring the procedure to return a standard result set (SELECT statement) or use a Table-Valued Parameter (TVP) instead of a cursor, which avoids this restriction entirely and is generally more performant in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 1050 — “This syntax is only allowed for parameterized queries”

Why This Error Happens

This error occurs when SQL Server 2025 parses a query containing dynamic syntax elements (such as certain hint placeholders, variable-length markers, or query parameter tokens like ? or @p) outside the context of a properly parameterized statement. It typically arises when an application or ORM sends a query using sp_executesql or prepared statement syntax but fails to supply the required parameter declarations, or when a query is manually constructed with placeholder syntax but executed as a plain batch via EXEC() instead of a parameterized call. This can also surface after upgrading to SQL Server 2025 if legacy client drivers (OLE DB, older ODBC versions) are incompatible with the updated query parser rules for parameterized execution plans.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Enable SQL Server Profiler or Extended Events to capture the exact statement text triggering Error 1050.
  • Look specifically for queries using ? placeholders, sp_executesql, or sp_prepare calls that are missing a matching parameter definition string.
  • Check the application’s connection string and query logs (e.g., in IIS or application server logs on Windows Server 2025) for the exact failing SQL text.

Step 2: Correct the Query Syntax

  • Rewrite the query to use sp_executesql correctly, ensuring the parameter definition matches the placeholders:
  EXEC sp_executesql N'SELECT * FROM Orders WHERE OrderID = @OrderID',
                      N'@OrderID INT', @OrderID = 1001;
  • Avoid mixing literal ? placeholders with direct EXEC() calls — ? syntax is only valid when passed through a parameterized API (ODBC/JDBC prepared statements), not raw T-SQL batches.
  • If using an ORM (Entity Framework, Hibernate, etc.), confirm that parameterization is enabled in the data access configuration rather than manually concatenating placeholder syntax.

Step 3: Update Client Drivers and Connection Settings

  • Navigate to Control Panel > ODBC Data Sources (64-bit) on Windows Server 2025 / Windows 11 and confirm the driver is “ODBC Driver 18 for SQL Server” or newer.
  • Update legacy OLE DB or ODBC drivers via the Microsoft Download Center, since older drivers do not support SQL Server 2025’s stricter parameterization parser.
  • In the connection string, ensure Parameterization=Forced or equivalent setting is not conflicting with manually embedded placeholder syntax.

Step 4: Review Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and run:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is below 170 (SQL Server 2025), update it:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Retest the failing query after the compatibility level change, as older compatibility modes handle parameter parsing differently.

Alternative or Verification Steps

  • Re-run the corrected query directly in SSMS using sp_executesql with explicit parameters to confirm Error 1050 no longer appears.
  • If the issue persists, temporarily set Parameterization to Simple at the database level (ALTER DATABASE ... SET PARAMETERIZATION SIMPLE;) as a workaround while auditing application code for hardcoded placeholder misuse.

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

Troubleshooting Guide: SQL Server Error 1048 — Conflicting Cursor Options

Why This Error Happens

Error 1048 occurs when a T-SQL DECLARE CURSOR statement specifies two or more cursor options that are mutually exclusive, such as combining FAST_FORWARD with SCROLL, or STATIC with DYNAMIC. SQL Server’s parser validates cursor attribute combinations at compile time, and since these options define conflicting behaviors for cursor positioning, concurrency, and membership, the engine cannot resolve them into a single valid cursor type. This is almost always a code-level issue in a stored procedure, application query, or ORM-generated script rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Cursor Declaration

  • Capture the exact query text using SQL Server Profiler, Extended Events, or the application error log (look for the %ls and %ls placeholders populated with actual option names like FORWARD_ONLY and SCROLL).
  • Search stored procedures and application code for DECLARE ... CURSOR FOR statements.
  • Run this query to locate recently modified procedures that may contain cursors:
SELECT OBJECT_NAME(object_id), modify_date 
FROM sys.sql_modules 
WHERE definition LIKE '%CURSOR%' 
ORDER BY modify_date DESC;

Step 2: Review and Correct Conflicting Options

  • Check for known incompatible pairs in the cursor declaration:
  • STATIC vs DYNAMIC vs KEYSET
  • FAST_FORWARD vs SCROLL (FASTFORWARD implies FORWARDONLY and READ_ONLY)
  • FORWARD_ONLY vs SCROLL
  • READ_ONLY vs FOR UPDATE
  • Rewrite the declaration using only one option from each conflicting category, for example:
DECLARE my_cursor CURSOR
FAST_FORWARD
FOR SELECT col1, col2 FROM dbo.MyTable;
  • If the application uses dynamic SQL or an ORM (Entity Framework, Dapper, etc.), inspect the generated SQL via SQL Server Profiler to confirm which options the ORM is injecting automatically.

Step 3: Deploy and Recompile Affected Objects

  • Save the corrected stored procedure or script.
  • On Windows Server 2025, open SQL Server Management Studio (SSMS) and execute the ALTER PROCEDURE statement, or redeploy via your CI/CD pipeline if using DACPAC/SSDT.
  • Force a recompilation to clear any cached invalid plan:
EXEC sp_recompile 'dbo.MyStoredProcedure';

Step 4: Clear Plan Cache if Error Persists

  • If the error references a plan that should have been corrected, flush the procedure cache for the specific database:
DBCC FREEPROCCACHE;
  • Use this cautiously in production as it will force recompilation of all cached plans, temporarily increasing CPU load.

Alternative or Verification Steps

  • Re-run the corrected stored procedure or application transaction and confirm Error 1048 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS) or Windows Event Viewer.
  • As an alternative, if the cursor logic is complex, consider replacing the cursor entirely with a set-based operation (e.g., MERGE, window functions, or a WHILE loop on a temp table) to eliminate the conflict permanently and improve performance.

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

Troubleshooting Guide: SQL Server Error 1049 — Mixing Old and New Cursor Syntax

Why This Error Happens

This error occurs when a single DECLARE CURSOR statement combines the legacy Transact-SQL cursor syntax (e.g., INSENSITIVE, SCROLL before the cursor name) with the newer ISO/ANSI-compliant syntax (e.g., LOCAL, FAST_FORWARD, SCROLL_LOCKS after the CURSOR keyword) in the same query. SQL Server’s parser cannot reconcile both styles simultaneously because they represent two distinct grammar definitions for cursor declaration. This typically stems from copy-pasted legacy code being merged with newer T-SQL templates, or from migration scripts that were only partially updated during an upgrade to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Cursor Declaration

  • Open the stored procedure, function, or script referenced in the error message and locate the exact DECLARE CURSOR statement causing the failure.
  • Use SQL Server Management Studio (SSMS) 21 or Azure Data Studio to run the script in isolation and capture the precise line number from the error output.
  • Check for a mix of keywords such as INSENSITIVE, SCROLL (old syntax) alongside LOCAL, GLOBAL, FORWARD_ONLY, STATIC, KEYSET, DYNAMIC, FAST_FORWARD, READ_ONLY, SCROLL_LOCKS, or OPTIMISTIC (new syntax) in the same declaration.

Step 2: Rewrite the Cursor Using a Single Syntax Standard

  • Choose either the old-style syntax: DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR FOR select_statement.
  • Or the new-style (ISO) syntax: DECLARE cursor_name CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL] [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] FOR select_statement.
  • Update the script so all cursor option keywords belong to only one of these two patterns—do not blend keywords from both lists.

Step 3: Validate Syntax Using SQL Server 2025 Compatibility Tools

  • Run the updated script against a compatibility level 170 database using sp_dbcmptlevel to confirm the new syntax parses correctly.
  • Use the Database Engine Tuning Advisor or SET PARSEONLY ON in SSMS to perform a dry-run syntax check without executing the full batch.
  • Search the codebase (via sys.sql_modules or source control) for other instances of the same anti-pattern, especially in migrated procedures from SQL Server 2014 or earlier.

Step 4: Deploy and Test the Corrected Script

  • Save the corrected stored procedure or script and redeploy it to the target database on Windows Server 2025.
  • Execute the procedure manually with test parameters to confirm Error 1049 no longer appears in the SSMS Messages tab or the SQL Server error log (Logs folder under the instance’s MSSQL directory).

Alternative or Verification Steps

  • Verify the fix by re-running the script and confirming successful execution with zero syntax errors; also check SQL Server Logs via SSMS Object Explorer > Management > SQL Server Logs for any recurrence of Error 1049.
  • As an alternative, use SQL Server’s built-in Database Compatibility Level Upgrade Advisor to batch-scan all stored procedures for deprecated or mixed cursor syntax before manually rewriting each one.

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

Troubleshooting Guide: SQL Server Error 1047 – Conflicting Locking Hints Specified

Why This Error Happens

Error 1047 occurs when a single T-SQL statement specifies two or more table locking hints that are logically incompatible with one another, such as combining NOLOCK with HOLDLOCK, or READUNCOMMITTED with SERIALIZABLE. SQL Server’s query parser detects these contradictory isolation-level instructions during the compilation phase and refuses to generate an execution plan. This is almost always caused by legacy code, ORM-generated queries, or copy-pasted query hints that were never validated against SQL Server 2025’s stricter hint-conflict checks.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Extended Events session for the exact statement text that triggered Error 1047.
  • Use SQL Server Management Studio (SSMS) 20 or Azure Data Studio connected to your instance and run:
  SELECT * FROM sys.dm_exec_query_stats
  CROSS APPLY sys.dm_exec_sql_text(sql_handle)
  WHERE text LIKE '%NOLOCK%' OR text LIKE '%HOLDLOCK%'
  • Note the table alias and hint combination causing the conflict.

Step 2: Review and Correct the Locking Hints

  • Open the stored procedure, view, or application query file (commonly found in deployment folders like C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Jobs\ or your application’s .sql migration scripts).
  • Remove mutually exclusive hints. Common invalid pairs to check for:
  • WITH (NOLOCK, HOLDLOCK) — invalid, choose one.
  • WITH (READUNCOMMITTED, REPEATABLEREAD) — invalid, choose one.
  • WITH (ROWLOCK, TABLOCK) combined with UPDLOCK, XLOCK in certain join contexts.
  • Replace with a single, intentional hint based on the actual isolation requirement (e.g., just WITH (NOLOCK) for dirty reads).

Step 3: Update Application or ORM-Generated Code

  • If the query originates from an ORM (Entity Framework, Dapper, NHibernate), inspect the generated SQL via logging/profiling.
  • Override the ORM’s default locking behavior in the data access layer configuration instead of injecting raw hint strings.
  • Redeploy the corrected stored procedures using:
  EXEC sp_recompile 'YourStoredProcedureName';

Step 4: Clear the Plan Cache and Test

  • After correcting the code, clear any cached invalid plans to force recompilation:
  DBCC FREEPROCCACHE;
  • Re-run the corrected query in a test environment (not production) to confirm it compiles without Error 1047.

Alternative or Verification Steps

  • Verify the fix by executing the corrected query directly in SSMS and confirming no error is thrown, then check sys.dm_exec_query_stats to ensure the plan compiled successfully.
  • If the error persists despite manual review, enable SET SHOWPLAN_TEXT ON before running the query to visually inspect the hint parsing order, which often reveals a nested hint inherited from a view or inline table-valued function.

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

Why This Error Happens

This error occurs because SQL Server 2025’s query parser has encountered a subquery in a location where the T-SQL syntax rules strictly require a single scalar value—such as inside a CHECK constraint, a computed column definition, a CASE expression branch, or as a default value. The engine cannot resolve a result set (multiple rows/columns) in these contexts because the execution plan compiler needs a fixed, singular value to bind to the expression at compile time. This is typically a query logic/syntax issue rather than a server configuration or permissions problem, though it can sometimes surface after a migration if deprecated syntax patterns were allowed in older compatibility levels but are now strictly enforced.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Location of the Subquery

  • Open SQL Server Management Studio (SSMS) 21 (compatible with SQL Server 2025) and locate the specific line number referenced in the error message details pane.
  • Check if the subquery resides inside a CASE WHEN, CHECK constraint, DEFAULT constraint, or a computed column definition.
  • Look specifically for patterns like WHERE ColumnA = (SELECT ColumnB, ColumnC FROM...) where multiple columns are being selected but only one is expected.

Step 2: Refactor the Query to Use Scalar-Safe Syntax

  • Rewrite the subquery to ensure it returns exactly one column and, ideally, one row (using TOP 1 with an ORDER BY if necessary).
  • Replace the subquery with a JOIN operation where possible, as joins are generally more performant and avoid scalar context restrictions entirely.
  • If the logic requires checking for existence, switch from IN (SELECT...) to EXISTS (SELECT 1 FROM...) if the context is a WHERE clause, or ensure you are not accidentally using a correlated subquery in a SELECT list expecting a single value.

Step 3: Verify Compatibility Level Settings

  • Run the following command to check the current compatibility level of the database, as SQL Server 2025 defaults to level 170 which has stricter parsing:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the query previously worked under an older SQL Server instance, ensure legacy “Allow subqueries” trace flags were not relied upon, as these are deprecated in the 2025 engine.
  • Update constraint definitions (like CHECK constraints) to use a User-Defined Function (UDF) wrapper if a complex scalar lookup is required instead of a direct inline subquery.

Step 4: Test the Isolated Query Block

  • Isolate the specific subquery snippet and run it independently in a new query window to confirm it returns a single scalar value (1 row, 1 column).
  • Use SELECT COUNT(*) on the subquery logic temporarily to ensure you aren’t accidentally fetching a result set exceeding one row.

Alternative or Verification Steps

  • Verification: Execute the modified stored procedure or query in SSMS; if the query compiles and returns a result grid without the red error text in the “Messages” tab, the fix is successful.
  • Alternative: If refactoring the subquery is too complex for the current context (e.g., inside a strict CHECK constraint), create a scalar-valued function (CREATE FUNCTION... RETURNS INT) that encapsulates the subquery logic and call the function instead of the raw subquery.

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

Troubleshooting Guide: SQL Server Error 1045 – “Aggregates Are Not Allowed in This Context”

Why This Error Happens

This error occurs when an aggregate function (such as SUM, COUNT, AVG, MIN, or MAX) is placed in a part of a T-SQL query where SQL Server’s query parser expects only a scalar expression, such as inside a WHERE clause, a JOIN ON condition, or a CHECK constraint. SQL Server 2025’s query optimizer evaluates these clauses before the grouping/aggregation phase of execution, so it has no row-set context in which to compute the aggregate at that stage. This is a query-logic issue rather than a server configuration, permissions, or corruption problem, meaning the root cause lives in the T-SQL syntax itself.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Clause in the Query

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact line referenced in the error output.
  • Check WHERE, ON (in JOIN), and CHECK constraint definitions specifically, since aggregates are not permitted in these locations.
  • Use SSMS > Query > Display Estimated Execution Plan to help pinpoint where the parser fails.

Step 2: Move the Aggregate to a Valid Clause

  • Replace a WHERE clause aggregate with a HAVING clause, since HAVING is designed to filter on aggregated results after GROUP BY is applied.
  • Example fix: change WHERE SUM(SalesAmount) > 1000 to GROUP BY CustomerID HAVING SUM(SalesAmount) > 1000.
  • If the aggregate is needed in a JOIN ON clause, pre-aggregate the data using a Common Table Expression (CTE) or subquery first, then join on the pre-computed scalar value.

Step 3: Refactor Using a CTE or Derived Table (If Needed in CHECK Constraints or Complex Joins)

  • Since CHECK constraints cannot reference aggregate functions at all, move that validation logic into a trigger (AFTER INSERT, UPDATE) instead.
  • For complex joins, wrap the aggregation logic in a CTE: WITH AggData AS (SELECT CustomerID, SUM(SalesAmount) AS TotalSales FROM Orders GROUP BY CustomerID) and then join the main query to AggData.
  • Save and re-run the modified query to confirm the parser no longer throws Error 1045.

Step 4: Validate Server-Side Compatibility Level

  • Confirm the database compatibility level is correctly set for SQL Server 2025 by running SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';.
  • If running in a legacy compatibility mode (e.g., migrated from SQL Server 2016/2019), update it using ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170; to ensure modern query parsing rules are applied consistently.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm it executes without throwing Error 1045, then check the results against expected aggregated values using a quick SELECT COUNT(*) sanity check.
  • If the error persists after refactoring, use sp_helptext on any referenced views or stored procedures to ensure a nested object isn’t also embedding an aggregate in an invalid clause.

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

Troubleshooting Guide: SQL Server Error 1044

Why This Error Happens

Error 1044 occurs because SQL Server maintains a shared namespace for certain object types within a schema, and a stored procedure cannot share the exact same name as an existing scalar or table-valued function within that same schema. This typically happens during database migrations, script deployments, or when a developer attempts to create a new object without verifying existing object names via sys.objects. The conflict is a naming resolution issue, not a permissions or corruption issue, and SQL Server throws this error to prevent ambiguous object calls.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Object

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check if the name already exists as a function:
SELECT name, type_desc FROM sys.objects WHERE name = 'YourProcedureName';
  • Confirm whether type_desc returns SQL_SCALAR_FUNCTION, SQL_TABLE_VALUED_FUNCTION, or SQL_STORED_PROCEDURE.

Step 2: Rename the New Stored Procedure

  • Modify your CREATE PROCEDURE script to use a unique, non-conflicting name.
  • Apply a naming convention prefix to avoid future collisions, such as usp_ for procedures and fn_ for functions.
CREATE PROCEDURE usp_GetCustomerData
AS
BEGIN
    SELECT * FROM Customers;
END

Step 3: Drop or Rename the Legacy Function (If Applicable)

  • If the existing function is deprecated or unused, drop it using:
DROP FUNCTION dbo.YourFunctionName;
  • Alternatively, rename the existing function using sp_rename if it must be preserved under a different identifier:
EXEC sp_rename 'dbo.YourFunctionName', 'YourFunctionName_Legacy';

Step 4: Clear Cached Execution Plans

  • Since Windows Server 2025 environments may cache compiled plans referencing the old object name, flush the procedure cache to avoid stale references.
DBCC FREEPROCCACHE;
  • Restart the SQL Server service via Services.msc or PowerShell if the cache issue persists:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 5: Re-deploy the Script

  • Execute the corrected CREATE PROCEDURE script again in SSMS or via sqlcmd.
  • Validate there are no further naming conflicts in the deployment output log.

Alternative or Verification Steps

  • Verify the fix by running sp_help 'usp_GetCustomerData' to confirm the object now exists as a SQL_STORED_PROCEDURE without errors.
  • If the conflict persists across linked servers or synonyms, check sys.synonyms for any aliasing that may still point to the old function name.

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

Troubleshooting Guide: SQL Server Error 1043 — “‘%.*ls’ is not yet implemented”

Why This Error Happens

This error occurs when a T-SQL statement, DBCC command, or client driver attempts to invoke a feature, syntax construct, or system procedure that is either deprecated, reserved for future use, or not supported in the current edition/build of SQL Server 2025. It is commonly triggered by compatibility-level mismatches, where legacy applications send syntax valid in older SQL Server versions but flagged as a placeholder or stub in the parser. This can also surface when a third-party tool or ORM generates dynamic SQL using a feature exclusive to Enterprise or Azure-connected editions while running on Standard or Developer editions.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Statement Triggering the Error

  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full stack trace accompanying Error 1043.
  • Run SELECT * FROM sys.dm_exec_requests WHERE session_id = @@SPID to capture the exact query text via sys.dm_exec_sql_text(sql_handle).
  • Isolate whether the error comes from a stored procedure, ad-hoc query, or client-generated SQL (e.g., from Entity Framework or JDBC).

Step 2: Verify Database Compatibility Level

  • Run SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDB'; to check the current level.
  • If the database was migrated from an older version, update it using:
  ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 170;
  • Confirm the feature causing the error is actually supported in SQL Server 2025 by cross-referencing Microsoft’s official Breaking Changes documentation for this release.

Step 3: Check Edition and Feature Licensing

  • Run SELECT SERVERPROPERTY('Edition'), SERVERPROPERTY('EngineEdition'); to confirm you are not on Express or Web Edition, which block certain enterprise-only features.
  • If using Azure Arc-enabled SQL Server features, verify the server is properly registered via azcmagent show in PowerShell.
  • Disable or rewrite any query hints, DBCC traceflags, or extended events that reference unsupported or removed functionality (common with deprecated traceflags like 1211 or 1224 in newer builds).

Step 4: Update SQL Server Cumulative Updates

  • Navigate to Windows Update or manually download the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Install via elevated PowerShell: Setup.exe /Action=Patch /IAcceptSQLServerLicenseTerms /Quiet.
  • Restart the SQL Server service: Restart-Service MSSQLSERVER -Force.

Step 5: Patch or Replace the Offending Client Driver

  • Update ODBC/OLEDB drivers to the latest version supporting SQL Server 2025 (minimum: ODBC Driver 18.4 or later).
  • Check driver version in Control Panel > ODBC Data Sources > Drivers tab.
  • If using a legacy application, apply a compatibility shim by rewriting the query to use fully-supported T-SQL syntax instead of relying on deprecated placeholders.

Alternative or Verification Steps

  • Re-run the original query or application transaction after each step and confirm Error 1043 no longer appears in sys.dm_os_ring_buffers or the SQL error log.
  • If the issue persists, open a case with Microsoft Support referencing the exact build number (SELECT @@VERSION;) since Error 1043 can sometimes indicate a genuinely unimplemented feature requiring a hotfix rather than a configuration fix.

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

Troubleshooting Guide: SQL Server Error 1042 – Conflicting Optimizer Hints

Why This Error Happens

Error 1042 occurs when a T-SQL query specifies two or more query hints that instruct the optimizer to use mutually exclusive execution strategies, such as combining HASH JOIN with MERGE JOIN, or pairing FORCE ORDER with conflicting join hints in the same statement. This is purely a query-authoring issue rather than a server configuration problem—SQL Server 2025’s query optimizer cannot resolve two contradictory directives simultaneously, and it rejects the batch at parse/bind time. The error commonly surfaces after code migrations, ORM-generated queries, or when legacy hint syntax is copied between stored procedures without reviewing hint compatibility.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing statement from the application log, SSMS error output, or Extended Events session filtering on error_reported with Error = 1042.
  • Check SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the timestamp correlating to the failure.
  • Reproduce the issue in SSMS by running the isolated query against a test database to confirm the hint conflict triggers consistently.

Step 2: Review and Isolate the Query Hints

  • Locate the OPTION() clause at the end of the query or inline hints like WITH (HASHJOIN), WITH (LOOP), or WITH (MERGE) on JOIN clauses.
  • Cross-reference hints against Microsoft’s documented incompatible combinations (e.g., FORCE ORDER conflicting with OPTIMIZE FOR UNKNOWN plus join-type hints, or INDEX hints conflicting with FORCESCAN/FORCESEEK).
  • Remove or comment out one hint at a time and re-execute to pinpoint exactly which pair is causing the conflict.

Step 3: Correct the Query Syntax

  • Rewrite the query using only one join-strategy hint per statement (choose either LOOP, HASH, or MERGE—never combine them).
  • If using stored procedures, update the definition via ALTER PROCEDURE and redeploy through your deployment pipeline or directly in SSMS.
  • For ORM-generated SQL (Entity Framework, Hibernate, etc.), check the data access layer or raw SQL fragments for hardcoded hints and adjust the mapping configuration accordingly.

Step 4: Validate Query Store and Cached Plans

  • Open SQL Server Management Studio, navigate to Databases > [YourDB] > Query Store > Top Resource Consuming Queries.
  • Clear any cached plans referencing the old hint combination using DBCC FREEPROCCACHE (scoped to a specific plan handle if in production) to prevent reuse of a bad plan shape.
  • Re-run the corrected query and confirm it compiles and executes without throwing Error 1042.

Step 5: Deploy and Monitor

  • Push the corrected stored procedure or application code to staging, then production, following your standard change management process.
  • Enable Extended Events trace temporarily to monitor for recurrence of Error 1042 across the broader application workload.

Alternative or Verification Steps

  • Run the corrected query directly in SSMS with Include Actual Execution Plan enabled; confirm no red warning icons or parser errors appear and the plan uses a single consistent join strategy.
  • If the error persists intermittently, check for dynamic SQL generation in the application layer that may be concatenating hints from multiple code paths—add logging to output the final generated SQL string before execution for full visibility.

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

Troubleshooting Guide: Error 1041 — “Option %.*ls is not allowed for a LOG file”

Why This Error Happens

This error occurs when a CREATE DATABASE, ALTER DATABASE, or RESTORE statement specifies a file-level option (such as FILESTREAM, MAXSIZE behavior reserved for data files, or a data-specific property) against a file explicitly declared with FILETYPE = LOG. SQL Server 2025 strictly validates that certain options are only valid for ROWS (data) files, and applying them to a .ldf log file entry violates the file-type schema rules. This is almost always caused by a malformed or copy-pasted T-SQL script where data-file syntax was mistakenly reused in the (NAME = ..., FILENAME = ...) block for the log file.

Step-by-Step Resolution Guide

Step 1: Review the T-SQL Script for Invalid Syntax

  • Open the script that triggered the error (CREATE DATABASE, ALTER DATABASE, or RESTORE FILELISTONLY-derived script).
  • Locate the LOG ON clause and check for options like FILEGROWTH paired with incompatible flags, FILESTREAM, or data-only properties incorrectly placed inside the log file definition.
  • Compare against Microsoft’s documented syntax: log files only support NAME, FILENAME, SIZE, MAXSIZE, and FILEGROWTH.

Step 2: Correct the File Definition Block

  • Remove any unsupported option from the (NAME = N'YourDB_log', FILENAME = N'L:\SQLLogs\YourDB_log.ldf', SIZE = ..., FILEGROWTH = ...) block.
  • Ensure the FILESTREAM or CONTAINMENT-specific clauses (if present) are moved exclusively under the PRIMARY or FILEGROUP section associated with data files, not the LOG ON section.
  • Save the corrected script and re-run it in SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.

Step 3: Validate Database Compatibility Level and Engine Edition

  • Confirm the target database compatibility level supports the options used (SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB';).
  • If using a newly introduced SQL Server 2025 option, verify it is supported in your specific edition (Standard vs. Enterprise) via SELECT SERVERPROPERTY('Edition');.
  • Re-attempt the operation after confirming edition/compatibility alignment.

Step 4: Check for Legacy Scripts or Migration Artifacts

  • If the script was migrated from an older SQL Server version (2016/2019), confirm deprecated syntax hasn’t been carried over.
  • Run DBCC TRACEON (3604) only if deeper diagnostic output is needed during a RESTORE operation, then re-check the generated file list with RESTORE FILELISTONLY FROM DISK = N'C:\Backups\YourDB.bak'; to ensure file types are correctly flagged as D (data) or L (log).

Alternative or Verification Steps

  • After applying the fix, re-run the original CREATE DATABASE / ALTER DATABASE / RESTORE command and confirm it completes with “Command(s) completed successfully” with no Error 1041 in the SQL Server Error Log (%ProgramFiles%\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • If the error persists, generate a fresh script using SSMS’s “Generate Scripts” wizard against an existing healthy database to get correctly formatted LOG ON syntax as a reliable template.

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

Troubleshooting Guide: SQL Server Error 1040 — Invalid MAXOUTSTANDINGIOPERVOLUME Value

Why This Error Happens

This error occurs when the MAX_OUTSTANDING_IO_PER_VOLUME parameter is set to a value of 0, a negative number, or a value exceeding the internal upper limit defined by SQL Server 2025’s storage engine. This typically happens due to a manual misconfiguration in a DBCC command, a startup trace flag, or an automated deployment script that passed an incorrect integer value. The root cause is almost always a configuration input error rather than a corrupted installation, since SQL Server validates this parameter strictly against a hard-coded ceiling before applying it to the I/O subsystem.

Step-by-Step Resolution Guide

Step 1: Identify the Source of the Invalid Value

  • Check if the parameter was set via a DBCC SETIOPARAMETER command or similar undocumented/diagnostic command in a recent script.
  • Review SQL Server Agent job history and any PowerShell/DSC deployment scripts for hard-coded values passed to this setting.
  • Search the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the exact timestamp and preceding context of Error 1040.

Step 2: Validate the Acceptable Range

  • Open a query window and run SELECT * FROM sys.dm_os_sys_info; to confirm the current I/O subsystem configuration and hardware thread count, since the upper bound is often tied to logical processor count or volume queue depth limits.
  • Cross-reference the maximum allowed value reported in the error message text (the second %d placeholder in the actual error output) rather than assuming a default like 255 or 512, as Windows Server 2025 NVMe stack changes have altered some defaults.
  • Confirm the target volume’s queue depth using Get-PhysicalDisk | Get-StorageReliabilityCounter in PowerShell to ensure your intended value aligns with actual hardware capability.

Step 3: Correct the Configuration Value

  • Edit the script, startup parameter, or configuration file (commonly found in SQL Server startup parameters under -T flags in SQL Server Configuration Manager) to use a valid positive integer within range.
  • Navigate to SQL Server Configuration Manager > SQL Server Services > [Instance Name] > Properties > Startup Parameters if the value was injected as a trace flag.
  • Set a conservative, validated value (e.g., 64 or 128) rather than an arbitrary high number, then save the configuration.

Step 4: Restart the SQL Server Service

  • Restart the instance via Restart-Service -Name 'MSSQLSERVER' in an elevated PowerShell session, or use SQL Server Configuration Manager.
  • Monitor the ERRORLOG in real time using Get-Content -Path "C:\...\ERRORLOG" -Wait to confirm the service initializes without re-triggering Error 1040.

Alternative or Verification Steps

  • Run SELECT * FROM sys.dm_io_virtual_file_stats(NULL, NULL); after restart to confirm I/O operations are being tracked normally across all database files with no stalls or latency spikes.
  • If the error persists after correcting the value, remove the custom MAX_OUTSTANDING_IO_PER_VOLUME setting entirely and allow SQL Server 2025 to use its dynamically calculated default, then reapply a custom value incrementally while monitoring Performance Monitor’s Avg. Disk Queue Length counter.

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

Troubleshooting Guide: SQL Server Error 1039 – “Option ‘%.*ls’ is Specified More Than Once”

Why This Error Happens

This error occurs when a T-SQL statement, command-line startup parameter, or configuration script contains a duplicate option or argument within the same command scope. SQL Server’s parser detects two instances of the same clause (such as a duplicate WITH option in an ALTER DATABASE/CREATE INDEX statement, or a repeated startup flag in the SQL Server service configuration) and rejects the entire statement to avoid ambiguous execution. This is typically caused by human error in hand-written scripts, copy-paste mistakes in automated deployment templates, or conflicting settings merged from multiple configuration sources (e.g., a startup parameter defined both in SQLServerManager and ERRORLOG startup string).

Step-by-Step Resolution Guide

Step 1: Identify the Exact Statement Triggering the Error

  • Open SQL Server Management Studio (SSMS) and check the Messages tab for the full error text, including the specific option name reported in place of %.*ls.
  • Check ERRORLOG located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025 for the exact query or startup string logged near the timestamp of the failure.
  • If the error occurred during a batch job, isolate the specific CREATE, ALTER, or BACKUP statement by running each command individually.

Step 2: Review and Correct the T-SQL Syntax

  • Open the offending script and search for the named option (e.g., MAXDOP, ONLINE, FILLFACTOR, WITH ENCRYPTION) to confirm it is listed twice within the same WITH (...) clause.
  • Remove the duplicate entry, keeping only one instance of the conflicting parameter.
  • Example fix for a duplicate index option:
-- Incorrect (duplicate ONLINE option)
ALTER INDEX IX_Test ON dbo.Orders REBUILD WITH (ONLINE = ON, ONLINE = OFF);

-- Corrected
ALTER INDEX IX_Test ON dbo.Orders REBUILD WITH (ONLINE = ON);

Step 3: Check SQL Server Startup Parameters (If Error Occurs on Service Start)

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services → right-click SQL Server (MSSQLSERVER) → Properties → Startup Parameters tab.
  • Inspect the list for duplicate flags such as two -T (trace flag) entries or two -d/-l/-e path parameters.
  • Remove the duplicate parameter and click Apply, then restart the SQL Server service via services.msc or by running:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Validate Automated Deployment Scripts or DACPAC Templates

  • If the error originates from a CI/CD pipeline (Azure DevOps, PowerShell DSC, or dbatools scripts), inspect the generated T-SQL output for merged duplicate parameters caused by templating logic.
  • Correct the source template (e.g., .sql or .json configuration files) to ensure each option is defined only once before re-running the deployment.

Alternative or Verification Steps

  • Re-run the corrected script in SSMS or via sqlcmd and confirm it executes without Error 1039 and returns the expected result set or confirmation message.
  • If using startup parameters, confirm successful service start by checking the Windows Event Viewer (Application log, source MSSQLSERVER) for Event ID 17137 (SQL Server started successfully) instead of a startup failure entry.

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

Troubleshooting Guide: SQL Server Error 1038

Why This Error Happens

Error 1038 occurs when a SELECT INTO statement attempts to create a new table but one or more columns in the result set lack explicit names—typically caused by computed columns, aggregate functions, or expressions that were not assigned an alias. SQL Server requires every column in the output to have a defined name since it uses this metadata to construct the schema of the new destination table. This commonly happens after query refactoring, copy-pasted T-SQL from another source, or when ORM-generated queries omit aliasing for calculated fields.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column in the Query

  • Review the SELECT INTO statement and locate any expressions, calculations, or function calls (e.g., COUNT(*), price * qty, GETDATE()) that do not have a column name.
  • Check for columns pulled from subqueries or joins where the source column name may have been lost due to aggregation or casting.
  • Use SQL Server Management Studio (SSMS) and run the inner SELECT portion alone (without INTO) to visually inspect the result grid headers—any column labeled “(No column name)” is the culprit.

Step 2: Add Explicit Aliases to All Unnamed Columns

  • Modify the query to assign an alias using the AS keyword for every computed or ambiguous column.
  • Example fix:
  SELECT CustomerID, SUM(OrderTotal) AS TotalSpent
  INTO dbo.CustomerSummary
  FROM Sales.Orders
  GROUP BY CustomerID;
  • Ensure aliases follow SQL Server naming rules (no reserved keywords, no leading numbers, and under 128 characters).

Step 3: Validate Nested Queries and CTEs

  • If the SELECT INTO pulls from a Common Table Expression (CTE) or derived table, confirm that the CTE itself defines column names either inline or via a column list immediately after the CTE name.
  • Example: WITH CTE_Sales (CustomerID, TotalSpent) AS (...) ensures downstream columns are never anonymous.
  • Re-run the corrected script in SSMS connected to your SQL Server 2025 instance and confirm the table is created successfully in the target database without throwing Error 1038.

Step 4: Check Linked Server or Cross-Database Queries (If Applicable)

  • If the source data originates from a linked server or OPENQUERY call on Windows Server 2025, verify that the remote provider is returning named columns rather than ordinal-only results.
  • Adjust the remote query syntax to include aliases before the data crosses the linked server boundary, as SQL Server cannot infer names from certain OLE DB providers.

Alternative or Verification Steps

  • After applying aliases, run sp_help 'dbo.YourNewTableName'; in SSMS to confirm all columns were created with proper names and expected data types.
  • As a quick alternative, wrap the entire query in an explicit column list using INSERT INTO TargetTable (Col1, Col2) SELECT ... instead of SELECT INTO, which forces you to define every column name manually and bypasses the auto-naming dependency entirely.

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

Why This Error Happens

Error 1036 occurs when a CREATE DATABASE or ALTER DATABASE statement is missing a mandatory file option—most commonly the NAME (logical name) or FILENAME (physical path) parameter required for a file specification. SQL Server 2025 enforces stricter syntax validation when defining primary, secondary, or log files, and omitting these attributes inside the (...) file clause triggers this parsing failure. This is typically a T-SQL syntax issue rather than a permissions or connectivity problem, though malformed scripts generated by outdated tools or migration wizards can also be the culprit.

Step-by-Step Resolution Guide

Step 1: Review the Exact T-SQL Statement Causing the Error

  • Locate the CREATE DATABASE or ALTER DATABASE command in your script, job, or application log.
  • Check whether the file definition block includes both NAME = 'logical_name' and FILENAME = 'C:\Path\To\File.mdf'.
  • Confirm you’re not missing the parameter entirely for a secondary data file (.ndf) or log file (.ldf) when using ADD FILE or ADD LOG FILE.

Step 2: Correct the File Specification Syntax

  • Rewrite the statement to include all required attributes, for example:
  ALTER DATABASE MyDB
  ADD FILE (NAME = 'MyDB_Data2', FILENAME = 'C:\SQLData\MyDB_Data2.ndf', SIZE = 100MB)
  TO FILEGROUP [PRIMARY];
  • Ensure the FILENAME path exists and the SQL Server service account has write access to that directory on Windows Server 2025 / Windows 11.
  • Double-check filegroup names and size/growth parameters are properly comma-separated inside the same parentheses block.

Step 3: Validate Script Against SQL Server 2025 Syntax Changes

  • Open SQL Server Management Studio (SSMS) and use the Query > Parse option (Ctrl+F5) before executing.
  • Compare your script against the current CREATE DATABASE documentation, as SQL Server 2025 may deprecate or require additional file-option keywords not present in older scripts.
  • If the script was auto-generated (e.g., via a migration tool or third-party backup utility), regenerate it using an updated version compatible with SQL Server 2025.

Step 4: Re-Run the Statement and Monitor the Error Log

  • Execute the corrected script in SSMS or via sqlcmd.
  • Open Event Viewer > Applications and Services Logs > MSSQLSERVER to confirm no further Error 1036 entries appear.
  • If running inside a deployment pipeline (DACPAC, DevOps release, etc.), re-trigger the pipeline and check the build log for the same error.

Alternative or Verification Steps

  • Run sp_helpdb 'YourDatabaseName' or query sys.master_files to confirm the new/altered file was created with the correct logical name and physical path.
  • If the error persists, extract the full generated DDL using SSMS > Generate Scripts on an existing healthy database and compare file-option syntax side-by-side with your failing script to spot the missing parameter.

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

Microsoft SQL Server 2025 — Error 1037: CASCADE Constraint Failure

Why This Error Happens

Error 1037 occurs when a CASCADE action (DELETE or UPDATE) on a foreign key relationship attempts to modify data that violates another constraint, trigger, or referential integrity rule elsewhere in the schema. This is commonly caused by circular foreign key references, conflicting multiple cascade paths pointing to the same child table, or a corrupted index on the constrained columns. In Windows Server 2025 / Windows 11 environments, this can also surface due to stale metadata caching in SQL Server’s plan cache after a schema change.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Constraint

  • Run DBCC CHECKCONSTRAINTS to find which constraint is blocking the cascade.
  • Query sys.foreign_keys and sys.foreign_key_columns to map out all relationships touching the affected table.
  • Look specifically for multiple cascade paths converging on a single child table — SQL Server disallows this by design.

Step 2: Break Circular or Multi-Path Cascade Chains

  • Open SQL Server Management Studio (SSMS) and navigate to Database > Tables > Keys.
  • Script out the offending foreign key using sp_helpconstraint 'TableName'.
  • Modify one of the conflicting constraints to use ON DELETE NO ACTION instead of CASCADE:
  ALTER TABLE dbo.ChildTable
  DROP CONSTRAINT FK_ChildTable_ParentTable;

  ALTER TABLE dbo.ChildTable
  ADD CONSTRAINT FK_ChildTable_ParentTable
  FOREIGN KEY (ParentID) REFERENCES dbo.ParentTable(ID)
  ON DELETE NO ACTION;
  • Handle the cascading logic manually via an INSTEAD OF DELETE trigger if business logic requires it.

Step 3: Clear Cached Execution Plans and Metadata

  • Run DBCC FREEPROCCACHE to clear stale plans referencing the old constraint structure.
  • Restart the SQL Server service via Services.msc (search SQL Server (MSSQLSERVER)) or run:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Confirm Windows Server 2025 Group Policy isn’t blocking the service restart under Local Security Policy > User Rights Assignment.

Step 4: Rebuild Affected Indexes

  • Run ALTER INDEX ALL ON dbo.ChildTable REBUILD; to rule out index corruption as a contributing factor.
  • Check sys.dm_db_index_physical_stats for fragmentation levels above 30% on the constrained columns.

Alternative or Verification Steps

  • Re-run the original DELETE/UPDATE statement that triggered Error 1037 and confirm it completes without rollback.
  • If the error persists, isolate the table in a test database using sp_fkeys to export only the foreign key structure, then rebuild constraints one at a time to pinpoint the exact conflicting path.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Error 1035

Why This Error Happens

Error 1035 with the message “Incorrect syntax near ‘%.*ls'” occurs when the SQL Server parser encounters a token it cannot resolve within the context of the surrounding Transact-SQL statement. This is typically caused by reserved keyword conflicts, a malformed query generated by an application or ORM, or incompatible syntax left over from a deprecated feature that Windows Server 2025 / Windows 11-hosted instances no longer support. In some cases, this also surfaces after an in-place upgrade when compatibility level settings do not match the T-SQL being submitted.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Statement

  • Enable SQL Server Profiler or Extended Events to capture the exact batch text sent to the server.
  • Look for the literal substitution placeholder (%.*ls) in the error log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Reproduce the query manually in SQL Server Management Studio (SSMS) to confirm the exact line and character position of the syntax break.

Step 2: Check for Reserved Keywords and Compatibility Level

  • Run SELECT name, compatibility_level FROM sys.databases; to confirm the database is set to the expected level (e.g., 160 for SQL Server 2022, 170 for SQL Server 2025).
  • If a reserved keyword (such as OPENJSON, STRING_SPLIT, or GRAPH identifiers) is being used as an object name, wrap it in square brackets, e.g., [Order].
  • Update compatibility level if needed: ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 170;

Step 3: Validate Application/ORM-Generated Queries

  • Inspect connection strings and ORM query builders (Entity Framework, Hibernate, etc.) for dynamically concatenated SQL that may insert unescaped special characters or NULL values.
  • Check for mismatched quotation marks, especially when the application passes Unicode strings (N'...') incorrectly.
  • Patch or update the data access layer/driver (e.g., Microsoft.Data.SqlClient) to the latest version compatible with SQL Server 2025.

Step 4: Repair Corrupted Stored Procedures or Scripts

  • Run sp_helptext 'YourProcedureName'; to review the stored procedure definition for corruption or truncation.
  • If corruption is suspected, drop and recreate the object using a known-good backup of the script from source control.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after making changes.

Alternative or Verification Steps

  • Re-run the original query or application transaction and confirm no Error 1035 appears in the SQL Server ERRORLOG or Windows Event Viewer (Application log).
  • If the issue persists, use DBCC CHECKDB to rule out underlying database corruption, and test the same query against a freshly restored copy of the database on a separate instance.

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

Troubleshooting Guide: SQL Server Error 1034 – Duplicate Trigger Action Specification

Why This Error Happens

This error occurs when a CREATE TRIGGER or ALTER TRIGGER statement specifies the same action (INSERT, UPDATE, or DELETE) more than once in the FOR/AFTER/INSTEAD OF clause. SQL Server’s parser requires each DML action to be declared only a single time per trigger definition, and a duplicate entry (e.g., FOR INSERT, INSERT, UPDATE) violates this syntax rule. This is typically caused by a copy-paste error, a faulty script-generation tool, or manual editing of a trigger script without reviewing the full action list.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Trigger Script

  • Open SQL Server Management Studio (SSMS) and identify the script that threw Error 1034.
  • Check the SQL Server Error Log (Management > SQL Server Logs) or the client application log for the exact timestamp and associated T-SQL batch.
  • If deploying via a DACPAC, CI/CD pipeline, or ORM-generated migration, pull the raw generated SQL file for inspection.

Step 2: Inspect and Correct the Trigger Declaration Syntax

  • Review the FOR, AFTER, or INSTEAD OF clause of the trigger definition.
  • Look specifically for repeated keywords, such as:
  • CREATE TRIGGER trg_Example ON dbo.Orders AFTER INSERT, INSERT, UPDATE AS ...
  • Remove the duplicate action so only unique actions remain, for example:
  • CREATE TRIGGER trg_Example ON dbo.Orders AFTER INSERT, UPDATE AS ...
  • Save the corrected script to a local .sql file before re-running it.

Step 3: Validate the Script Using SQLCMD or SSMS Parse Mode

  • In SSMS, highlight the corrected trigger script and use Query > Parse (Ctrl+F5) to confirm there are no syntax errors before execution.
  • Alternatively, validate from the command line on Windows Server 2025 / Windows 11 using:
  • sqlcmd -S localhost -d YourDatabaseName -i "C:\Scripts\FixTrigger.sql" -b
  • Confirm the output returns no error messages referencing Error 1034.

Step 4: Re-deploy the Trigger

  • Execute the corrected CREATE TRIGGER or ALTER TRIGGER statement against the target database.
  • If the trigger already exists in a broken state, drop it first using:
  • DROP TRIGGER IF EXISTS dbo.trg_Example;
  • Then run the corrected creation script to register the trigger cleanly.

Alternative or Verification Steps

  • Verify the fix by querying sys.triggers and sys.sql_modules to confirm the trigger exists and its definition no longer contains duplicate action keywords: SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('dbo.trg_Example');
  • If the error persists despite a visually correct script, check for hidden duplicate trigger definitions in source control or build artifacts (common in auto-generated migration scripts) and regenerate the script from a clean schema export.

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

Troubleshooting Guide: SQL Server Error 1033 – “The ORDER BY Clause Is Invalid in Views”

Why This Error Happens

This error occurs because SQL Server does not permit an ORDER BY clause in a view definition unless it is paired with TOP, OFFSET, or FOR XML, since views are meant to represent unordered result sets by design. The root cause is almost always a T-SQL syntax violation where a developer attempts to force a specific sort order directly into the CREATE VIEW statement without one of these qualifying clauses. This is not a permissions or corruption issue, but a query logic restriction enforced by the Database Engine to maintain relational set theory compliance.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Open SQL Server Management Studio (SSMS) 21 and connect to your Windows Server 2025 instance.
  • Locate the specific view under Databases > [YourDB] > Views that is throwing Error 1033.
  • Right-click the view and select Script View as > ALTER To > New Query Editor Window to view the raw T-SQL.

Step 2: Modify the Query Using TOP 100 PERCENT

  • Add the TOP 100 PERCENT clause immediately after the SELECT statement to make the ORDER BY clause technically valid.
  • Update the syntax to match the following pattern:
  • CREATE VIEW dbo.vw_YourView AS SELECT TOP 100 PERCENT ColumnA, ColumnB FROM dbo.YourTable ORDER BY ColumnA;
  • Note: This method is syntactically valid but does not guarantee physical sort order upon retrieval due to the SQL Server Query Optimizer potentially ignoring the sort for view indexes.

Step 3: Implement a Row-Limiting Function (Recommended Fix)

  • Replace TOP 100 PERCENT with OFFSET 0 ROWS FETCH NEXT to enforce a strict ANSI SQL standard sort that the optimizer cannot ignore.
  • Rewrite the view logic as follows: SELECT ColumnA, ColumnB FROM dbo.YourTable ORDER BY ColumnA OFFSET 0 ROWS FETCH NEXT 9999999 ROWS ONLY;
  • Execute the ALTER VIEW script to save the updated, error-free definition to the database schema.

Step 4: Move Sorting Logic to the Consumer Query

  • Best practice dictates removing the ORDER BY from the view entirely and placing it on the outer query that calls the view.
  • Update your application code or reporting tool (e.g., Power BI 2025, SSRS) to use: SELECT * FROM dbo.vw_YourView ORDER BY ColumnA;
  • Save and redeploy the connection string configuration to ensure the application pulls the updated view schema.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM dbo.vw_YourView; in a new query window; if the ALTER VIEW executes without throwing Error 1033 and returns data, the fix is successful.
  • Alternative: If strict ordering is mandatory for compliance reasons, consider converting the standard view into an Indexed View with a `UNIQUE CLUSTERED INDEX**, which physically stores the data on disk in the specified order, bypassing the standard logical view restrictions.

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

Troubleshooting Guide: SQL Server Error 1031 – “Percent Values Must Be Between 0 and 100”

Why This Error Happens

This error typically occurs when a SQL Server command (such as DBCC SHRINKDATABASE, BACKUP, or a maintenance plan task) receives a corrupted, malformed, or out-of-range parameter for a percentage value, often due to a misconfigured T-SQL script or a legacy maintenance plan that was not properly upgraded during migration to SQL Server 2025. In some cases, this is triggered by third-party monitoring tools passing invalid integer values (negative numbers or values exceeding 100) into system stored procedures. It can also result from registry corruption on Windows Server 2025 affecting default instance configuration values.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Job

  • Open SQL Server Management Studio (SSMS) and navigate to SQL Server Agent > Jobs.
  • Review the job history for the specific job that threw Error 1031.
  • Check for DBCC SHRINKFILE or SHRINKDATABASE commands with a hardcoded percentage parameter.
  • Run the following query to check system health extended events: SELECT * FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL);

Step 2: Correct the Percentage Parameter in T-SQL

  • Locate the script causing the error (usually in Maintenance Plans or custom stored procedures).
  • Ensure the value passed is an integer between 0 and 100 (inclusive).
  • Example of a corrected command: DBCC SHRINKDATABASE (YourDB, 10);
  • Avoid using variables that might resolve to NULL or negative integers; add a validation check like IF @PercentValue BETWEEN 0 AND 100.

Step 3: Verify Windows Server 2025 Registry and Instance Configuration

  • Open the Registry Editor (regedit) on the Windows Server 2025 host.
  • Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLServer.
  • Look for corrupted or unexpected string values related to BackupDirectory or shrink thresholds.
  • If corruption is found, restore this key from a recent System State backup rather than manually editing values.

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

  • Check your current build number by running: SELECT @@VERSION;
  • Compare it against the latest Cumulative Update available on the Microsoft Update Catalog.
  • Download and install the latest CU to patch potential internal bugs related to parameter validation in system procedures.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after installation.

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific job or script manually in SSMS. If the task completes without throwing Error 1031, the parameter validation issue is resolved.
  • Alternative Solution: If the error persists after patching, rebuild the specific Maintenance Plan from scratch using the Maintenance Plan Wizard rather than editing the existing XML/SSIS package, as the underlying package file may be corrupted beyond simple parameter edits.

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

Troubleshooting Guide: SQL Server Error 1032 – Column Prefix Mismatch

Why This Error Happens

This error occurs when an UPDATE statement references a table alias or column prefix that doesn’t match the actual table name specified in the UPDATE clause. SQL Server’s query parser requires strict consistency between the alias defined in the FROM clause (or UPDATE clause) and any column prefixes used elsewhere in the query, particularly when JOINs are involved. This is typically a T-SQL syntax issue rather than a server configuration problem, often introduced after query refactoring, ORM-generated SQL, or copy-pasted scripts where an alias was renamed in one place but not another.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query from SQL Server error logs or Activity Monitor in SQL Server Management Studio (SSMS) 21.
  • Check the error message details for the specific prefix and object names referenced (e.g., 'dbo.Orders' vs 'o').
  • Open the query in SSMS and locate the UPDATE statement in question.

Step 2: Audit the UPDATE Clause and Aliases

  • Verify the table/alias declared immediately after the UPDATE keyword matches the alias used in the SET clause.
  • Example of incorrect syntax:
  UPDATE o
  SET t.Status = 'Shipped'
  FROM Orders o
  JOIN Tracking t ON o.OrderID = t.OrderID
  • Correct the mismatch so the UPDATE target aligns with the column prefix being modified:
  UPDATE t
  SET t.Status = 'Shipped'
  FROM Orders o
  JOIN Tracking t ON o.OrderID = t.OrderID

Step 3: Validate Multi-Table JOIN Logic

  • Ensure every column prefix in the SET clause matches an alias explicitly defined in the FROM/JOIN section.
  • Remove any legacy prefixes (e.g., old table names) left over from previous script versions.
  • Re-run the query in a non-production environment using SSMS 21 or Azure Data Studio connected to your SQL Server 2025 instance.

Step 4: Check for ORM or Application-Generated Scripts

  • If the query originates from an application (e.g., Entity Framework, Dapper), inspect the generated SQL via SQL Server Profiler or Extended Events.
  • Update the application-side query builder logic to ensure aliasing logic is consistent before regenerating the script.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS; a successful execution with no Error 1032 confirms the fix.
  • If the issue persists, use SET PARSEONLY ON before running the query to isolate syntax errors without executing the full statement, then review the parsed output for alias mismatches.

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

Why This Error Happens

Error 1030 occurs when SQL Server encounters a non-deterministic time or date reference—such as GETDATE(), CURRENT_TIMESTAMP, or an implicit current-date literal—inside a context that strictly requires constant, deterministic values. This typically happens in computed column definitions, CHECK constraints, default constraints tied to indexed views, or partition function boundary definitions where SQL Server needs to guarantee the same value will be produced every time the expression is evaluated. Because the current date/time changes on every execution, the query optimizer rejects it to preserve index and constraint integrity.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object or Query

  • Run DBCC TRACEON(3604); followed by the failing DDL statement to capture the exact line triggering Error 1030.
  • Check recent changes in SQL Server Management Studio (SSMS) under Object Explorer > Databases > [YourDB] > Tables > Constraints.
  • Look specifically for computed columns, CHECK constraints, or indexed view definitions referencing GETDATE(), SYSDATETIME(), or CURRENT_TIMESTAMP.

Step 2: Replace Non-Deterministic Functions with Constants or Triggers

  • Remove the non-deterministic function from the computed column or constraint definition.
  • For default values, move the logic into an INSTEAD OF INSERT trigger or application-layer logic instead of a schema-bound default.
  • Example fix for a computed column:
  ALTER TABLE dbo.Orders
  DROP COLUMN OrderDateCalc;
  ALTER TABLE dbo.Orders
  ADD OrderDateCalc AS ('2025-01-01');

Step 3: Rebuild Indexed Views or Partition Functions

  • If the error originates from an indexed view, drop and recreate the view using WITH SCHEMABINDING but exclude any date/time functions from the SELECT list.
  • For partition functions, replace relative date expressions with hard-coded boundary values (e.g., '2025-01-01' instead of DATEADD(day, -1, GETDATE())).
  • Re-run the deployment script in SSMS or via sqlcmd -S localhost -d YourDB -i script.sql to confirm the object compiles cleanly.

Step 4: Validate Schema Changes in a Test Environment

  • Deploy the corrected script to a staging instance of SQL Server 2025 first.
  • Use sp_helptext 'dbo.YourObject' to confirm the function or constraint no longer references non-deterministic calls.

Alternative or Verification Steps

  • Run SELECT OBJECTPROPERTYEX(OBJECT_ID('dbo.YourObject'), 'IsDeterministic'); to confirm the object now returns 1 (deterministic).
  • If the constraint truly requires current-date logic, implement it via an application-level insert/update procedure instead of a schema-bound constraint, then re-test the original transaction that triggered Error 1030.

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

Troubleshooting Guide: SQL Server Error 1029 – “Browse Mode Is Invalid for Subqueries and Derived Tables”

Why This Error Happens

This error occurs because the FOR BROWSE clause is fundamentally incompatible with queries that reference subqueries, derived tables, or views containing aggregates—SQL Server’s browse mode requires a direct mapping between result columns and base table columns to support updatable cursors. When the query optimizer flattens or rewrites the execution plan to include a derived table (common in Microsoft SQL Server 2025’s enhanced query rewriting engine), it loses the metadata needed to track row origins for browse mode. This is typically triggered by legacy client applications (often using DB-Library or ODBC SQLSetPos operations) that append FOR BROWSE to complex, non-simple SELECT statements.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Enable SQL Server Profiler or Extended Events on the instance to capture the exact T-SQL statement triggering Error 1029.
  • Look specifically for SELECT ... FOR BROWSE statements combined with JOIN (SELECT ...) or nested subqueries in the WHERE clause.
  • Check the application’s connection string or driver settings (common in older ODBC/DB-Library clients) for forced browse-mode flags.

Step 2: Refactor the Query to Remove Derived Tables

  • Rewrite the subquery or derived table into a Common Table Expression (CTE) only if the client supports it, or flatten the logic into a single-level SELECT statement using direct JOINs to base tables.
  • Replace SELECT * FROM (SELECT col1, col2 FROM TableA) AS Derived FOR BROWSE with a direct query: SELECT col1, col2 FROM TableA FOR BROWSE.
  • If the application logic requires filtering, move the filtering to a standard WHERE clause rather than a nested subquery.

Step 3: Update Client Driver and Connection Settings

  • Navigate to the ODBC Data Source Administrator on Windows Server 2025 (Control Panel > System and Security > Administrative Tools > ODBC Data Sources).
  • Verify the driver version is updated to the latest SQL Server Native Client or Microsoft ODBC Driver 18+ for SQL Server, as older drivers force FOR BROWSE syntax unnecessarily.
  • Under the DSN configuration, disable “Use ANSI Quoted Identifiers” if it is conflicting with legacy browse mode requests.

Step 4: Modify Application-Side Cursor Logic

  • If using a legacy application, locate the connection string in the config file (e.g., web.config or app.config) and remove the SET FMTONLY ON or SQLSetPos triggers that force server-side browse cursors.
  • Switch the cursor type from “Keyset-driven” to “Static” or “Forward-only” where row-level updates via browse mode are not strictly necessary.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell to clear cached execution plans after making changes.

Alternative or Verification Steps

  • Verification: Run the modified query directly in SQL Server Management Studio (SSMS) 2025 with SET FMTONLY OFF; preceding the statement to ensure the execution plan resolves without throwing Error 1029.
  • Alternative: If refactoring the query is not feasible due to third-party application constraints, implement a server-side INSTEAD OF trigger on a simple view that mimics the required data output, bypassing the need for FOR BROWSE on the complex derived table entirely.

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

Troubleshooting Guide: SQL Server Error 1028 – “The CUBE Getting Data” Structure Error

Why This Error Happens

Error 1028 typically occurs when SQL Server Analysis Services (SSAS) encounters a corrupted or inconsistent CUBE structure during OLAP processing, often due to interrupted metadata synchronization between the relational data source and the cube’s dimensional schema. This can result from abrupt service termination during a previous processing job, insufficient permissions on the SSAS service account to access underlying data source views (DSVs), or schema drift where source tables have been altered without reprocessing the cube structure. In some cases, this is also triggered by corrupted .cub or .asdatabase files within the SSAS data directory following an improper shutdown or disk-level fault.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions and Connectivity

  • Open SQL Server Configuration Manager and confirm the SSAS service (MSOLAP$INSTANCENAME) is running under a valid domain or service account.
  • Ensure the account has db_datareader rights on the source relational database and read access to the Data Source View (DSV) tables.
  • Test connectivity manually using sqlcmd -S servername -E -Q "SELECT 1" to rule out authentication failures.

Step 2: Reprocess the Cube with Full Process Mode

  • In SQL Server Management Studio (SSMS), right-click the affected cube under Analysis Services and select Process.
  • Choose Process Full instead of incremental options to force a complete rebuild of the cube structure and aggregations.
  • Monitor the job output pane for schema mismatch warnings, which often pinpoint the exact dimension or measure group causing the failure.

Step 3: Repair or Restore Corrupted Cube Files

  • Navigate to the SSAS data directory, typically located at C:\Program Files\Microsoft SQL Server\MSAS16.MSSQLSERVER\OLAP\Data\.
  • Check for .0.db, .cub, or .asdatabase files with a recent modification timestamp that may be truncated or zero-byte.
  • If corruption is confirmed, restore the database from the last known good backup using Restore-ASDatabase in PowerShell or via SSMS Restore Database under Analysis Services.

Step 4: Rebuild the Data Source View Schema

  • Open the project in SQL Server Data Tools (SSDT) and refresh the Data Source View to resync table/column metadata.
  • Deploy the updated project to the server to push corrected schema definitions before reprocessing.

Alternative or Verification Steps

  • Run a test query against the cube using MDX in SSMS (e.g., SELECT {[Measures].[Sales Amount]} ON COLUMNS FROM [YourCube]) to confirm data retrieval succeeds without Error 1028.
  • If reprocessing fails repeatedly, delete and recreate the cube object from the SSDT project file, then redeploy as a clean installation to bypass residual metadata corruption.

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

Troubleshooting Guide: SQL Server Error 1026 – GOTO Cannot Jump Into TRY/CATCH Scope

Why This Error Happens

This error occurs because Transact-SQL enforces strict structural boundaries around TRY…CATCH blocks, and a GOTO statement is attempting to transfer control from outside the block to a label defined inside it. SQL Server 2025’s parser validates control-flow integrity at compile time, rejecting any jump that would bypass the structured entry point of a TRY or CATCH block. This is not a server configuration or permissions issue — it is a T-SQL syntax violation rooted in how the batch or stored procedure script was authored.

Step-by-Step Resolution Guide

Step 1: Identify the Offending GOTO Statement

  • Open the stored procedure, trigger, or script referenced in the error message (SQL Server will typically report the line number alongside Error 1026).
  • Locate the GOTO statement and trace which label it targets.
  • Confirm whether that label resides inside a BEGIN TRY…END TRY or BEGIN CATCH…END CATCH block.

Step 2: Restructure the Code to Avoid Cross-Boundary Jumps

  • Move the label (and the logic it represents) outside the TRY/CATCH block if it needs to be reachable from external code.
  • Alternatively, relocate the GOTO statement itself so it originates from within the same TRY or CATCH scope as its target label.
  • Replace GOTO-based branching with structured alternatives such as IF/ELSE, WHILE loops, or nested stored procedure calls where possible — this is best practice in SQL Server 2025 and avoids future maintainability issues.

Step 3: Validate the Script in SQL Server Management Studio (SSMS) or Azure Data Studio

  • Use the “Parse” (Ctrl+F5) function in SSMS to validate T-SQL syntax before execution.
  • Check the Messages pane for confirmation that no further Error 1026 instances appear.
  • If the procedure is lengthy, isolate and test the TRY/CATCH block independently in a scratch query window.

Step 4: Recompile and Redeploy the Stored Procedure

  • Run ALTER PROCEDURE (or DROP and CREATE) to push the corrected logic back to the database.
  • Clear the plan cache for that object if testing in a development environment:
  • EXEC sp_recompile 'YourProcedureName';
  • Re-run the calling application or job to confirm the procedure executes without compile errors.

Alternative or Verification Steps

  • Verify the fix by executing the corrected procedure manually via EXEC YourProcedureName; and confirming it completes without raising Error 1026 in the Messages tab.
  • If GOTO logic is deeply embedded in legacy code and difficult to refactor safely, consider wrapping the entire procedure body in a single outer TRY/CATCH block and eliminate internal GOTO jumps entirely in favor of early RETURN statements or nested procedure calls.

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

Troubleshooting Guide: SQL Server Error 1027 – Too Many Expressions in CUBE (GROUP BY Clause)

Why This Error Happens

This error occurs because SQL Server 2025 imposes a hard internal limit on the number of expressions that can be specified within a single CUBE or ROLLUP operator in a GROUP BY clause. When a query attempts to generate grouping sets that exceed this threshold (typically related to the 2^n combinations the engine must compute), the Query Optimizer rejects the statement before execution. This is not a server configuration or permissions issue, but rather a T-SQL syntax limitation designed to prevent exponential resource consumption during aggregation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Count Expressions

  • Locate the exact query referenced in the application log or SSMS error output that triggered Error 1027.
  • Count the number of column expressions listed inside the CUBE(...) or ROLLUP(...) function.
  • Note that SQL Server 2025 typically restricts this to a maximum of 10 expressions per CUBE operator; exceeding this triggers the error.

Step 2: Refactor the GROUP BY Clause

  • Break the single large CUBE into multiple smaller, separate GROUP BY CUBE statements combined with UNION ALL.
  • Alternatively, replace CUBE with GROUPING SETS to manually define only the specific combinations of columns you actually need, rather than generating every possible permutation.
  • Example rewrite: GROUP BY GROUPING SETS ((Col1, Col2), (Col1), (Col2), ()) instead of GROUP BY CUBE(Col1, Col2, Col3, Col4, ...).

Step 3: Optimize the Underlying Data Model

  • Review the source table or view to determine if all listed columns are genuinely required for the aggregate report.
  • Remove redundant or low-cardinality columns from the CUBE expression that do not add analytical value (e.g., columns that are functionally dependent on others already in the list).

Step 4: Update Application/Reporting Layer Logic

  • If the query is auto-generated by a BI tool (e.g., Power BI, SSRS, or a custom reporting engine) running on Windows Server 2025, check the data source configuration or MDX/DAX-to-SQL translation layer.
  • Update the report definition to limit the dimensions pulled into a single cube aggregation request.

Alternative or Verification Steps

  • After refactoring, execute the query in SQL Server Management Studio (SSMS) using SET SHOWPLAN_TEXT ON to confirm the query parses successfully without throwing Error 1027.
  • If reducing expressions is not feasible due to business requirements, consider pre-aggregating data into a summary table via an SSIS/ETL job, then running simpler GROUP BY queries against that smaller dataset instead of using CUBE directly on raw data.

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

Troubleshooting Guide: FIPS Warning — Identifier Length Exceeds 18 Characters (Error 1025)

Why This Error Happens

This warning occurs because SQL Server 2025, when running with FIPS (Federal Information Processing Standard) compliance flagging enabled, checks all object identifiers (table names, column names, variable names, etc.) against the ISO standard limit of 18 characters. Any identifier longer than 18 characters triggers Error 1025 as a compliance warning rather than a fatal error, since SQL Server itself supports identifiers up to 128 characters. This is not a corruption or permissions issue—it is a strict ANSI/ISO SQL compliance check that flags non-portable code when the FIPS_FLAGGER session setting or trace flag is active.

Step-by-Step Resolution Guide

Step 1: Confirm the Source of the FIPS Flagging

  • Check if SET FIPS_FLAGGER is being called explicitly in your T-SQL scripts, stored procedures, or application connection strings.
  • Run the following to inspect current session settings:
  DBCC USEROPTIONS;
  • Look for any FIPS_FLAGGER 'ENTRY', 'INTERMEDIATE', 'FULL', or 'ISO' level set in the session.

Step 2: Disable FIPS Flagging if Compliance Is Not Required

  • If strict ISO SQL compliance is not a business requirement, turn off the flagger in the session or script causing the warning:
  SET FIPS_FLAGGER OFF;
  • For application-wide settings, check sqlservr.ini or the startup parameters in SQL Server Configuration Manager (Windows Server 2025 / Windows 11) under:
    Computer Management > Services and Applications > SQL Server Configuration Manager > SQL Server Services
  • Remove any -T trace flag startup parameters tied to ISO compliance checking (e.g., trace flags used in older FIPS enforcement setups).

Step 3: Rename Long Identifiers (If Compliance Must Be Kept)

  • If FIPS/ISO compliance is mandatory for your environment, shorten any object or variable names exceeding 18 characters.
  • Use sp_rename for existing database objects:
  EXEC sp_rename 'dbo.VeryLongTableNameExample', 'ShortTblName';
  • Update all dependent stored procedures, views, and application code referencing the renamed objects.

Step 4: Audit Scripts and ORM-Generated Code

  • Check Entity Framework, Dapper, or other ORM-generated migration scripts, as auto-generated identifiers often exceed the 18-character ISO limit.
  • Adjust naming conventions in your ORM configuration file (e.g., appsettings.json or OnModelCreating in EF Core) to enforce shorter name generation.

Alternative or Verification Steps

  • Verify the fix by re-running the script or query that originally triggered Error 1025 and confirming no warning appears in SQL Server Management Studio (SSMS) Messages tab.
  • If the warning persists, use SQL Server Profiler or Extended Events to trace exactly which session or login is invoking FIPS_FLAGGER, as it may be set at the connection-string level by a third-party application rather than directly in T-SQL.

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

Troubleshooting Guide: SQL Server Error 1024 — FIPS Warning on Non-ANSI Function

Why This Error Happens

This warning occurs when SQL Server 2025’s FIPS (Federal Information Processing Standards) compliance flag is enabled and a query references a function that does not conform to strict ANSI SQL-92/SQL-99 standards. Non-ANSI functions—such as certain legacy string, date, or system functions—are flagged because FIPS mode requires full standards-compliant syntax for regulatory certification environments. This typically surfaces after enabling FIPS_FLAGGER at the session or database level, often as part of hardening SQL Server for government or compliance-driven deployments on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Flagged Function and Line Number

  • Review the full error message text, which includes the exact line number (%d) and function name (%ls) triggering the warning.
  • Run the query manually in SQL Server Management Studio (SSMS) with SET FIPS_FLAGGER 'ENTRY' (or the relevant level: OFF, ENTRY, INTERMEDIATE, FULL) to reproduce the exact warning in a controlled session.
  • Cross-reference the flagged function against Microsoft’s documented list of non-ANSI functions (e.g., GETDATE(), CHARINDEX(), ISNULL(), @@IDENTITY).

Step 2: Replace Non-ANSI Functions with ANSI-Compliant Equivalents

  • Swap GETDATE() for CURRENT_TIMESTAMP.
  • Swap ISNULL() for COALESCE().
  • Swap CHARINDEX() for POSITION() where functionally equivalent.
  • Update stored procedures, views, and functions in your database project files (typically under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\ or your source-controlled .sql scripts) to reflect these changes.

Step 3: Adjust the FIPS_FLAGGER Setting Scope

  • If the warning is informational only and not a hard compliance requirement, disable flagging at the session level using SET FIPS_FLAGGER 'OFF'; before executing legacy scripts.
  • For persistent environment-wide settings, configure this via a login trigger or default session settings in SSMS under Tools > Options > Query Execution > SQL Server > Advanced.
  • Avoid disabling FIPS mode at the OS level (Windows Server 2025 Local Security Policy > Security Options) unless absolutely necessary, as this impacts broader system cryptographic compliance.

Step 4: Re-Deploy and Re-Test Affected Scripts

  • Re-run the modified T-SQL scripts in a staging environment first.
  • Use sqlcmd -S <ServerName> -i script.sql -o output.log to batch-test multiple scripts and capture any remaining Error 1024 instances in the output log.

Alternative or Verification Steps

  • Verify the fix by re-executing the original query with SET FIPS_FLAGGER 'FULL'; active—if no Error 1024 appears, the function has been successfully converted to ANSI-compliant syntax.
  • If replacing functions is not feasible due to application dependency constraints, document the exception and apply SET FIPS_FLAGGER 'OFF' strictly at the stored procedure level rather than globally, minimizing compliance scope impact.

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

Troubleshooting Guide: SQL Server Error 1023 – “Invalid Parameter %d Specified for %ls”

Why This Error Happens

Error 1023 typically occurs when a system stored procedure, DBCC command, or extended stored procedure call receives an invalid or out-of-range parameter value, often due to mismatched SQL Server version compatibility settings after an upgrade to SQL Server 2025. This can also result from corrupted metadata in system catalogs or a mismatch between the client driver version and the server’s expected parameter schema. In some cases, deprecated parameter syntax from older SQL Server versions is passed to a procedure that no longer supports that format in the new engine.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Command Causing the Error

  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full stack trace.
  • Identify the specific stored procedure or DBCC command referenced in the %ls placeholder.
  • Run the command manually in SQL Server Management Studio (SSMS) 21 to reproduce the exact parameter being passed.

Step 2: Validate Database Compatibility Level

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

Step 3: Check for Driver and Client Library Mismatches

  • Confirm the application or client tool is using the updated ODBC Driver 19 or higher, or the Microsoft.Data.SqlClient library version 6.x.
  • Navigate to C:\Windows\System32\msodbcsql18.dll (or equivalent path) to verify the driver file version matches SQL Server 2025 requirements.
  • Update outdated drivers through the Microsoft Download Center or via winget upgrade Microsoft.ODBCDriverforSQLServer.

Step 4: Run Database Consistency Checks

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out metadata corruption.
  • Review the output for any system table inconsistencies that could be generating invalid parameter calls.
  • If corruption is found, restore from the most recent verified backup.

Step 5: Reapply the Latest Cumulative Update

  • Go to Control Panel > Programs and Features or use Get-Package in PowerShell to confirm the current SQL Server 2025 build number.
  • Download and install the latest Cumulative Update (CU) from the Microsoft SQL Server Download Center.
  • Reboot the Windows Server 2025 or Windows 11 host after installation to finalize the patch.

Alternative or Verification Steps

  • To verify the fix, re-run the original query or procedure that triggered Error 1023 and confirm it completes without raising the invalid parameter message in the Error Log.
  • As an alternative, isolate the issue by testing the same command against a newly created test database with default compatibility settings; if it succeeds there, the original database likely requires a schema or metadata repair.

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

Troubleshooting Guide: SQL Server Error 1021 – FIPS Warning Non-ANSI Statement

Why This Error Happens

This warning occurs when SQL Server’s FIPS flagger feature is enabled (via SET FIPS_FLAGGER) and it detects Transact-SQL syntax that deviates from the ANSI SQL-92 standard. The root cause is typically the use of SQL Server-specific extensions—such as TOP, OUTER JOIN shorthand syntax, system functions, or proprietary data types—within a session where strict ANSI compliance checking is active. This is not a corruption or permissions issue, but rather a compliance-auditing feature flagging code that would not be portable to other ANSI-compliant database systems.

Step-by-Step Resolution Guide

Step 1: Identify the Session-Level FIPS Flagger Setting

  • Open SQL Server Management Studio (SSMS) on your Windows Server 2025 or Windows 11 machine.
  • Run DBCC USEROPTIONS; to check if fips_flagger is currently active in your session.
  • Review the query or script referenced in the error message (Line %d) to locate the exact non-ANSI statement.

Step 2: Disable FIPS Flagger if Compliance Is Not Required

  • If strict ANSI compliance is not a business requirement, disable the flagger for your session by running:
  SET FIPS_FLAGGER OFF;
  • Place this command at the top of your script, before any other T-SQL statements execute.
  • Save the script and re-run it to confirm the warnings no longer appear.

Step 3: Rewrite Non-ANSI Syntax for Compliance (If Required)

  • If ANSI compliance is mandatory (e.g., for regulatory or portability reasons), manually refactor the flagged line.
  • Replace SQL Server-specific syntax with ANSI-standard equivalents:
  • Replace *= and =* legacy join syntax with explicit LEFT JOIN / RIGHT JOIN.
  • Replace TOP (n) with FETCH FIRST n ROWS ONLY where supported.
  • Avoid proprietary functions like ISNULL() in favor of COALESCE().
  • Save the corrected script under version control for future audits.

Step 4: Apply the Fix at the Server or Connection String Level (Optional)

  • For persistent enforcement across all sessions, configure the FIPS flagger level in your application’s connection initialization script.
  • Navigate to your application’s appsettings.json or web.config on Windows Server 2025 and ensure the initialization SQL includes SET FIPS_FLAGGER 'ENTRY'; (or the appropriate level: ENTRY, INTERMEDIATE, FULL).
  • Restart the SQL Server service via services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER to ensure new sessions pick up the setting consistently.

Alternative or Verification Steps

  • Verify the fix by re-executing the original script in SSMS and confirming Error 1021 no longer appears in the Messages pane.
  • If warnings persist, check for nested stored procedures or triggers that may independently invoke SET FIPS_FLAGGER, overriding your session-level setting.

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

Troubleshooting Guide: SQL Server Error 1022 — FIPS Warning on Non-ANSI Clause

Why This Error Happens

This warning occurs when FIPS flagging is enabled in SQL Server 2025 (via SET FIPS_FLAGGER) and the executing T-SQL batch contains syntax that deviates from the ANSI SQL-92 standard. Common triggers include legacy Sybase-style joins, proprietary functions (like GETDATE() instead of ANSI equivalents), or non-standard data types. This is not a fatal error but a compliance-level advisory, meaning the query will still execute unless strict enforcement policies are layered on top via Group Policy or application-level linting tools.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Line and Clause

  • Review the SQL Server Error Log or SSMS “Messages” tab for the exact line number (%d) and clause (%ls) referenced in the warning.
  • Open the stored procedure or script file in question using SSMS or Azure Data Studio.
  • Cross-reference the flagged clause against the ANSI SQL-92 keyword list in Microsoft Docs.

Step 2: Check the FIPS_FLAGGER Session Setting

  • Run the following to confirm if flagging is active in your session:
DBCC USEROPTIONS;
  • If FIPS flagging was enabled intentionally for compliance auditing, keep it active and proceed to rewrite the query.
  • If it was enabled accidentally (often via a legacy login trigger or startup script), disable it using:
SET FIPS_FLAGGER OFF;

Step 3: Rewrite the Non-ANSI Clause

  • Replace old-style joins (e.g., FROM TableA, TableB WHERE TableA.ID = TableB.ID) with ANSI-standard INNER JOIN syntax.
  • Swap proprietary functions for ANSI-compliant equivalents where possible (e.g., use CURRENT_TIMESTAMP instead of GETDATE()).
  • Save the corrected script and re-run it with FIPS flagging still enabled to confirm the warning no longer appears.

Step 4: Audit Startup Scripts and Logon Triggers

  • Check sys.server_triggers and any sp_procoption-flagged startup procedures for hard-coded SET FIPS_FLAGGER calls.
  • On Windows Server 2025, inspect the SQL Server Agent job steps under SQL Server Agent > Jobs to ensure no automated job is forcing strict ANSI mode unexpectedly.

Alternative or Verification Steps

  • Re-execute the corrected script in a fresh SSMS session with SET FIPS_FLAGGER ON; explicitly set — if no warning appears in the Messages pane, the fix is confirmed.
  • If rewriting all non-ANSI clauses is impractical (e.g., large legacy codebase), consider scoping FIPS flagging only to new development databases rather than globally, by isolating the setting to specific connection strings or application pools instead of server-wide configuration.

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

Troubleshooting Guide: Error 1020 – Sub-Entity Lists Cannot Be Specified for Entity-Level Permissions

Why This Error Happens

Error 1020 occurs when a GRANT, DENY, or REVOKE statement attempts to mix entity-level (table/object-level) permission syntax with a column-level or sub-entity list in a single, incompatible statement. This typically happens because SQL Server 2025’s permission parser requires sub-entity lists (such as specific column names or security predicate expressions) to be explicitly scoped using parentheses immediately after the securable name, and omitting or misplacing this scope causes the engine to reject the statement as ambiguous. It can also surface after an in-place upgrade to SQL Server 2025 where legacy T-SQL scripts used a permission syntax that was tolerated in older engine versions but is now strictly validated.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Statement

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact script or stored procedure that triggered Error 1020.
  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the timestamp and session ID associated with the failure.
  • Confirm whether the statement is a GRANT SELECT, DENY UPDATE, or similar command targeting both a table and specific columns simultaneously.

Step 2: Correct the Permission Syntax

  • Rewrite the statement so the column list is wrapped in parentheses directly after the object name, for example: GRANT SELECT ON dbo.Employees (EmployeeID, LastName) TO [DomainUser];
  • Do not attempt to apply a sub-entity list to an entity-level only permission (such as ALTER or CONTROL), as these permissions do not support column scoping at all — remove the sub-entity list in these cases.
  • If using Row-Level Security expressions, ensure the security predicate function is bound via CREATE SECURITY POLICY rather than being appended to a GRANT statement.

Step 3: Validate Compatibility Level and Scripts

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; to confirm the database is running under SQL Server 2025’s supported compatibility level (160 or higher).
  • Use the Database Engine Tuning Advisor or sp_helprotect to audit all existing permission scripts for deprecated syntax patterns before re-deployment.
  • Re-run the corrected script in a test environment on Windows Server 2025 to confirm the parser accepts the new syntax without raising Error 1020.

Step 4: Apply Cumulative Updates

  • Check Windows Update or the Microsoft Update Catalog for the latest Cumulative Update (CU) for SQL Server 2025, as parser edge cases are frequently patched.
  • Install the update using setup.exe /q /ACTION=Patch /INSTANCENAME=MSSQLSERVER /IACCEPTSQLSERVERLICENSETERMS from an elevated PowerShell session.
  • Restart the SQL Server service via services.msc or Restart-Service -Name 'MSSQLSERVER' after patching completes.

Alternative or Verification Steps

  • Verify the fix by re-executing the original failing script in SSMS; a successful execution with no Error 1020 confirms resolution, and you can further validate by querying sys.database_permissions to confirm the new column-level grants were correctly recorded.
  • If the error persists after syntax correction, as a workaround, split the statement into two separate commands — one granting entity-level access and a second explicit statement solely for the column-level or security expression scope.

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

Troubleshooting Guide: SQL Server Error 1019 – Invalid Column List in GRANT/REVOKE Statement

Why This Error Happens

Error 1019 occurs when a GRANT or REVOKE statement includes a column list after the object name, but the specified columns do not exist in the target table or view, or the column-level permission syntax is malformed. This commonly happens due to typos in column names, case-sensitivity mismatches under certain collations, or attempting to apply column-level permissions to an object type that doesn’t support them (such as a stored procedure or scalar function). It can also occur after a schema change where a column referenced in a permission script was renamed or dropped but the script wasn’t updated.

Step-by-Step Resolution Guide

Step 1: Verify the Target Object and Column Names

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SchemaName.TableName') to confirm the exact column names and spelling.
  • Cross-check the column names in your GRANT/REVOKE statement against this result set, paying close attention to case sensitivity if the database uses a case-sensitive collation.

Step 2: Confirm the Object Type Supports Column-Level Permissions

  • Check whether the target object is a table or view, since column-level GRANT/REVOKE is only valid for these object types.
  • Run SELECT type_desc FROM sys.objects WHERE object_id = OBJECT_ID('SchemaName.ObjectName') to confirm the object type.
  • If the object is a stored procedure, function, or other unsupported type, remove the column list and apply permissions at the object level instead.

Step 3: Correct the Syntax in the Permission Statement

  • Rewrite the statement using the correct format: GRANT SELECT ON SchemaName.TableName (Column1, Column2) TO [UserOrRole].
  • Ensure parentheses are placed immediately after the object name with no extra commas, trailing column references, or missing brackets around multi-word identifiers.
  • Save the corrected script in a new query window in SSMS under the active database context (verify via USE DatabaseName; at the top of the script).

Step 4: Refresh Metadata and Re-run the Script

  • If the column was recently renamed or added, run EXEC sp_refreshsqlmodule 'SchemaName.ObjectName'; to refresh cached metadata (for views) or simply reconnect SSMS to clear any stale IntelliSense cache.
  • Re-execute the corrected GRANT/REVOKE statement in a new query tab.

Alternative or Verification Steps

  • Confirm the fix by running SELECT * FROM fn_my_permissions('SchemaName.TableName', 'OBJECT') to validate that the specified permissions were applied correctly at the column level.
  • If the error persists, bypass column-level granularity entirely by granting permissions at the table or view level only, then use a DENY statement on specific columns if restriction is still required.

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

Troubleshooting Guide: SQL Server Error 1018 — “Incorrect Syntax Near Table Hint”

Why This Error Happens

Error 1018 occurs when the SQL Server Query Parser encounters a malformed WITH clause, typically due to a missing comma between multiple table hints, an incorrectly quoted hint (e.g., NOLOCK instead of NOLOCK), or a deprecated hint syntax that is no longer supported in SQL Server 2025’s updated query engine. This is purely a T-SQL syntax validation failure and does not indicate database corruption or a server-level configuration issue. It most commonly surfaces after migrating legacy scripts, stored procedures, or ORM-generated queries (like older Entity Framework or Hibernate mappings) to a newer SQL Server compatibility level.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the full query text using SQL Server Profiler, Extended Events, or the error message pop-up in SSMS, which usually highlights the exact statement number.
  • Check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the full stack trace tied to Event ID 1018.
  • Look specifically for WITH (...) clauses attached to table names in FROM or JOIN sections.

Step 2: Correct the Table Hint Syntax

  • Ensure every hint inside the parentheses is separated by a comma, for example: FROM Orders WITH (NOLOCK, INDEX(IX_OrderDate)).
  • Remove deprecated hints such as HOLDLOCK combined improperly with READPAST in older syntax formats; verify against the current Microsoft T-SQL reference for SQL Server 2025.
  • If the query was auto-generated by an ORM, update the ORM provider/driver to the latest version compatible with SQL Server 2025 (e.g., Microsoft.Data.SqlClient 6.x or newer).

Step 3: Validate Database Compatibility Level

  • Open SSMS, right-click the target database, select Properties > Options, and check the Compatibility Level field.
  • Run the following to confirm the current setting:
  • SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is set below 160 (SQL Server 2022) or the new 2025 equivalent, some older hint syntax may behave unexpectedly; test the query after aligning it with the current compatibility level standard.

Step 4: Rebuild and Test the Query in Isolation

  • Strip the query down to a minimal reproducible version containing only the FROM and WITH clause.
  • Execute it directly in a new SSMS query window connected to the Windows Server 2025 instance to confirm the parser accepts the corrected syntax.
  • Gradually reintroduce the rest of the original query (joins, filters, subqueries) to ensure no other clause is reintroducing the error.

Alternative or Verification Steps

  • Run SET PARSEONLY ON; before executing the corrected query batch — SQL Server will validate syntax without actually executing it, confirming the fix without touching live data.
  • If the error persists only on Windows Server 2025 but not on Windows 11 dev environments, verify both machines are running the identical SQL Server 2025 cumulative update (CU) via SELECT @@VERSION;, as parser behavior can shift slightly between CU builds.

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

Troubleshooting Guide: SQL Server Error 1016

Why This Error Happens

Error 1016 occurs when a Transact-SQL query attempts to apply the old-style outer join operators (*= or =*) within the WHERE clause of a statement that also contains ANSI-style JOIN syntax in the FROM clause. SQL Server’s query parser cannot resolve ambiguous join logic when both legacy and modern join syntaxes are mixed in the same statement. This is a syntax-level restriction enforced by the query compiler, not a server configuration or permissions issue, and it typically surfaces after migrating legacy applications or scripts to SQL Server 2025, where older compatibility behaviors have been further restricted.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query text from the application log, SSMS error dialog, or SQL Server Profiler/Extended Events trace.
  • Look specifically for *= or =* operators inside the WHERE clause.
  • Confirm that the same query also contains an explicit INNER JOIN, LEFT JOIN, RIGHT JOIN, or FULL JOIN keyword in the FROM clause.

Step 2: Rewrite the Query Using ANSI Join Syntax

  • Replace WHERE TableA.ID *= TableB.ID with LEFT JOIN TableB ON TableA.ID = TableB.ID.
  • Replace WHERE TableA.ID =* TableB.ID with RIGHT JOIN TableB ON TableA.ID = TableB.ID.
  • Move all join conditions out of the WHERE clause and into explicit ON clauses within the FROM clause.
  • Test the rewritten query in SQL Server Management Studio (SSMS) against a development instance before deploying to production.

Step 3: Check and Adjust Database Compatibility Level (Temporary Workaround)

  • Open SSMS, right-click the database, select Properties, then navigate to the Options page.
  • Check the current Compatibility Level value (e.g., SQL Server 2019 = 150, SQL Server 2022 = 160).
  • Note that legacy *= syntax is deprecated and unsupported regardless of compatibility level in SQL Server 2025, so this step only confirms configuration — it is not a long-term fix.
  • Document any application dependency on legacy syntax for code remediation.

Step 4: Search and Update All Affected Stored Procedures/Views

  • Run a search across the database for old-style join operators using:
SELECT OBJECT_NAME(object_id), definition
FROM sys.sql_modules
WHERE definition LIKE '%*=%' OR definition LIKE '%=*%';
  • Update each returned stored procedure, view, or function to use ANSI join syntax.
  • Redeploy the corrected objects using ALTER PROCEDURE or ALTER VIEW.

Step 5: Validate Application Code and ORM-Generated Queries

  • Review any dynamically generated SQL from ORMs (Entity Framework, Dapper, etc.) or legacy application layers.
  • Update query builders or raw SQL strings to eliminate legacy join syntax.
  • Re-run integration tests to confirm no further Error 1016 instances occur.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS or via sqlcmd and confirm it returns results without raising Error 1016.
  • Enable SQL Server Extended Events (sqlserver.error_reported) filtered on Error 1016 to monitor the production environment for any remaining legacy syntax usage after deployment.

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

Troubleshooting Guide: SQL Server Error 1017 — “The %ls hint cannot be specified more than once”

Why This Error Happens

This error occurs when a T-SQL query contains a duplicate query hint within the same OPTION clause, such as specifying OPTIMIZE FOR or MAXDOP twice in a single statement. It is a parser-level validation error in SQL Server 2025’s query compiler, meaning the SQL syntax itself is malformed rather than an environment or permissions issue. This commonly happens after query refactoring, auto-generated SQL from ORMs, or merging query hints from multiple sources (like a stored procedure plus a client-side hint injection) without checking for conflicts.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact failing statement using SQL Server Profiler, Extended Events (sqlserver.error_reported filtered on error 1017), or the application’s query log.
  • Look specifically at the OPTION (...) clause at the end of the statement — this is where duplicate hints live.
  • Check for ORM-generated queries (Entity Framework, Hibernate, Dapper) since these frequently concatenate hints from multiple configuration layers.

Step 2: Inspect and De-duplicate the OPTION Clause

  • Open the query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio and locate the OPTION clause, e.g.:
    OPTION (RECOMPILE, OPTIMIZE FOR (@param = 1), OPTIMIZE FOR (@param2 = 2))
  • Merge duplicate hints into a single instance — SQL Server only allows one OPTIMIZE FOR, one MAXDOP, one RECOMPILE, etc., per statement.
  • If using OPTIMIZE FOR UNKNOWN alongside explicit OPTIMIZE FOR (@param = value), remove one — they cannot coexist or be repeated.

Step 3: Check for Hint Injection from Multiple Layers

  • Review any query hint injection happening at the application layer (e.g., EF Core interceptors, custom repository patterns) as well as inside stored procedures or views being called.
  • Search stored procedure definitions using:
    SELECT OBJECT_DEFINITION(OBJECT_ID('YourProcName'))
  • Confirm hints aren’t being appended twice when the app wraps an already-hinted stored procedure call with its own OPTION clause.

Step 4: Correct and Redeploy the Query/Procedure

  • Edit the stored procedure or ad hoc query to include each hint only once.
  • Deploy the corrected object using SSMS, Azure Data Studio, or your CI/CD pipeline (e.g., SqlPackage.exe / DACPAC deployment on Windows Server 2025).
  • If the query is generated dynamically (via sp_executesql or string concatenation), add validation logic in the application to prevent duplicate hint strings from being appended.

Step 5: Clear the Plan Cache for the Affected Object

  • After correcting the query, clear any cached invalid plans tied to the object:
    DBCC FREEPROCCACHE (plan_handle) or ALTER PROCEDURE ... WITH RECOMPILE
  • This ensures SQL Server doesn’t attempt to reuse a cached execution context tied to the faulty syntax.

Alternative or Verification Steps

  • Re-run the corrected query directly in SSMS against SQL Server 2025 — if it compiles and returns results without Error 1017, the fix is confirmed.
  • If the error persists, enable Query Store (ALTER DATABASE [YourDB] SET QUERY_STORE = ON) and review the “Tracked Queries” pane to confirm no other cached or parameterized version of the query still contains the duplicate hint.

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

Troubleshooting Guide: SQL Server Error 1015 — Aggregate in ON Clause

Why This Error Happens

This error occurs because Transact-SQL does not permit aggregate functions (such as SUM(), COUNT(), AVG(), MAX(), or MIN()) to be evaluated directly within the ON clause of a JOIN statement. The SQL Server query optimizer processes JOIN conditions before the GROUP BY or aggregation logic is applied, meaning the aggregate values simply do not exist yet at the point the engine tries to evaluate the join logic. This is typically a query construction issue rather than a server configuration or permissions problem, often introduced after a migration to SQL Server 2025 where legacy queries with loose syntax are now being strictly parsed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Check the Activity Monitor or recent query history to locate the specific script throwing Error 1015.
  • Look specifically for syntax where an aggregate function appears immediately after ON or inside an AND/OR condition within the JOIN clause.

Step 2: Refactor the Query Using a Subquery or CTE

  • Move the aggregate logic out of the JOIN...ON clause and into a Common Table Expression (CTE) or a derived table (subquery).
  • Perform the aggregation in the subquery first, then join the result of that subquery to your main table.
  • Example structure: SELECT * FROM TableA JOIN (SELECT ID, SUM(Value) as Total FROM TableB GROUP BY ID) AS SubQuery ON TableA.ID = SubQuery.ID

Step 3: Move Aggregate Logic to the HAVING Clause

  • If the goal was to filter grouped results rather than join on them, remove the aggregate from the ON clause entirely.
  • Ensure the query includes a GROUP BY clause for the non-aggregated columns.
  • Place the aggregate condition inside a HAVING clause instead, such as HAVING SUM(Value) > 100.

Step 4: Validate Compatibility Level Settings

  • Open a new query window and run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDBName'; to check the current database compatibility level.
  • If the database was recently upgraded, ensure the compatibility level matches SQL Server 2025 standards (170) to ensure the parser handles the syntax using the newest rule set.
  • Run ALTER DATABASE YourDBName SET COMPATIBILITY_LEVEL = 170; if an update is required.

Alternative or Verification Steps

  • Verification: Execute the modified query in a test environment using SET SHOWPLAN_TEXT ON; to ensure the execution plan compiles successfully without throwing Error 1015 before deploying to production.
  • Alternative: If refactoring is complex, utilize a temporary table (#TempTable) to store the aggregated results first, then perform a standard JOIN against the temporary table in a separate, subsequent step.

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

Troubleshooting Guide: SQL Server Error 1014 – “A TOP or FETCH Clause Contains an Invalid Value”

Why This Error Happens

This error occurs when a query’s TOP or FETCH NEXT clause references a value that is negative, non-integer, NULL, or exceeds the data type’s acceptable range (such as a ROW_COUNT expression evaluating incorrectly). It is typically a T-SQL syntax or logic issue rather than a server configuration problem, often introduced by dynamic SQL, parameterized queries, or variables that were not validated before being passed into the clause. In some cases, it can also surface after an application update or migration to SQL Server 2025 where stricter parsing rules reject values that older engine versions silently tolerated.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Extended Events session for the exact statement that triggered Error 1014.
  • Use SELECT * FROM sys.dm_exec_query_stats cross-applied with sys.dm_exec_sql_text to locate recently failed or cached query text containing TOP or FETCH.
  • Review application logs (IIS, .NET, or custom middleware) for the stored procedure or dynamic SQL string that was executed at the time of failure.

Step 2: Validate the Variable or Parameter Feeding the Clause

  • Confirm the data type of the variable used in TOP (@N) or FETCH NEXT @N ROWS ONLY — it must be a non-negative integer (INT or BIGINT).
  • Add a validation check before execution, for example:
  IF @N IS NULL OR @N < 0 SET @N = 0;
  • Ensure no string concatenation or implicit conversion is passing a non-numeric or oversized value into the clause.

Step 3: Correct the Query Syntax

  • Rewrite the clause to explicitly cast and bound the value, e.g. TOP (CAST(@N AS INT)).
  • If using OFFSET/FETCH, ensure OFFSET is non-negative and FETCH NEXT is a positive literal or variable, since negative paging offsets are not permitted in SQL Server 2025.
  • Test the corrected query in SQL Server Management Studio (SSMS) 21 or Azure Data Studio against a non-production database first.

Step 4: Apply Fixes to Stored Procedures or ORM-Generated Queries

  • If the query originates from an ORM (Entity Framework, Dapper, etc.), inspect the generated SQL via SQL Server Profiler or Extended Events to confirm the parameter value being sent.
  • Update application-layer pagination logic to enforce minimum/maximum bounds before the request reaches SQL Server.
  • Redeploy the corrected stored procedure using ALTER PROCEDURE and recompile with sp_recompile to clear any cached bad execution plans.

Step 5: Restart Services If Plan Caching Persists the Error

  • If the error continues despite query fixes, clear the procedure cache: DBCC FREEPROCCACHE;
  • Restart the SQL Server service via Services.msc (Windows Server 2025 / Windows 11) or net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Alternative or Verification Steps

  • Re-run the corrected query or stored procedure with boundary test values (0, 1, NULL, and a large integer) to confirm Error 1014 no longer appears.
  • If the issue persists only under load, enable Query Store (ALTER DATABASE [YourDB] SET QUERY_STORE = ON;) to capture and compare execution plans for the failing query across different parameter values.

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

Troubleshooting Guide: SQL Server Error 1013

Why This Error Happens

Error 1013 occurs when a Transact-SQL query references two or more tables, views, or derived tables in the FROM clause that resolve to the same exposed name, typically because the same table is joined to itself or multiple objects share an identical base name across different schemas. SQL Server’s query parser cannot distinguish between these objects when building the execution plan, since each object in a FROM clause must have a unique identifier within that query scope. This commonly happens after schema refactoring, self-joins, or when copy-pasted query logic unintentionally duplicates a table reference without updating its alias.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Objects in the Query

  • Open the failing query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact FROM clause referenced in the error message.
  • Check the error text for the two object names in quotes (e.g., "dbo.Orders" and "dbo.Orders") to confirm they are indeed duplicates.
  • Run sp_helptext or review the stored procedure/view definition if the error originates from a database object rather than an ad-hoc query.

Step 2: Add Correlation Names (Table Aliases)

  • Edit the query to assign unique aliases to each instance of the repeated object, for example: FROM dbo.Orders AS o1 JOIN dbo.Orders AS o2 ON o1.ParentID = o2.OrderID.
  • Update all column references in the SELECT, WHERE, JOIN, and ORDER BY clauses to use the new alias prefixes (e.g., o1.OrderID, o2.CustomerID).
  • Save the corrected script and re-execute it in a test environment before deploying to production.

Step 3: Check for Cross-Schema or Cross-Database Naming Collisions

  • Verify whether two different schemas (e.g., Sales.Orders and Archive.Orders) are being referenced without schema qualifiers, causing SQL Server to treat them as the same exposed object.
  • Explicitly qualify each object with its schema name in the FROM clause to remove ambiguity.
  • Use SELECT * FROM sys.tables WHERE name = 'Orders' to confirm how many objects share that base name across the database.

Step 4: Review Dynamic SQL or ORM-Generated Queries

  • If the query is generated by an application, ORM (like Entity Framework), or dynamic SQL string in a stored procedure, inspect the generated T-SQL output using SQL Server Profiler or Extended Events.
  • Correct the query-building logic in the application code to always inject unique aliases when the same table is referenced more than once.

Step 5: Validate Views and Nested Subqueries

  • If the error originates inside a view or derived table, expand the nested query logic and confirm that subquery aliases don’t collide with outer-query table names.
  • Rename any derived table aliases that conflict with existing table or view names in the same scope.

Alternative or Verification Steps

  • Re-run the corrected query in SSMS and confirm it executes without throwing Error 1013; also check the Execution Plan tab to ensure both object instances now appear as distinct nodes.
  • If the issue persists in a complex stored procedure, use sp_depends or the Database Engine Tuning Advisor to map all object dependencies and locate any remaining unaliased duplicate references.

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

Troubleshooting Guide: SQL Server Error 1012

Why This Error Happens

This error occurs when a Transact-SQL query assigns a correlation name (alias) to a table that is identical to the exposed name of another table already referenced in the same FROM clause. SQL Server requires every exposed name within a query scope to be unique so the query optimizer can correctly resolve column references without ambiguity. This is purely a T-SQL syntax/logic issue in the query batch, stored procedure, or view definition rather than a server configuration or permissions problem.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact query text from the error message or from SQL Server Management Studio (SSMS) output.
  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025 to find the session and statement that triggered Error 1012.
  • Note the two conflicting names listed in the %.*ls placeholders within the error text.

Step 2: Review the FROM Clause for Duplicate Aliases

  • Open the query in SSMS and locate every table reference in the FROM and JOIN clauses.
  • Look for a case like FROM Orders AS Customers, Customers where the alias Customers duplicates an existing table’s exposed name.
  • Pay special attention to self-joins (e.g., FROM Employees e1, Employees e2) where aliases are required but may have been omitted or mistyped.

Step 3: Rename the Conflicting Alias

  • Edit the query to assign a distinct, descriptive alias to each table instance.
  • Example fix:
  SELECT e1.Name, e2.Name AS ManagerName
  FROM Employees AS e1
  JOIN Employees AS e2 ON e1.ManagerID = e2.EmployeeID;
  • Ensure all column references elsewhere in the query (SELECT, WHERE, GROUP BY) are updated to use the new alias names.

Step 4: Update Dependent Objects

  • If the faulty query resides inside a stored procedure, view, or function, use ALTER PROCEDURE, ALTER VIEW, or ALTER FUNCTION in SSMS to redeploy the corrected definition.
  • Search for the same alias pattern across other scripts using SSMS’s “Find in Files” or sp_helptext to prevent recurrence in related objects.

Step 5: Re-execute and Validate

  • Run the corrected query in a test environment on Windows 11 or Windows Server 2025 against a non-production database copy first.
  • Confirm no Error 1012 appears and the result set returns expected rows.

Alternative or Verification Steps

  • Execute the query with SET PARSEONLY ON; in SSMS to quickly validate syntax without full execution, confirming the alias conflict is resolved.
  • If the error persists in a complex query with multiple subqueries, use SELECT * FROM sys.dm_exec_describe_first_result_set(N'your_query_text', NULL, 0); to help pinpoint exactly which nested scope still has the duplicate exposed name.

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

Troubleshooting Guide: SQL Server Error 1011 — Duplicate Correlation Name in FROM Clause

Why This Error Happens

This error occurs when a Transact-SQL query references the same table alias (correlation name) more than once within a single FROM clause, which SQL Server’s parser cannot resolve since each alias must be unique within its query scope. It typically results from copy-paste mistakes when joining multiple tables, nested subqueries reusing an outer alias name, or self-joins where the same table is referenced twice without distinct aliases. This is a query authoring issue rather than a server configuration or permissions problem, so it will occur consistently on any SQL Server 2025 instance regardless of the underlying Windows Server 2025 or Windows 11 environment.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open the query that triggered Error 1011 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Note the exact alias name reported in the error message (e.g., t1, o, emp).
  • Check the entire FROM clause, including any JOIN, subquery, or CTE (Common Table Expression) blocks, since the duplicate may span across nested logic.

Step 2: Locate Duplicate Alias Usage

  • Use Ctrl+F in SSMS to search for every instance of the reported alias name within the query text.
  • Pay close attention to self-joins, such as FROM Employees e JOIN Employees e ON ..., where the same table is joined to itself without a unique second alias.
  • Inspect derived tables and subqueries that may unintentionally reuse an alias already declared in the outer query scope.

Step 3: Rename Conflicting Aliases

  • Assign a unique alias to each table reference, for example changing the second instance to e2 in a self-join: FROM Employees e JOIN Employees e2 ON e.ManagerID = e2.EmployeeID.
  • Update all corresponding column references throughout the SELECT, WHERE, and ORDER BY clauses to match the newly renamed alias.
  • Save the corrected script and re-run it against the database to confirm the parser accepts the updated FROM clause.

Step 4: Validate Nested and Dynamic SQL

  • If the query is generated dynamically (via sp_executesql or string concatenation in an application layer), review the code logic that builds the SQL string for alias reuse bugs.
  • Add logging or print the final generated SQL string before execution to visually inspect for duplicate aliases prior to sending it to SQL Server.

Alternative or Verification Steps

  • Execute the corrected query directly in SSMS against a test database to confirm Error 1011 no longer appears and results return as expected.
  • If using an ORM (Object-Relational Mapper) or reporting tool that auto-generates SQL, check for a known bug or update, and manually override the generated query if the tool is injecting duplicate aliases.

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

Troubleshooting Guide: SQL Server Error 1009 – “DEFAULT Is Not Allowed in DBCC Commands”

Why This Error Happens

This error occurs when a DBCC command is executed using invalid or unsupported syntax, specifically attempting to pass the DEFAULT keyword as a parameter where SQL Server 2025 expects an explicit value, filegroup name, or omission of the parameter entirely. This is typically caused by legacy scripts, maintenance plans, or third-party tools that were written for older SQL Server versions and have not been updated to reflect syntax changes or deprecations in the DBCC command parser. It can also occur if a copy-pasted script from documentation or a forum contains a placeholder (DEFAULT) that was never replaced with an actual value.

Step-by-Step Resolution Guide

Step 1: Identify the Offending DBCC Command

  • Open SQL Server Management Studio (SSMS) and check the Activity Monitor or SQL Server Error Log for the exact statement that triggered Error 1009.
  • Review any SQL Agent Job steps, maintenance plans, or automated scripts scheduled to run DBCC commands (e.g., DBCC CHECKDB, DBCC SHRINKFILE, DBCC CHECKFILEGROUP).
  • Look specifically for syntax resembling DBCC SHRINKFILE(N'filename', DEFAULT) or similar constructs using the DEFAULT keyword.

Step 2: Correct the DBCC Syntax

  • Replace the DEFAULT keyword with the actual required value. For example, change DBCC SHRINKFILE(N'MyData', DEFAULT) to a specific target size, such as DBCC SHRINKFILE(N'MyData', 10).
  • If DEFAULT was used to indicate “no size specified,” simply omit the parameter entirely rather than typing the word DEFAULT, as SQL Server 2025 strictly validates parameter syntax.
  • Save the corrected script to C:\Scripts\SQLMaintenance\ or your organization’s designated script repository for version control.

Step 3: Update Legacy Scripts and Maintenance Plans

  • Open SQL Server Agent in SSMS and navigate to Jobs > [Job Name] > Steps.
  • Edit any job step containing deprecated DBCC syntax and apply the corrected command from Step 2.
  • If using a Maintenance Plan, open it in the Maintenance Plan Designer and manually inspect the “Check Database Integrity” or “Shrink Database” tasks for auto-generated DEFAULT parameters.

Step 4: Test the Corrected Command in a Non-Production Environment

  • Execute the revised DBCC command against a test or staging instance of SQL Server 2025 first.
  • Confirm no syntax errors (Error 1009 or otherwise) are returned in the Messages pane of SSMS.
  • Check the Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for any residual warnings tied to Event ID 1009.

Alternative or Verification Steps

  • Re-run the corrected DBCC command in production during a maintenance window and confirm it completes successfully without raising Error 1009 in the SQL Server Error Log.
  • If the error persists, run DBCC HELP ('DBCC_COMMAND_NAME') in SSMS to view the current supported syntax for that specific command in SQL Server 2025, as parameter requirements may have changed from previous versions.

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

Troubleshooting Guide: SQL Server Error 1010 – “Invalid Escape Character ‘%.*ls'”

Why This Error Happens

This error occurs when SQL Server’s T-SQL parser encounters an invalid or unsupported escape character sequence, typically within a LIKE clause, a string literal, or a query that uses the ESCAPE keyword incorrectly. It is often triggered by malformed queries generated by ORMs, linked server queries, or scripts migrated from other database platforms (like MySQL or PostgreSQL) that use different escape syntax. Corrupted collation settings or incompatible client drivers communicating with SQL Server 2025 can also cause the parser to misinterpret a valid character as an escape sequence.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log via SSMS or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to find the exact statement that triggered the event.
  • Use SQL Server Profiler or Extended Events (xEvents) to capture the specific batch text associated with Error 1010.
  • Look specifically for LIKE clauses containing stray percent (%), underscore (_), or bracket ([) characters.

Step 2: Correct the T-SQL Syntax

  • Ensure that any literal special character in a LIKE clause is explicitly defined using the ESCAPE keyword.
  • Example of a fix: Change WHERE Column LIKE '%50%\%' to WHERE Column LIKE '%50%!%' ESCAPE '!'.
  • Verify that the escape character defined (e.g., ! or \) is a single character and is not null.

Step 3: Validate Client Driver Compatibility

  • Navigate to Control Panel > ODBC Data Sources (64-bit) and verify the driver version connecting to SQL Server 2025.
  • Update the client machine to use the latest Microsoft ODBC Driver 18 for SQL Server or the updated OLE DB Driver, as older drivers may incorrectly encode string literals before sending them to the server.
  • Restart the “SQL Server” service via services.msc after updating connectivity components on the Windows Server 2025 host.

Step 4: Check Database Collation Settings

  • Run SELECT DATABASEPROPERTYEX('YourDB', 'Collation'); to check for collation mismatches between the database and the server instance.
  • If a mismatch exists between a Linked Server (e.g., Azure SQL) and the local SQL Server 2025 instance, align the collations to prevent character set misinterpretation.

Alternative or Verification Steps

  • Verification: Re-run the specific query isolated in Step 1 directly in a new SSMS query window. If the query executes without the “Invalid escape character” error (1010), the syntax correction was successful.
  • Alternative: If the error persists only on a specific application (not in SSMS), bypass the issue temporarily by using CHARINDEX() or PATINDEX() functions instead of LIKE...ESCAPE to search for the string pattern, as these functions handle special characters differently.

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

Troubleshooting Guide: SQL Server Error 1008

Why This Error Happens

Error 1008 occurs when a SELECT statement attempts to use ORDER BY with an ordinal position (e.g., ORDER BY 1) while also combining that position with a variable in the same expression. SQL Server’s query parser cannot resolve a dynamic variable against a static column position because ordinal references must be resolved at compile time, not runtime. This typically happens in dynamically constructed queries or stored procedures where developers mistakenly mix positional sorting syntax with parameterized logic.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the exact stored procedure, view, or application query referenced in the error message using SQL Server Management Studio (SSMS).
  • Check the SQL Server Error Log via SSMS > Management > SQL Server Logs or query sys.dm_exec_query_stats to find the specific query text causing the failure.
  • Look specifically for an ORDER BY clause containing a mix of numbers and variables, such as ORDER BY @SortColumn + 1.

Step 2: Rewrite the ORDER BY Clause

  • Replace the invalid ordinal/variable hybrid expression with a direct column name reference.
  • If dynamic sorting is required, use a CASE statement instead of positional variables. For example, replace:
  ORDER BY @SortCol

with:

  ORDER BY 
    CASE WHEN @SortCol = 1 THEN ColumnA END,
    CASE WHEN @SortCol = 2 THEN ColumnB END
  • Ensure the CASE statement explicitly references column names rather than performing arithmetic on the ordinal position itself.

Step 3: Validate Application Code (If Using Dynamic SQL)

  • If the query originates from a .NET or Java application connecting to SQL Server 2025, check the data access layer for string concatenation errors that might be injecting a variable into the ordinal position.
  • Open the application’s data layer (e.g., C:\inetpub\wwwroot\YourApp\DataAccess\) and search for ORDER BY string builders.
  • Modify the code to pass the full column name as a string parameter rather than an integer variable intended for positional sorting.

Step 4: Test the Corrected Syntax

  • Run the modified query directly in SSMS against a test database to confirm the parser accepts the syntax without throwing Error 1008.
  • Check the Messages tab in SSMS to ensure the query returns “Command(s) completed successfully” rather than a syntax exception.

Alternative or Verification Steps

  • Verification: Execute the stored procedure with the exact parameters used by the failing application instance; successful execution and correct data ordering confirm the fix.
  • Alternative: If modifying the ORDER BY logic is not immediately feasible, implement a temporary wrapper view that pre-sorts the data using static logic, bypassing the need for dynamic ordinal variables in the primary query.

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

Troubleshooting Guide: SQL Server Error 1006 — “CREATE TRIGGER contains no statements”

Why This Error Happens

This error occurs when SQL Server parses a CREATE TRIGGER statement and finds a valid BEGIN...END block (or trigger body) that is either empty or contains only comments, whitespace, or a batch separator (GO) placed too early. SQL Server requires at least one executable T-SQL statement inside the trigger body to compile the object successfully. This is typically caused by a scripting error, a failed deployment template, or a corrupted migration script that stripped out the trigger logic during generation.

Step-by-Step Resolution Guide

Step 1: Review the Trigger Definition Script

  • Open the .sql file or the deployment script containing the CREATE TRIGGER statement in SSMS (SQL Server Management Studio) or Azure Data Studio.
  • Locate the BEGIN and END keywords and visually confirm there is at least one valid statement (e.g., INSERT, UPDATE, RAISERROR, or PRINT) between them.
  • Check for a misplaced GO command immediately after BEGIN, as this splits the batch and leaves the trigger body empty.

Step 2: Correct the Syntax and Add Logic

  • If the trigger is genuinely meant to be a placeholder, insert a RETURN; statement or a no-op comment followed by SELECT 1; to satisfy the parser.
  • If the trigger was auto-generated, re-run the source ORM or migration tool (e.g., Entity Framework, Flyway) to regenerate the trigger body with the correct business logic included.
  • Example of a valid minimal fix:
CREATE TRIGGER trg_Example ON dbo.YourTable AFTER INSERT AS BEGIN SET NOCOUNT ON; END;

Step 3: Validate File Encoding and Source Control

  • Check the source file in your version control system (Git) for a previous commit where the trigger body logic may have been accidentally deleted or overwritten.
  • Verify the file encoding is UTF-8 or UTF-8 with BOM; corrupted encoding on Windows Server 2025 can sometimes cause SSMS to misinterpret line breaks within the BEGIN...END block, effectively “hiding” code from the parser.
  • Re-save the script using SSMS’s native “Save As” function to ensure clean formatting before re-execution.

Step 4: Execute and Compile

  • Run the corrected script against the target database using sqlcmd or the SSMS Query Editor.
  • Command line example: sqlcmd -S localhost -d YourDatabase -i C:\Scripts\FixTrigger.sql

Alternative or Verification Steps

  • Verify: Run SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('trg_Example'); to confirm the trigger body now contains the expected T-SQL logic rather than an empty string.
  • Alternative: If the trigger is no longer needed, bypass the error entirely by dropping the object using DROP TRIGGER trg_Example; instead of attempting to repair a legacy or unused script.

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

Troubleshooting Guide: SQL Server Error 1007 — Numeric Out of Range (Maximum Precision 38)

Why This Error Happens

This error occurs when an arithmetic operation, conversion, or aggregation produces a numeric or decimal value that exceeds SQL Server’s maximum supported precision of 38 digits. It is commonly triggered by implicit data type conversions, multiplication of two high-precision decimal columns, or imported data containing values that overflow the target column’s defined precision and scale. This is a data/schema design issue rather than a server configuration or permissions problem, meaning it will persist until the underlying query logic or column definitions are corrected.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Operation

  • Capture the exact T-SQL statement from the application log or SQL Server error log that triggered Error 1007.
  • Use SELECT @@ERROR or enable Extended Events (sp_server_diagnostics) to trace the exact line and variable involved.
  • Check for implicit conversions by running the query with SET ARITHABORT ON to surface precision issues early.

Step 2: Review Column and Variable Precision/Scale Definitions

  • Run sp_help 'YourTableName' or query sys.columns joined with sys.types to inspect current DECIMAL(p,s) or NUMERIC(p,s) definitions.
  • Look specifically for multiplication or division operations where the resulting precision (p1 + p2 + 1) can exceed 38.
  • Example: DECIMAL(30,10) * DECIMAL(20,5) will mathematically exceed the 38-digit ceiling and must be refactored.

Step 3: Adjust Data Types or Cast Explicitly

  • Reduce unnecessary precision/scale on source columns where business logic allows (e.g., DECIMAL(38,10) → DECIMAL(28,6)).
  • Add explicit CAST or CONVERT statements in the query to control intermediate precision before the final calculation.
  • Example fix: CAST(ColumnA AS DECIMAL(18,4)) * CAST(ColumnB AS DECIMAL(18,4)).

Step 4: Validate Source Data for Import/ETL Jobs

  • If the error originates from SSIS, Data Factory, or BULK INSERT jobs, check the source file/dataset for abnormally large numeric strings (e.g., scientific notation artifacts or corrupted exports).
  • Add data validation or truncation logic in the ETL pipeline to reject or round values before insertion into SQL Server 2025.

Step 5: Apply Compatibility Level and Patch Checks

  • Confirm the database compatibility level is correctly set for SQL Server 2025 via SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'.
  • Ensure the latest Cumulative Update (CU) for SQL Server 2025 is installed on Windows Server 2025/Windows 11, as early builds had known precision-handling bugs in the Tabular Data Stream (TDS) layer.

Alternative or Verification Steps

  • Re-run the original query or ETL job after applying the CAST/CONVERT fix and confirm Error 1007 no longer appears in sys.dm_exec_requests or the SQL Server error log.
  • As a workaround, if full precision isn’t critical, use TRY_CONVERT instead of CONVERT to gracefully return NULL instead of throwing a hard error, allowing the application to handle edge cases without crashing.

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

Why This Error Happens

This error occurs when a script attempts to create or execute a “numbered” stored procedure using the legacy ;number syntax (e.g., procedure_name;40000), and the value provided falls outside the valid 16-bit integer range of 1 to 32767. It is frequently triggered by migration scripts or ORM-generated code that auto-increments procedure group numbers without bounds checking, or by corrupted metadata in sys.objects referencing an invalid group number. Since SQL Server 2025 continues to support this deprecated feature for backward compatibility, any script ported from older environments can surface this error if the numbering logic was flawed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Script or Procedure Call

  • Open SQL Server Management Studio (SSMS) and locate the exact line number referenced in the error message (Line %d).
  • Search the script for the semicolon-numbering pattern: CREATE PROCEDURE dbo.MyProc;<number>.
  • Check if the number is dynamically generated via a loop or variable (common in automated deployment scripts).

Step 2: Correct or Remove the Invalid Numbering

  • If the number exceeds 32767, remove the numbered suffix entirely and create the procedure as a standalone object (e.g., dbo.MyProc instead of dbo.MyProc;5).
  • If the application logic relies on grouped procedures, re-architect it to use separate, uniquely named stored procedures instead of the legacy numbering system, as Microsoft has fully deprecated this feature path.
  • Update any deployment/migration tooling (SSDT, DACPAC scripts, Liquibase, Flyway) to strip semicolon-numbering before execution.

Step 3: Validate Database Metadata for Corruption

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out metadata corruption causing a malformed object.
  • Query sys.objects and sys.procedures to check for orphaned or mismatched numbered procedure entries:
SELECT name, object_id, type_desc 
FROM sys.objects 
WHERE name LIKE '%;%';
  • Drop and recreate any procedure entries that show inconsistent numbering artifacts.

Step 4: Restart the SQL Server Service (If Metadata Was Cached)

  • 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 cached execution plans or compiled procedure groups that may still reference the invalid number.

Alternative or Verification Steps

  • Re-run the original script after correction; the batch should compile without raising Error 1005, and the procedure should appear correctly under Programmability > Stored Procedures in SSMS Object Explorer.
  • If the error persists, extract the script into smaller isolated batches and execute line-by-line to confirm which specific CREATE PROCEDURE statement is still passing an out-of-range value.

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

Troubleshooting Guide: SQL Server Error 1004 — Invalid Column Prefix

Why This Error Happens

This error occurs when a T-SQL query references a column using a table alias or table name prefix (e.g., TableName.ColumnName) that doesn’t match any table, view, or alias defined in the FROM clause of that query scope. It commonly arises from typos in alias names, copy-pasted query fragments where the source table was renamed or removed, or incorrect scoping in subqueries and CTEs where the outer alias is mistakenly referenced inside an inner query. Additionally, this can surface after a schema migration or application update where column references were not properly updated to match new table aliases.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Line Number

  • Check the SQL Server error log or the application’s exception trace to capture the full query text associated with Error 1004.
  • Use SQL Server Management Studio (SSMS) to run the query in isolation and note the exact line/column prefix mentioned in the error message (e.g., TableAlias.ColumnName).
  • If the error originates from a stored procedure, run sp_helptext 'ProcedureName' to review the full procedure definition.

Step 2: Validate Table Aliases and FROM Clause Scope

  • Confirm that every table prefix used in SELECT, WHERE, JOIN, or ON clauses has a matching alias or table name explicitly declared in the FROM clause of the same query block.
  • Pay special attention to nested subqueries and CTEs — an alias defined in an outer query is not visible inside an inner subquery unless explicitly joined or passed through.
  • Correct any mismatched aliases, for example changing SELECT o.OrderID FROM Orders ord to SELECT ord.OrderID FROM Orders ord.

Step 3: Check for Recent Schema or Application Changes

  • Review recent deployment logs or Git history for changes to views, stored procedures, or ORM-generated queries (e.g., Entity Framework, Hibernate) that may have altered table aliases.
  • If using an ORM, regenerate the data model or clear the query cache to ensure aliases match the current database schema.
  • Re-deploy or re-script affected stored procedures/views using SSMS’s “Script as ALTER” feature after fixing the alias references.

Step 4: Rebuild and Test the Corrected Query

  • Execute the corrected query directly in SSMS against a non-production copy of the database to confirm Error 1004 no longer appears.
  • Use SET SHOWPLAN_TEXT ON or the Execution Plan viewer to ensure the query compiles and resolves all table references correctly.

Alternative or Verification Steps

  • Re-run the original failing transaction or application workflow and confirm Error 1004 no longer appears in the SQL Server Error Log or Windows Event Viewer (Event ID 1004 under the Application log).
  • If the issue persists in a complex view or procedure, use sys.sql_expression_dependencies to trace all object dependencies and confirm no orphaned or renamed table references remain.

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

Troubleshooting Guide: SQL Server Error 1003 — “Line %d: %ls clause allowed only for %ls”

Why This Error Happens

This error occurs when a Transact-SQL statement uses a clause that is syntactically valid in SQL Server’s grammar but is restricted to a specific object type, context, or statement form that doesn’t match how it was used. It is a parser-level error, typically triggered by applying a clause (such as WITH CHECK OPTION, OUTPUT, or a partition-specific clause) to an object type that does not support it — for example, using a view-only clause against a table, or a table-valued function clause inside a scalar function definition. This is almost always caused by a scripting mistake, an outdated query template, or a migration script written for an older/different SQL Server edition that has since changed clause-compatibility rules in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Clause Flagged by the Parser

  • Open the error message in SSMS or the SQL Server error log and note the exact line number (%d) and clause name (%ls) reported.
  • Cross-reference the script against the object type (%ls) mentioned at the end of the message — this tells you what the clause is allowed for.
  • If running from a .sql deployment file, open it in a text editor with line numbers enabled (e.g., Notepad++ or VS Code) to jump directly to the offending line.

Step 2: Validate the Object Type Against the Clause Usage

  • Confirm whether the statement is being executed against a TABLE, VIEW, FUNCTION, or PROCEDURE — many clauses (like WITH CHECK OPTION) are valid only for views, not tables.
  • Check if the script was authored for an older SQL Server version (2017/2019) where clause restrictions were more lenient; SQL Server 2025 enforces stricter ANSI compliance.
  • Run the following to inspect object type directly from metadata:
SELECT name, type_desc FROM sys.objects WHERE name = 'YourObjectName';

Step 3: Correct the Script Syntax

  • Remove or relocate the clause to the correct statement type. For example, move WITH CHECK OPTION from a CREATE TABLE statement to the corresponding CREATE VIEW statement.
  • If using OUTPUT or OPTION(...) query hints, verify they are attached to INSERT, UPDATE, DELETE, or MERGE statements only — not SELECT-only views or inline table-valued functions.
  • Save the corrected script and re-run it in a non-production environment first (e.g., a dev instance on Windows 11) to confirm the parser accepts it.

Step 4: Rebuild or Redeploy Dependent Objects

  • If the error surfaced during a database migration or DACPAC deployment, regenerate the deployment script using SQL Server Data Tools (SSDT) targeting SQL Server 2025 compatibility level (170 or higher).
  • Check ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170; is applied before redeploying, since compatibility level affects some clause parsing behavior.

Step 5: Clear Cached Query Plans After the Fix

  • Run DBCC FREEPROCCACHE; on the affected database to ensure no stale, invalid execution plans referencing the old syntax remain cached.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if the issue persists after the script correction.

Alternative or Verification Steps

  • Re-execute the corrected script in SSMS and confirm no Error 1003 appears in the Messages tab; also check the SQL Server error log (ERRORLOG file, typically under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for recurrence.
  • As an alternative, use sys.dm_exec_describe_first_result_set or SET PARSEONLY ON before running the full script to catch syntax/clause errors early without executing the full batch.

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

Why This Error Happens

This error occurs when a T-SQL statement defines a column, variable, or cast operation with a length or precision value that falls outside the valid range supported by SQL Server 2025 (for example, a DECIMAL precision greater than 38, or a VARCHAR length exceeding 8000 without using MAX). It can also surface due to corrupted or outdated database scripts generated by third-party tools that haven’t been updated for SQL Server 2025 syntax changes. Occasionally, this is triggered by a migration script carrying over legacy precision values from an older SQL Server instance that are no longer compatible.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Line and Statement

  • Open the exact script referenced in the error log; the error message explicitly states Line %d, so navigate directly to that line number in SQL Server Management Studio (SSMS).
  • Look for data type declarations such as DECIMAL(p, s), NUMERIC(p, s), VARCHAR(n), NVARCHAR(n), or CHAR(n).
  • Confirm whether the precision or length value is a hardcoded number or a dynamically generated variable (common in auto-generated migration scripts).

Step 2: Validate Against SQL Server 2025 Supported Ranges

  • For DECIMAL/NUMERIC: precision must be between 1 and 38; scale must be between 0 and the precision value.
  • For VARCHAR/CHAR/BINARY: length must be between 1 and 8000, or use the MAX keyword for larger values (up to 2GB).
  • For NVARCHAR: length must be between 1 and 4000, or use MAX.
  • Correct any value outside these bounds directly in the script (e.g., change DECIMAL(40,2) to DECIMAL(38,2)).

Step 3: Check for Legacy Compatibility Level Conflicts

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName'; in SSMS.
  • If the compatibility level is set below 170 (SQL Server 2025 default), some legacy precision behaviors may conflict with new engine validation.
  • Update it using: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Re-run the script after updating compatibility mode.

Step 4: Rebuild or Regenerate the Script Using Native Tools

  • If the script was generated by a third-party ORM or migration tool, regenerate it using SSMS’s built-in “Generate Scripts” wizard to ensure native SQL Server 2025 syntax compliance.
  • Navigate to: SSMS > Object Explorer > Right-click Database > Tasks > Generate Scripts.
  • Ensure the “Script for Server Version” option under Advanced settings is explicitly set to SQL Server 2025.

Step 5: Restart the SQL Server Service

  • After applying script corrections, restart the instance to clear any cached query plans referencing the invalid definitions.
  • Open services.msc on Windows Server 2025/Windows 11, locate SQL Server (MSSQLSERVER), right-click, and select Restart.

Alternative or Verification Steps

  • Re-execute the corrected script in SSMS and confirm it completes with “Command(s) completed successfully” with no Error 1001 in the Activity Log or Event Viewer (Windows Logs > Application).
  • If the error persists, use DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; to rule out underlying schema corruption that may be feeding invalid metadata into the script generator.

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

Troubleshooting Guide: Error 1002 – “Specified Scale %d Is Invalid” in SQL Server 2025

Why This Error Happens

This error occurs when a Transact-SQL statement defines a numeric, decimal, or datetime2/time data type with a scale value that falls outside the permissible range (typically 0 to 38, depending on the data type). It is commonly triggered by manually scripted DDL statements, migrated code from older applications, or ORM-generated schemas that pass an incorrect precision/scale pair. Corrupted or mismatched schema definitions during database migration to SQL Server 2025 can also propagate invalid scale values into automated deployment scripts.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Line and Statement

  • Note the exact “Line %d” reference provided in the error message from SSMS or the application log.
  • Open the corresponding .sql script or stored procedure definition in SQL Server Management Studio (SSMS) 21 on Windows Server 2025 / Windows 11.
  • Locate the DECIMAL(p,s), NUMERIC(p,s), DATETIME2(s), or TIME(s) declaration on that line.

Step 2: Correct the Precision and Scale Values

  • For DECIMAL/NUMERIC types, ensure the scale value is less than or equal to the precision value and does not exceed 38 (e.g., DECIMAL(18,2) is valid; DECIMAL(18,40) is not).
  • For DATETIME2, DATETIMEOFFSET, and TIME types, ensure the scale is between 0 and 7 (e.g., DATETIME2(7) is the maximum allowed fractional seconds precision).
  • Update the script using a text editor or directly in SSMS Query Editor, then save the corrected file to C:\Scripts\SQL\ or your deployment repository.

Step 3: Re-run the Script in a Validation Environment

  • Execute the corrected script against a non-production or staging instance first using sqlcmd -S <ServerName> -i "C:\Scripts\SQL\CorrectedScript.sql".
  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to confirm Error 1002 no longer appears.

Step 4: Audit Related Scripts and ORM Mappings

  • If the error originated from an Entity Framework, Hibernate, or other ORM-generated migration, review the model’s column attributes (e.g., [Column(TypeName = "decimal(18,2)")]) for incorrect scale configurations.
  • Regenerate the migration script after correcting the model definitions to prevent recurrence across future deployments.

Alternative or Verification Steps

  • Verify the fix by querying INFORMATION_SCHEMA.COLUMNS or sys.columns joined with sys.types on the affected table to confirm the precision and scale values now match your intended schema design.
  • If the error persists despite corrections, run DBCC CHECKDB to rule out metadata corruption, and consider restoring the affected database object from a known-good backup taken prior to the schema change.

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

Troubleshooting Guide: Error 998 – Database Does Not Exist in Server

Why This Error Happens

This error occurs when SQL Server 2025 cannot locate the specified database on the connected instance, typically because the database name was misspelled, the database was detached, dropped, or offline, or the connection string is pointing to the wrong SQL Server instance entirely. It can also happen when a user is connecting to a different instance (such as a default instance instead of a named instance) where the database genuinely does not reside, or when the database exists but the login lacks visibility permissions (CONNECT ANY DATABASE or VIEW ANY DATABASE) causing it to appear nonexistent.

Step-by-Step Resolution Guide

Step 1: Verify the Exact Database Name and Instance

  • Open SQL Server Management Studio (SSMS) 2025 and connect to the target instance.
  • Run SELECT name, state_desc FROM sys.databases; to confirm the exact spelling and current state of the database.
  • Check that your connection string or SSMS login is pointing to the correct instance name (e.g., SERVERNAME\INSTANCENAME vs. just SERVERNAME).
  • Confirm there are no trailing spaces or case-sensitivity issues if the server collation is case-sensitive.

Step 2: Check Database State and File Availability

  • If the database shows as OFFLINE, RESTORING, or SUSPECT in sys.databases, bring it online using:
    ALTER DATABASE [YourDBName] SET ONLINE;
  • Verify the physical .mdf and .ldf files exist under the expected path, typically:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\
  • If files are missing or the database was detached, reattach it using:
    CREATE DATABASE [YourDBName] ON (FILENAME = 'C:\Path\YourDB.mdf') FOR ATTACH;

Step 3: Confirm Login Permissions and Database Visibility

  • Ensure the login being used has at least CONNECT permission on the database or is mapped via Security > Logins > User Mapping in SSMS.
  • Grant visibility if the database is hidden due to security policy:
    GRANT VIEW ANY DATABASE TO [YourLogin];
  • Restart the SQL Server service via services.msc (service name: SQL Server (MSSQLSERVER)) after permission changes to refresh cached metadata.

Step 4: Validate Network and Instance Routing

  • If using a named instance, confirm SQL Server Browser service is running (services.msc → SQL Server Browser → Status: Running).
  • Check that the client connection string uses the correct port (default 1433) or instance alias configured in SQL Server Configuration Manager.
  • Use sqlcmd -S ServerName\InstanceName -Q "SELECT @@SERVERNAME" from Command Prompt to confirm you’re hitting the intended server.

Alternative or Verification Steps

  • Run sqlcmd -S YourServer -d YourDatabase -Q "SELECT DB_NAME()" to confirm the connection resolves to the correct database without error.
  • If the issue persists, restore the database from a recent backup using RESTORE DATABASE [YourDBName] FROM DISK = 'C:\Backups\YourDB.bak' WITH REPLACE; to rule out corruption or accidental deletion.

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

Troubleshooting Guide: Error 997 — “Failed to get the update lock on database”

Why This Error Happens

This error occurs when SQL Server attempts an asynchronous I/O operation (typically during database locking for DDL changes, backups, or recovery) but the overlapped I/O request cannot complete immediately, and Windows returns “ERRORIOPENDING” in a context SQL Server doesn’t expect. It is frequently triggered by antivirus or endpoint protection software intercepting file handles on the MDF/LDF files, outdated storage drivers, or a filter driver (like backup or replication software) holding a lock on the database files. In some cases, it stems from insufficient permissions for the SQL Server service account on the database file directory, preventing the update lock handshake from completing cleanly.

Step-by-Step Resolution Guide

Step 1: Exclude SQL Server Files from Antivirus Scanning

  • Open Windows Security or your third-party AV console on the Windows Server 2025 / Windows 11 host.
  • Add exclusions for *.mdf, *.ldf, *.ndf file extensions.
  • Exclude the SQL Server binary directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Also exclude the sqlservr.exe process itself from real-time behavioral scanning.

Step 2: Verify Service Account Permissions

  • Open File Explorer, navigate to the database file directory, right-click → Properties → Security.
  • Confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER or a custom domain service account) has Full Control on the data/log folder.
  • Use PowerShell to quickly audit permissions:
  Get-Acl "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA" | Format-List
  • Reapply permissions if inheritance was broken after a server migration or restore.

Step 3: Update Storage and Filter Drivers

  • Open Device Manager and check storage controller drivers (especially for SAN/iSCSI or virtualized disks under Hyper-V).
  • Update to the latest WHQL-certified drivers from the vendor (Dell, HPE, Broadcom, etc.).
  • Run fltmc filters in an elevated Command Prompt to review loaded filter drivers; temporarily unload suspicious third-party backup or replication filters to isolate the conflict.

Step 4: Check for Blocking Processes Holding the Database Lock

  • Run sp_who2 or query sys.dm_tran_locks in SSMS to identify sessions holding locks on the affected database.
  • Check if a third-party backup tool (e.g., Veeam, Commvault) has an active VSS snapshot session against the SQL instance.
  • Kill the blocking session with KILL <session_id> only after confirming it is safe to do so.

Step 5: Apply Latest SQL Server 2025 Cumulative Update

  • Open SQL Server Configuration Manager and verify the current build number under SQL Server Services.
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as known I/O completion bugs are frequently patched.
  • Restart the SQL Server service after installation via net stop MSSQLSERVER && net start MSSQLSERVER.

Alternative or Verification Steps

  • After applying fixes, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS to confirm no lock or consistency errors remain.
  • If Error 997 persists, try taking the database offline and back online (ALTER DATABASE [YourDB] SET OFFLINE; ALTER DATABASE [YourDB] SET ONLINE;) during a maintenance window to force a clean lock re-acquisition.

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

Troubleshooting Guide: Error 996 – Disabled Columnstore Index Cannot Be Upgraded

Why This Error Happens

This error occurs because a columnstore index was left in a disabled state (often from a prior maintenance operation, bulk load failure, or manual ALTER INDEX ... DISABLE command) before a SQL Server version upgrade or database engine migration was performed. SQL Server 2025’s upgrade process cannot rebuild or validate the internal structure of a disabled columnstore index because the underlying row groups and delta store metadata are not in a consistent, readable state. Since the upgrade routine requires all indexes to be either active or droppable to rewrite catalog metadata, it halts and raises Error 996 instead of silently skipping the broken structure.

Step-by-Step Resolution Guide

Step 1: Identify the Disabled Columnstore Index

  • Connect to the instance using SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Run the following query to locate all disabled indexes prior to upgrade:
SELECT t.name AS TableName, i.name AS IndexName, i.type_desc, i.is_disabled
FROM sys.indexes i
JOIN sys.tables t ON i.object_id = t.object_id
WHERE i.is_disabled = 1 AND i.type_desc LIKE '%COLUMNSTORE%';
  • Note the exact schema, table, and index names returned.

Step 2: Rebuild or Drop the Disabled Index

  • If the index is needed, rebuild it to restore it to an active, upgradeable state:
ALTER INDEX [IndexName] ON [Schema].[TableName] REBUILD;
  • If the index is obsolete or was disabled intentionally and is no longer required, drop it instead:
DROP INDEX [IndexName] ON [Schema].[TableName];
  • Repeat this for every disabled columnstore index found in Step 1.

Step 3: Clear Residual Upgrade Blockers

  • On Windows Server 2025 / Windows 11, stop the SQL Server service via services.msc or net stop MSSQLSERVER.
  • Clear any cached setup bootstrap logs located at C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\Log\ to prevent the installer from reusing a stale pre-upgrade inventory.
  • Restart the SQL Server service with net start MSSQLSERVER before re-running Setup.exe for the upgrade.

Step 4: Re-Run the Upgrade Process

  • Launch SQL Server 2025 Setup again and select the “Upgrade” path for the affected instance.
  • Monitor the Summary.txt log under the Setup Bootstrap Log folder in real time to confirm Error 996 does not reappear.

Alternative or Verification Steps

  • After the upgrade completes, re-run the disabled-index query from Step 1; it should return zero rows, confirming no lingering disabled columnstore indexes remain.
  • If rebuilding fails due to corruption, run DBCC CHECKTABLE('[Schema].[TableName]') WITH DATA_PURITY to assess structural damage, then restore the table from the last known-good backup before retrying the upgrade.

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

Troubleshooting Guide: Error 994 – Index Disabled Due to Computed Column

Why This Error Happens

This warning occurs when a non-persisted computed column that underlies an index becomes unavailable for evaluation, typically because the computed column definition references a user-defined function, a schema-bound dependency, or a column collation that SQL Server 2025 can no longer deterministically resolve at index time. SQL Server automatically disables the index rather than risk serving stale or incorrect data from a computed value it cannot recalculate. This commonly surfaces after a schema change, an in-place upgrade to SQL Server 2025, or a database restore where the underlying column dependencies were altered or dropped.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Index and Computed Column

  • Run the following query to confirm which index and computed column triggered Error 994:
SELECT i.name AS IndexName, c.name AS ColumnName, c.is_persisted, cc.definition
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
JOIN sys.computed_columns cc ON c.object_id = cc.object_id AND c.column_id = cc.column_id
WHERE i.is_disabled = 1;
  • Note the definition column output — this reveals the expression causing the dependency failure.

Step 2: Check Column Determinism and Persistence Settings

  • Open SQL Server Management Studio (SSMS 21) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Verify whether the computed column is marked PERSISTED. Non-persisted columns relying on non-deterministic functions (e.g., GETDATE(), CLR functions without IsDeterministic = true) cannot support indexing.
  • If persistence is required, alter the column:
ALTER TABLE dbo.YourTable
ALTER COLUMN YourComputedColumn AS (Expression) PERSISTED;

Step 3: Rebuild the Disabled Index

  • Once the computed column dependency is corrected, rebuild the index rather than just re-enabling it:
ALTER INDEX [IndexName] ON dbo.YourTable REBUILD;
  • If the index was dropped during troubleshooting, recreate it explicitly using CREATE INDEX, specifying WITH (DROP_EXISTING = ON) if applicable.

Step 4: Validate Schema Dependencies (Windows Server 2025 Environment)

  • Confirm no orphaned schema-bound objects exist by running sp_depends or querying sys.sql_expression_dependencies.
  • On Windows Server 2025/Windows 11 hosts, ensure the SQL Server service account (check via services.msc) has not changed permissions on linked DLLs or CLR assemblies located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\, as restricted access can block function evaluation needed for deterministic checks.

Alternative or Verification Steps

  • Verify the fix by re-running the sys.indexes query from Step 1 and confirming is_disabled = 0 for the target index.
  • If the index remains disabled, as a fallback, drop the computed column dependency entirely and recreate the index on a persisted, deterministic alternative column to avoid future recurrence.

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

Why This Error Happens

This warning occurs when SQL Server 2025 attempts to upgrade database metadata or rebuild internal index structures during a version upgrade, but encounters an index that resides on a filegroup marked as READ_ONLY. Since the upgrade process (or an internal statistics/index maintenance rebuild) requires write access to modify the index’s internal page structure, it cannot complete the operation and instead disables the index rather than failing the entire upgrade. This typically happens when databases are migrated from older SQL Server versions with filegroups intentionally locked for archival or compliance purposes, and the read-only flag was not temporarily lifted before running the upgrade wizard.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Filegroup and Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to locate read-only filegroups tied to the disabled index:
  SELECT fg.name AS FilegroupName, fg.is_read_only, d.name AS DatabaseName
  FROM sys.filegroups fg
  JOIN sys.databases d ON d.database_id = DB_ID()
  WHERE fg.is_read_only = 1;
  • Cross-reference the filegroup name against the one mentioned in the warning message.

Step 2: Temporarily Set the Filegroup to READ_WRITE

  • In SSMS, execute the following T-SQL command (replace placeholders accordingly):
  ALTER DATABASE [YourDatabaseName] 
  MODIFY FILEGROUP [YourFilegroupName] READWRITE;
  • Ensure no other active transactions are locking the filegroup by checking sys.dm_tran_locks on Windows Server 2025.
  • Confirm the underlying .ndf or .mdf file is not set to “Read-only” at the Windows file system level (right-click the file in File Explorer > Properties > uncheck Read-only).

Step 3: Rebuild or Re-enable the Disabled Index

  • Run the index rebuild command to restore the index to a usable state:
  ALTER INDEX [YourIndexName] ON [YourSchema].[YourTable] REBUILD;
  • If the index was fully disabled (not just flagged), use:
  ALTER INDEX [YourIndexName] ON [YourSchema].[YourTable] REBUILD WITH (ONLINE = ON);

Step 4: Revert the Filegroup to READ_ONLY (If Required)

  • Once the upgrade and index rebuild complete successfully, restore the original read-only state for compliance or archival purposes:
  ALTER DATABASE [YourDatabaseName] 
  MODIFY FILEGROUP [YourFilegroupName] READONLY;
  • Re-run the SQL Server Upgrade Advisor or Setup Wizard to confirm no further warnings appear for this filegroup.

Alternative or Verification Steps

  • Verify the fix by querying sys.indexes and confirming is_disabled = 0 for the affected index:
  SELECT name, is_disabled FROM sys.indexes WHERE object_id = OBJECT_ID('YourSchema.YourTable');
  • If the filegroup must remain permanently read-only, consider migrating the affected table/index to a writable filegroup using CREATE INDEX ... WITH (DROP_EXISTING = ON) ON [NewFilegroup] before attempting future upgrades.

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

Troubleshooting Guide: SQL Server Error 993 – Redo Database Version Upgrade Step

Why This Error Happens

This message is logged when SQL Server 2025 performs a redo operation during database recovery and detects that the database’s internal version number needs to be upgraded as part of the Always On Availability Group synchronization or crash recovery process. It typically occurs after a SQL Server upgrade (e.g., moving from SQL Server 2022 to SQL Server 2025) when a secondary replica or a restored database is still running an older internal schema version and must be brought up to the current engine version during redo. While Error 993 itself is informational and confirms a successful version step-up, repeated or stalled occurrences usually indicate an interrupted upgrade, a corrupted transaction log, or mismatched binary versions between nodes in an Availability Group.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Patch Level Consistency

  • Run SELECT @@VERSION; on every node (primary and all secondaries) in the Availability Group.
  • Confirm all instances are running the identical SQL Server 2025 Cumulative Update (CU) build number.
  • If versions differ, apply the matching CU package from the Microsoft Update Catalog to bring all nodes in sync before restarting the SQL Server service.

Step 2: Check the SQL Server Error Log for Redo Completion

  • Open the error log via SSMS: Management > SQL Server Logs, or query directly:
  EXEC sys.xp_readerrorlog 0, 1, N'Redo';
  • Confirm that the message reports completion (from %d to %d showing the final target version) rather than repeating the same step number, which would indicate a stalled redo thread.
  • If the redo thread appears stuck, check the sys.dm_exec_requests DMV for the DB STARTUP or REDO wait type to confirm active progress.

Step 3: Validate Database File and Log Integrity

  • Take the affected database offline if it’s a standalone instance (not part of an AG), and run:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Inspect the physical .mdf/.ldf files located typically at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ for signs of disk-level corruption using chkdsk C: /f on Windows Server 2025.
  • If corruption is found, restore from the last known good full backup and apply transaction log backups sequentially.

Step 4: Rebuild or Resynchronize the Availability Group Replica

  • On the secondary replica, remove the database from the Availability Group using SSMS or:
  ALTER DATABASE [YourDatabaseName] SET HADR OFF;
  • Re-seed the database using Automatic Seeding or manually restore a fresh backup with WITH NORECOVERY.
  • Re-join the database to the Availability Group and monitor the redo queue size via sys.dm_hadr_database_replica_states.

Alternative or Verification Steps

  • After completing the steps above, confirm resolution by checking sys.databases for state_desc = 'ONLINE' and verifying the redo_queue_size in sys.dm_hadr_database_replica_states drops to zero.
  • As an alternative if redo remains stuck, fail over the Availability Group to a healthy secondary, then remove and fully re-seed the problematic replica rather than attempting an in-place repair.

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

Troubleshooting Guide: SQL Server Error 992 – Failed to Get Shared Lock on Database

Why This Error Happens

Error 992 occurs when SQL Server cannot acquire a shared lock on a database because another session is holding an exclusive lock, typically during operations like ALTER DATABASE, auto-close events, or database snapshot creation. This is commonly caused by a conflicting process (such as a backup job, DBCC command, or another administrative session) that has not yet released its lock, or by a database stuck in a transitional state (e.g., RESTORING, RECOVERY_PENDING). In some cases, it can also stem from orphaned sessions left behind due to an abrupt disconnect or a stalled transaction log operation.

Step-by-Step Resolution Guide

Step 1: Identify the Blocking Session

  • Open SQL Server Management Studio (SSMS) and run the following query to find blocking locks:
  SELECT request_session_id, resource_type, resource_database_id, request_mode, request_status
  FROM sys.dm_tran_locks
  WHERE resource_type = 'DATABASE';
  • Cross-reference the request_session_id with sys.dm_exec_sessions to identify the offending login, host, or application.
  • Check if the session correlates with a long-running backup, restore, or maintenance job in SQL Server Agent.

Step 2: Terminate or Wait Out the Conflicting Process

  • If the blocking session is a runaway or orphaned connection, terminate it safely using:
  KILL <session_id>;
  • If the lock is held by a legitimate backup/restore operation, allow it to complete rather than forcibly killing it, as this can corrupt the backup file.
  • On Windows Server 2025, check Task Manager or Resource Monitor to confirm no external process (like antivirus or a backup agent) is locking the .mdf/.ldf files at the OS level.

Step 3: Verify Database State and Permissions

  • Run sp_who2 or query sys.databases to confirm the database state is ONLINE and not stuck in RECOVERY_PENDING or SUSPECT:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the SQL Server service account has the necessary NTFS permissions on the database file path (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).
  • If permissions were recently changed via Group Policy or local security policy on Windows Server 2025, re-validate the “Log on as a service” rights for the SQL Server service account in secpol.msc.

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

  • If the lock remains stuck with no identifiable session, restart the SQL Server instance via services.msc or by running:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Confirm no critical transactions are in-flight before restarting, as this will roll back all open transactions.

Alternative or Verification Steps

  • After applying fixes, re-run the original command (e.g., ALTER DATABASE or backup job) and confirm it completes without throwing Error 992.
  • If the issue persists, run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption that might be causing SQL Server to hold locks abnormally.

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

Troubleshooting Guide: Error 991 – Failed to Take Host Database Offline Due to Suspect Partition Database

Why This Error Happens

This error occurs when SQL Server 2025 attempts to take a horizontally partitioned (sharded) host database offline, but one or more of its underlying partition databases has been flagged as SUSPECT due to a failed recovery process, corrupted transaction log, or inaccessible data file. Since the host database relies on all partition databases being in a healthy, online state to coordinate a clean offline transition, SQL Server blocks the operation to prevent data inconsistency or metadata corruption across the distributed database topology. Common root causes include unexpected storage disconnects during recovery, disk corruption on the volume hosting the partition’s MDF/LDF files, or insufficient permissions for the SQL Server service account to access the partition database files after a failover.

Step-by-Step Resolution Guide

Step 1: Identify the Suspect Partition Database

  • Open SQL Server Management Studio (SSMS) and connect to the host instance.
  • Run the following query to identify which partition is marked suspect:
  SELECT name, state_desc, is_in_standby 
  FROM sys.databases 
  WHERE state_desc = 'SUSPECT';
  • Cross-reference the partition name with your sharding/partition mapping table to confirm its role in the host database group.

Step 2: Review SQL Server Error Logs for Root Cause

  • Navigate to the default log path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG
  • Search for entries timestamped around the failure, looking for keywords like “recovery failed,” “823,” “824,” or “I/O error.”
  • Confirm whether the issue is due to physical disk corruption, a torn page, or an access-denied error related to the SQL Server service account.

Step 3: Attempt to Bring the Partition Database Back Online

  • Try running ALTER DATABASE [PartitionDBName] SET ONLINE; to force a recovery attempt.
  • If the command fails, check EMERGENCY mode access using:
  ALTER DATABASE [PartitionDBName] SET EMERGENCY;
  DBCC CHECKDB ([PartitionDBName]) WITH NO_INFOMSGS;
  • Based on DBCC CHECKDB results, run ALTER DATABASE [PartitionDBName] SET ONLINE or proceed to repair options like REPAIR_REBUILD (avoid REPAIR_ALLOW_DATA_LOSS unless necessary).

Step 4: Restore Partition Database from Backup (If Repair Fails)

  • If DBCC CHECKDB indicates unrecoverable corruption, restore the partition database from the last known good full backup plus transaction log backups.
  • Use: RESTORE DATABASE [PartitionDBName] FROM DISK = 'D:\Backups\PartitionDBName.bak' WITH NORECOVERY, followed by log restores and WITH RECOVERY on the final log file.
  • Ensure the restored partition database is reattached correctly to the host database’s partition mapping metadata.

Step 5: Retry Taking the Host Database Offline

  • Once all partition databases report ONLINE status, retry the original operation:
  ALTER DATABASE [HostDBName] SET OFFLINE;
  • Monitor the SQL Server Error Log in real time to confirm the operation completes without re-triggering Error 991.

Alternative or Verification Steps

  • Run SELECT name, state_desc FROM sys.databases; across all partition databases to confirm every database tied to the host shows ONLINE before retrying the offline command.
  • If the suspect partition cannot be repaired or restored in time, consider temporarily removing it from the partition mapping (if your sharding architecture supports dynamic partition exclusion) so the host database can be taken offline without that specific shard, then reintegrate it once resolved.

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

Troubleshooting Guide: SQL Server Error 989

Why This Error Happens

Error 989 occurs when SQL Server 2025 attempts to take a partitioned (federated) database offline, but the operation is blocked because one or more of its partition member databases has been marked as SUSPECT. This typically happens due to corrupted transaction log files, abrupt power loss during a write operation, or storage-level I/O failures on the underlying disk subsystem. Since SQL Server cannot guarantee transactional consistency across all partitions while one member is inaccessible, it halts the offline process entirely to prevent data corruption.

Step-by-Step Resolution Guide

Step 1: Identify the Suspect Partition Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to locate the specific database ID and partition causing the failure:
  SELECT name, database_id, state_desc 
  FROM sys.databases 
  WHERE state_desc = 'SUSPECT';
  • Note the database_id referenced in the Event ID 989 log entry in Event Viewer (Windows Logs > Application).

Step 2: Attempt to Reset the Database Status via Emergency Mode

  • In a new query window, force the suspect database into EMERGENCY mode to allow read-only access:
  ALTER DATABASE [YourPartitionDB] SET EMERGENCY;
  • Run a consistency check to diagnose the corruption level:
  DBCC CHECKDB ('YourPartitionDB') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output for the extent of logical or physical corruption.

Step 3: Repair or Restore the Partition Database

  • If corruption is minor, attempt an automatic repair (Note: this may result in data loss):
  ALTER DATABASE [YourPartitionDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  DBCC CHECKDB ('YourPartitionDB', REPAIR_ALLOW_DATA_LOSS);
  ALTER DATABASE [YourPartitionDB] SET MULTI_USER;
  • If REPAIR_ALLOW_DATA_LOSS is not viable, restore the partition from the last known good backup via Tasks > Restore > Database in SSMS, ensuring the WITH RECOVERY option is selected.

Step 4: Retry the Offline Operation

  • Once the partition database status changes from SUSPECT to ONLINE, re-attempt to take the host database offline:
  ALTER DATABASE [HostDatabaseName] SET OFFLINE WITH ROLLBACK IMMEDIATE;
  • Monitor the SQL Server Error Log to confirm Error 989 does not reappear.

Alternative or Verification Steps

  • Verification: Re-run SELECT name, state_desc FROM sys.databases; to confirm all partition members report a status of ONLINE before scheduling future maintenance offline tasks.
  • Alternative: If the database remains inaccessible after repair attempts, detach the specific partition file (.mdf/.ndf) using sp_detach_db and perform a hardware-level chkdsk /f scan on the Windows Server 2025 volume to rule out underlying disk sector failures before re-attaching.

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

Why This Error Happens

Error 990 occurs when SQL Server’s federated database engine detects that one or more partition (member) databases within a distributed partitioned view configuration has entered a SUSPECT state, typically due to an incomplete recovery, a corrupted transaction log, or an I/O failure during startup. Because the host database relies on all partition databases being consistent and online to serve federated queries, the engine proactively takes the entire host database offline to prevent data integrity issues or split-brain query results. This is most commonly triggered by abrupt power loss, storage subsystem corruption, or a failed disk extension on one of the underlying partition files (.mdf/.ldf).

Step-by-Step Resolution Guide

Step 1: Identify the Suspect Partition Database

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to locate the suspect database(s):
  SELECT name, state_desc, database_id FROM sys.databases WHERE state_desc = 'SUSPECT';
  • Cross-reference the database_id from the Error 990 message in the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025/Windows 11 default installs).

Step 2: Attempt to Bring the Partition Database Out of Suspect Mode

  • Set the database to EMERGENCY mode to allow read-only access and diagnostics:
  ALTER DATABASE [PartitionDB_Name] SET EMERGENCY;
  • Run DBCC CHECKDB to assess the extent of corruption:
  DBCC CHECKDB ('PartitionDB_Name') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is confirmed, set the database to SINGLE_USER mode before repair:
  ALTER DATABASE [PartitionDB_Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  DBCC CHECKDB ('PartitionDB_Name', REPAIR_ALLOW_DATA_LOSS);

Step 3: Restore from Backup if Repair Fails

  • If DBCC CHECKDB cannot resolve the corruption, restore the affected partition database from the last known good full backup and subsequent transaction log backups.
  • Use the WITH RECOVERY option on the final restore step to bring the database back online:
  RESTORE DATABASE [PartitionDB_Name] FROM DISK = 'E:\Backups\PartitionDB_Full.bak' WITH NORECOVERY;
  RESTORE LOG [PartitionDB_Name] FROM DISK = 'E:\Backups\PartitionDB_Log.trn' WITH RECOVERY;

Step 4: Reset Multi-User Mode and Bring the Host Database Online

  • Return the partition database to multi-user access:
  ALTER DATABASE [PartitionDB_Name] SET MULTI_USER;
  • Manually bring the host federated database back online:
  ALTER DATABASE [HostDB_Name] SET ONLINE;

Step 5: Validate Underlying Storage Health

  • Check Windows Server 2025 Event Viewer under Windows Logs > System for Disk or NTFS warnings (Event ID 7 or 153) that may indicate a failing storage volume.
  • Run chkdsk E: /f /r against the volume hosting the partition database files to rule out file system-level corruption.

Alternative or Verification Steps

  • After recovery, re-run SELECT name, state_desc FROM sys.databases; to confirm both the host and all partition databases show ONLINE status, then execute a test query against the distributed partitioned view to confirm data consistency.
  • If the issue recurs intermittently, consider migrating away from legacy distributed partitioned views to native Table Partitioning or Always On Availability Groups with automatic page repair, which are more resilient against single-node corruption in SQL Server 2025.

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

Troubleshooting Guide: Error 988 – Database Lacks Quorum of Nodes for High Availability

Why This Error Happens

Error 988 occurs when a database participating in an Always On Availability Group loses communication with the majority of nodes in the Windows Server Failover Cluster (WSFC), causing the cluster to lose quorum. This typically happens due to network partitioning between replicas, a cluster service outage on one or more nodes, or misconfigured quorum witness settings (File Share Witness or Cloud Witness). Without a quorum majority, SQL Server intentionally blocks access to the database to prevent split-brain scenarios and maintain data consistency.

Step-by-Step Resolution Guide

Step 1: Verify Cluster Node and Quorum Status

  • Open PowerShell as Administrator and run Get-ClusterNode to check the status of all nodes (Up, Down, or Paused).
  • Run Get-ClusterQuorum to confirm the current quorum configuration and witness type.
  • Check Failover Cluster Manager (CluAdmin.msc) for any nodes shown in a “Down” or “Unreachable” state.

Step 2: Restore Network Connectivity Between Nodes

  • Confirm that cluster network adapters are communicating using Test-NetConnection -ComputerName <NodeName> -Port 3343 (the default cluster communication port).
  • Check Windows Firewall rules on Windows Server 2025 to ensure cluster ports (3343 UDP/TCP) and SQL Server ports (1433, 5022 for AG endpoints) are not blocked.
  • Restart the Cluster Service on affected nodes using Restart-Service -Name ClusSvc -Force.

Step 3: Repair or Reconfigure the Quorum Witness

  • Navigate to Failover Cluster Manager > right-click the cluster name > More Actions > Configure Cluster Quorum Settings.
  • If using a File Share Witness, verify the share path (e.g., \\FileServer\Witness$) is accessible and the Cluster Name Object (CNO) has Full Control NTFS/Share permissions.
  • If the witness is unreachable, temporarily reconfigure to a Cloud Witness using an Azure Storage Account connection string to re-establish quorum manually.

Step 4: Force Quorum (Only If Majority Nodes Are Permanently Lost)

  • As a last resort, if the majority of nodes are offline and cannot be recovered, force start the cluster using Start-ClusterNode -FixQuorum on a surviving node.
  • Immediately bring any failed nodes back online and rejoin them to prevent prolonged single-node operation, which risks data divergence.

Alternative or Verification Steps

  • After applying the fix, run SELECT * FROM sys.dm_hadr_availability_replica_states; in SQL Server Management Studio to confirm all replicas show CONNECTED and the primary role is ONLINE.
  • If the error persists after cluster repair, fail over the Availability Group manually to a healthy secondary replica using ALTER AVAILABILITY GROUP [AGName] FAILOVER; to restore immediate database access while diagnosing the root node failure.

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

Troubleshooting Guide: SQL Server Error 987 – Duplicate Key Insert on System Objects

Why This Error Happens

Error 987 occurs when SQL Server’s internal consistency check detects a duplicate key violation while attempting to update system catalog objects, which almost always points to corruption in the system tables or their underlying indexes. This typically results from an abrupt shutdown during a metadata operation, underlying storage/disk corruption, or a bug triggered during an in-place upgrade (such as moving to SQL Server 2025) that left system table indexes out of sync. In rare cases, it can also be caused by manual or third-party tool intervention that directly manipulated system catalog views.

Step-by-Step Resolution Guide

Step 1: Isolate the Affected Database and Check Error Logs

  • Identify the exact database name referenced in the %.*ls placeholder from the SQL Server error log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025/Windows 11 default installs).
  • Run EXEC sp_readerrorlog 0, 1, 'Error: 987'; in SSMS to pull the full context of when and where the error triggered.
  • Note whether the error occurs during startup, a scheduled job, or an upgrade process — this narrows down whether it’s storage-related or upgrade-related.

Step 2: Run DBCC CHECKDB to Confirm Corruption Scope

  • Open a new query window in SQL Server Management Studio (SSMS) connected to the affected instance.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to get a full corruption report, paying close attention to errors referencing sys.sysschobjs, sys.sysidxstats, or other system base tables.
  • If corruption is confirmed in system tables specifically, escalate directly to Step 3 rather than attempting standard repair options.

Step 3: Restore From a Known Good Backup

  • Because system table corruption is rarely safely repairable with DBCC CHECKDB repair options (which can cause further data loss on system objects), the most reliable fix is restoring from the last known good full backup taken before the corruption occurred.
  • Use RESTORE DATABASE [YourDatabaseName] FROM DISK = 'D:\Backups\YourDatabaseName.bak' WITH REPLACE, RECOVERY; in SSMS.
  • If no clean backup exists, open a Microsoft Support case referencing Error 987 for assisted recovery, especially since this is a newly released version (SQL Server 2025) where repair tooling may still be maturing.

Step 4: Check Storage Health and Windows Event Viewer

  • Open Windows Event Viewer on Windows Server 2025/Windows 11 and navigate to Windows Logs > System to check for underlying disk I/O errors (Event ID 7 or 51) that may have caused the original corruption.
  • Run chkdsk D: /f /r (replace D: with your SQL data drive) during a maintenance window to rule out physical disk issues.
  • If using virtualized storage or SAN, confirm there were no recent storage failover or snapshot events that coincided with the corruption timestamp.

Alternative or Verification Steps

  • After restoring, immediately re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS; to confirm zero allocation or consistency errors before resuming normal operations.
  • As a preventive measure going forward, enable CHECKSUM page verification (ALTER DATABASE [YourDatabaseName] SET PAGE_VERIFY CHECKSUM;) and schedule regular DBCC CHECKDB jobs via SQL Server Agent to catch similar corruption early.

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

Why This Error Happens

Error 985 is technically an informational status message generated by the SQL Server Setup engine, not a failure condition—it simply logs that a specific file was successfully copied into a target directory during installation or patching. However, users often “report” this as an issue because it appears repeatedly in Summary.txt or Detail.txt logs, causing confusion when paired with other warnings, or because the installation appears to hang immediately after this message is logged. This typically happens when a subsequent component (like a feature rule check or a service registration) stalls due to file lock conflicts, insufficient NTFS permissions on the target folder, or a corrupted MSI cache entry immediately following this log entry.

Step-by-Step Resolution Guide

Step 1: Validate the Setup Log Context

  • Navigate to %ProgramFiles%\Microsoft SQL Server\160\Setup Bootstrap\Log\<timestamp>\Detail.txt.
  • Search for “Error 985” and read the next 5-10 lines immediately following it to identify the actual blocking component (e.g., sqlservr.exe, Launchpad, or Reporting Services).
  • Confirm whether the process exited with a non-zero return code shortly after this entry; if it did, the root cause lies in the following component, not this file-copy event.

Step 2: Audit NTFS and Share Permissions on the Target Folder

  • Right-click the destination folder referenced in the log (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn) and select Properties > Security.
  • Ensure the NT SERVICE\MSSQLSERVER and NT AUTHORITY\SYSTEM accounts have Full Control.
  • If missing, run the following elevated PowerShell command to reset inheritance:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER" /reset /T

Step 3: Clear the Windows Installer Cache and Temp Files

  • Stop any lingering msiexec.exe processes via Task Manager.
  • Delete stale cache files in C:\Windows\Installer\$PatchCache$\ associated with the SQL Server 2025 build GUID.
  • Clear the setup temp directory at %TEMP%\SqlSetup to prevent duplicate file-lock conflicts on the next install attempt.

Step 4: Re-run Setup with Verbose Logging

  • Launch setup from an elevated Command Prompt using:
  setup.exe /Action=Install /INDICATEPROGRESS /Q
  • Monitor the console output in real-time to confirm the installer proceeds past the file-copy phase without hanging on Error 985.

Alternative or Verification Steps

  • Verify the fix by checking that Summary.txt shows “Final result: Passed” and that the SQL Server service starts automatically (Get-Service MSSQLSERVER should return Running).
  • If the installer still stalls, use the SQL Server Installation Center > Repair option to force a clean re-copy of binaries, bypassing the cached file state entirely.

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

Troubleshooting Guide: SQL Server Error 986 – “Couldn’t Get a Clean Bootpage for Database”

Why This Error Happens

This error occurs when SQL Server’s checkpoint process encounters concurrent, rapid modifications to a database’s boot page (page 9 in the primary file) while trying to read a transactionally consistent snapshot of it. It is typically triggered by extremely high transaction throughput or aggressive concurrent DDL/DML operations against the database, causing the engine to retry the read multiple times. Despite the alarming wording, Microsoft explicitly classifies this as an informational message, meaning it is usually benign and self-resolving as SQL Server simply retries until it succeeds.

Step-by-Step Resolution Guide

Step 1: Confirm the Severity and Context of the Message

  • Check the SQL Server Error Log via SSMS (Management > SQL Server Logs) or xp_readerrorlog to confirm Error 986 is logged as Informational and not paired with a higher-severity error (like 823, 824, or 825) which would indicate actual I/O corruption.
  • Note the timestamp and cross-reference it with Windows Performance Monitor (PerfMon) logs for disk latency spikes.
  • Run the following query to check recent error log entries:
  EXEC sys.xp_readerrorlog 0, 1, N'986';

Step 2: Analyze Workload and Checkpoint Frequency

  • Identify if this coincides with a manual or automatic CHECKPOINT operation during heavy write activity.
  • Check if “Indirect Checkpoints” are enabled for the database, as this can sometimes reduce the frequency of boot page contention.
  SELECT name, target_recovery_time_in_seconds 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If target_recovery_time_in_seconds is 0 (Automatic/Legacy), consider setting it to a non-zero value (e.g., 60) to enable Indirect Checkpoints, which can smooth out I/O patterns.
  ALTER DATABASE YourDatabaseName SET TARGET_RECOVERY_TIME = 60 SECONDS;

Step 3: Rule Out Underlying Disk I/O Bottlenecks

  • Since this error often correlates with storage subsystem lag on Windows Server 2025, verify the health of the underlying storage using Storage Spaces Direct health checks or Device Manager.
  • Open Resource Monitor (resmon.exe) and check the Disk tab for high queue lengths or response times exceeding 15ms on the drive hosting the .mdf file.
  • Update storage drivers via Windows Update or the manufacturer’s dashboard (e.g., Dell OMSA, HPE iLO) to ensure compatibility with Windows Server 2025 I/O stack changes.

Step 4: Validate Database Integrity

  • Although the error is informational, run a full integrity check to validate that no physical corruption exists on the boot page itself.
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output specifically for allocation errors on Page ID 1:9 (the boot page).

Alternative or Verification Steps

  • Verification: Monitor the SQL Server Error Log for the next 24–48 hours; if Error 986 does not recur alongside Error 823/824, or if it occurs only once without a corresponding DBCC CHECKDB failure, the system is healthy and no further action is needed.
  • Alternative Fix: If the error persists frequently under heavy load, consider migrating the database’s transaction log and data files to separate physical volumes (or faster NVMe storage) to reduce I/O contention during checkpoint operations.

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

Troubleshooting Guide: SQL Server Setup Error 984 — Failed Versioned Copy of sqlscriptdowngrade.dll

Why This Error Happens

This error typically occurs when the SQL Server Setup process does not have sufficient NTFS permissions to write to the Binn\Cache folder during installation, upgrade, or patching operations. It can also happen if the sqlscriptdowngrade.dll file is locked by another process (such as a running SQL Server service or antivirus scanner), or if the file itself is corrupted/missing from the source media. Additionally, Windows File System Protection or a pending reboot state can interfere with the VerInstallFile API call, causing the versioned copy operation to fail.

Step-by-Step Resolution Guide

Step 1: Verify and Reset Folder Permissions

  • Navigate to the SQL Server installation directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn.
  • Right-click the Binn folder (and the Binn\Cache subfolder if it exists) and select Properties > Security.
  • Ensure the SYSTEM, Administrators, and the SQL Server service account have Full Control permissions.
  • Apply permissions recursively using an elevated Command Prompt:
  • icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn" /grant SYSTEM:(OI)(CI)F /T

Step 2: Stop Conflicting Processes and Clear File Locks

  • Open Services.msc and stop all SQL Server-related services (SQL Server, SQL Server Agent, SQL Server Browser).
  • Temporarily disable real-time antivirus/endpoint protection scanning on the Binn and Binn\Cache directories, as locking mechanisms often block VerInstallFile.
  • Use Process Explorer (Sysinternals) to search for any handle locking sqlscriptdowngrade.dll and terminate the offending process if found.

Step 3: Clear the Cache Folder and Re-run Setup

  • Manually delete the contents of the Binn\Cache folder (do not delete the folder itself) to force a clean versioned copy attempt.
  • Check for a pending reboot flag in the registry that may be blocking file operations:
  • Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager and look for a PendingFileRenameOperations key; if present, reboot the server to clear it.
  • Re-launch SQL Server Setup as Administrator and retry the installation/patch step that triggered Error 984.

Step 4: Repair Corrupted Installation Media

  • If the error persists, the local setup cache or source ISO/executable may be corrupted.
  • Clear the bootstrap cache located at C:\ProgramData\Microsoft\SQL Server\XXX\Setup Bootstrap\Cache (replace XXX with the relevant version folder).
  • Re-download the SQL Server 2025 installation media from the official Microsoft source and verify the checksum before re-running setup.

Alternative or Verification Steps

  • To verify the fix, check the detailed Setup log at C:\Program Files\Microsoft SQL Server\170\Setup Bootstrap\Log\Summary.txt and confirm no further Error 984 or VerInstallFile failures appear.
  • If the issue persists after permission and cache fixes, perform the installation using a local Administrator account directly on the console (avoid RDP sessions with restricted tokens) to rule out User Account Control (UAC) token-filtering issues.

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

Troubleshooting Guide: Error 982 – No Online Secondary Replicas Enabled for Read-Only Access

Why This Error Happens

This error occurs when a client application attempts to connect to an Availability Group (AG) listener using a connection string that specifies ApplicationIntent=ReadOnly, but no secondary replica in the AG is currently configured or available to service read-only requests. This typically happens due to misconfigured read-only routing lists, a secondary replica being offline or in a “Resolving” state, or the Readable Secondary property being incorrectly set to “No” on all secondary nodes. Additionally, this can occur transiently during failover events when Windows Server 2025 clustering (WSFC) is still stabilizing the roles of the replicas.

Step-by-Step Resolution Guide

Step 1: Verify Replica Accessibility Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the primary replica.
  • Navigate to Always On High Availability > Availability Groups > [Your AG Name] > Availability Replicas.
  • Right-click the specific secondary replica and select Properties.
  • Under the Connections in Secondary Role section, ensure the dropdown is set to “Allow all connections” or “Allow only read-intent connections” rather than “No connections.”

Step 2: Check Read-Only Routing URLs via T-SQL

  • Open a New Query window on the Primary replica and verify the routing list configuration using the following command: SELECT * FROM sys.availability_read_only_routing_lists;
  • If the list is empty or incorrect, update the routing list using ALTER AVAILABILITY GROUP [YourAGName] MODIFY REPLICA ON 'PrimaryServerName' WITH (PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('SecondaryServerName')));
  • Ensure the READ_ONLY_ROUTING_URL is correctly set for the secondary instance (e.g., TCP://SecondaryServerName.domain.com:1433).

Step 3: Validate Cluster Health in Windows Server 2025

  • Open Failover Cluster Manager on the Windows Server 2025 host.
  • Check the Roles tab to ensure the Availability Group resource is “Running” and not in a “Partial” or “Failed” state.
  • If the secondary node shows a “Not Healthy” status, right-click the node and select More Actions > Resume Role to force a resync with the primary.

Step 4: Restart the SQL Server Service on the Secondary Node

  • If the replica remains stuck in a “Resolving” state despite healthy cluster status, restart the SQL Server (MSSQLSERVER) service via Services.msc or Server Manager.
  • This forces the Always On Availability Groups listener to re-establish the session state and refresh the read-only routing cache.

Alternative or Verification Steps

  • Verification: Run SELECT replica_server_name, role_desc, operational_state_desc, readable_secondary FROM sys.dm_hadr_availability_replica_states to confirm the secondary shows operational_state_desc = ONLINE and readable_secondary = TRUE (1).
  • Alternative: If the issue persists under heavy load, bypass the routing list temporarily by connecting directly to the secondary replica’s instance name (rather than the AG Listener) with ApplicationIntent=ReadOnly to confirm the database itself is accessible, isolating the issue to the listener/routing configuration rather than the data itself.

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

Troubleshooting Guide: Error 983 – Availability Database Not in PRIMARY or SECONDARY Role

Why This Error Happens

This error occurs when an Always On Availability Group database replica is transitioning between roles (such as during a failover) or is stuck in the RESOLVING state due to a communication failure between replicas. It can also happen if the availability replica lost quorum, the WSFC (Windows Server Failover Cluster) cannot determine the current primary, or the endpoint used for replica communication is unreachable due to a firewall or port conflict. In some cases, a corrupted cluster database or an unexpected restart of the SQL Server service while a failover was in progress leaves the replica in an undefined state.

Step-by-Step Resolution Guide

Step 1: Verify the Current State of the Availability Group

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to check replica health:
SELECT ag.name AS AGName, ar.replica_server_name, ars.role_desc, ars.connected_state_desc, ars.synchronization_health_desc
FROM sys.availability_groups ag
JOIN sys.availability_replicas ar ON ag.group_id = ar.group_id
JOIN sys.dm_hadr_availability_replica_states ars ON ar.replica_id = ars.replica_id;
  • Look specifically for RESOLVING_NORMAL or RESOLVING_PENDING_FAILOVER under role_desc, as these confirm the root cause.

Step 2: Check Windows Server Failover Cluster (WSFC) Health

  • Open Failover Cluster Manager on Windows Server 2025 and inspect the “Roles” tab for the Availability Group resource.
  • Confirm cluster quorum is intact by running this in PowerShell (Run as Administrator):
Get-ClusterQuorum
Get-ClusterNode | Select Name, State
  • If a node shows as “Down” or “Unreachable,” restart the Cluster Service on that node via services.msc or:
Restart-Service -Name ClusSvc -Force

Step 3: Validate Network and Endpoint Connectivity

  • Ensure the Database Mirroring Endpoint port (default 5022) is open on Windows Defender Firewall for all replicas.
  • Test connectivity between nodes using:
Test-NetConnection -ComputerName <PartnerServerName> -Port 5022
  • Check the endpoint status in SQL Server:
SELECT name, protocol_desc, port, state_desc FROM sys.tcp_endpoints;

Step 4: Force a Manual Failover or Resume the Replica

  • If the primary replica is unresponsive, initiate a manual failover from a healthy secondary using SSMS: Right-click the Availability Group → Failover….
  • If data movement is suspended, resume it manually:
ALTER DATABASE [YourDatabaseName] SET HADR RESUME;
  • For a replica stuck in RESOLVING state with no healthy partner, you may need to force failover with possible data loss (use only as a last resort):
ALTER AVAILABILITY GROUP [YourAGName] FORCE_FAILOVER_ALLOW_DATA_LOSS;

Step 5: Restart SQL Server and HADR Services

  • Restart the SQL Server service on the affected node via services.msc (Service name: MSSQLSERVER or named instance equivalent).
  • Confirm “AlwaysOn Availability Groups” is still enabled in SQL Server Configuration Manager under the instance properties (HADR tab).

Alternative or Verification Steps

  • After applying fixes, re-run the sys.dm_hadr_availability_replica_states query from Step 1 and confirm role_desc shows PRIMARY or SECONDARY with connected_state_desc as CONNECTED.
  • If the issue persists, check the SQL Server Error Log and Windows Event Viewer (Application/System logs) for Event ID 1135 or 19407, which often accompany Error 983 and indicate deeper cluster-level failures requiring WSFC log review (Get-ClusterLog -Destination C:\ClusterLogs).

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

Troubleshooting Guide: SQL Server Error 981 — Database Manager Target Version Mismatch

Why This Error Happens

Error 981 occurs when the SQL Server Database Manager detects that a database’s internal version number does not match the version expected by the current instance of SQL Server 2025. This typically happens after an in-place upgrade, a restore from an incompatible build, or when system catalog metadata becomes partially corrupted during an interrupted upgrade process. In most cases, the underlying cause is a mismatch between the on-disk database schema version and the SQL Server engine binaries currently installed on Windows Server 2025 or Windows 11.

Step-by-Step Resolution Guide

Step 1: Verify the Current SQL Server Build and Database Version

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; to confirm the installed engine build.
  • Cross-reference the returned build number against Microsoft’s official SQL Server 2025 version table to identify the expected internal database version.
  • Check the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact “target database version” value reported alongside Error 981.

Step 2: Confirm and Repair Pending Upgrade State

  • Open Services.msc on Windows Server 2025 or Windows 11 and confirm the SQL Server (MSSQLSERVER) service stopped mid-upgrade or shows a “Starting” state that never completes.
  • Restart the SQL Server service using an elevated PowerShell prompt: Restart-Service -Name 'MSSQLSERVER' -Force.
  • If the upgrade is still stuck, re-run SQL Server Setup from the installation media, selecting Repair under Maintenance options to force the upgrade scripts to complete.

Step 3: Restore or Attach the Database Using a Compatible Engine Version

  • If the database was restored from a newer SQL Server build than the one installed, uninstall and reinstall the matching SQL Server 2025 Cumulative Update (CU) from the Microsoft Update Catalog.
  • Use RESTORE DATABASE [YourDB] WITH RECOVERY; only after confirming the CU level matches the backup’s origin version.
  • Avoid attaching .mdf/.ldf files directly from a higher-version instance; instead, use a compatible backup/restore or sp_detach_db / sp_attach_db only when versions align.

Step 4: Rebuild System Databases if Corruption Is Suspected

  • Run SQL Server Setup with the /ACTION=REBUILDDATABASE parameter to rebuild the master, model, and msdb system databases if the version mismatch persists after upgrade repair.
  • Example command: Setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=BUILTIN\Administrators.
  • Reapply the latest Cumulative Update immediately after the rebuild to realign system catalog versions.

Alternative or Verification Steps

  • After applying the fix, run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'; to confirm the database compatibility level now matches the instance.
  • If Error 981 persists, detach the database, apply the correct SQL Server 2025 CU package matching the database’s original version, then reattach and monitor the ERRORLOG for successful recovery messages.

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

Troubleshooting Guide: Error 980 – Columnstore Index Not Supported by SQL Server Edition

Why This Error Happens

Error 980 occurs when SQL Server attempts to attach or restore a database that contains one or more columnstore indexes on an edition that does not support this feature, such as SQL Server 2025 Standard, Web, or Express. Columnstore indexes are an Enterprise-tier feature, so when a database created or backed up under Enterprise edition is moved to a lower edition, the engine blocks the database from coming online to prevent data access errors. This commonly happens after a migration, a downgrade, or when restoring a backup onto a different licensed instance than the one it originated from.

Step-by-Step Resolution Guide

Step 1: Confirm the Edition and Feature Mismatch

  • Run SELECT SERVERPROPERTY('Edition'); in SQL Server Management Studio (SSMS) to confirm the current installed edition.
  • Check the source environment to verify whether the database originally resided on an Enterprise or Developer edition instance.
  • Review SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the full Error 980 message, including the exact database name.

Step 2: Upgrade the Edition (Preferred Fix)

  • If columnstore functionality is required, upgrade the instance to SQL Server 2025 Enterprise or Developer edition.
  • Open Command Prompt as Administrator and run the Edition Upgrade wizard:
  Setup.exe /ACTION=EditionUpgrade /INSTANCENAME=MSSQLSERVER /PID=xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
  • Restart the SQL Server service afterward via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Remove the Columnstore Index (If Staying on Current Edition)

  • On the original Enterprise/Developer instance (where the database can still be loaded), connect via SSMS and identify all columnstore indexes:
  SELECT i.name, i.type_desc, t.name AS table_name
  FROM sys.indexes i
  JOIN sys.tables t ON i.object_id = t.object_id
  WHERE i.type IN (5, 6);
  • Drop each columnstore index using:
  DROP INDEX [IndexName] ON [SchemaName].[TableName];
  • Re-back up the database with BACKUP DATABASE [YourDB] TO DISK = 'C:\Backups\YourDB_NoColumnstore.bak';.

Step 4: Re-Attach or Restore the Cleaned Database

  • Copy the new backup file to the target Standard/Web edition server.
  • Restore using SSMS or T-SQL:
  RESTORE DATABASE [YourDB] FROM DISK = 'C:\Backups\YourDB_NoColumnstore.bak' WITH REPLACE;
  • Confirm the database comes online by checking its status in sys.databases (state_desc should read ONLINE).

Alternative or Verification Steps

  • Verify the fix by running SELECT name, state_desc FROM sys.databases WHERE name = 'YourDB'; — a healthy result shows ONLINE with no further Error 980 entries in the Error Log.
  • If upgrading or dropping indexes isn’t feasible, consider standing up a separate Enterprise/Developer edition instance (even temporarily, under a trial license) solely to strip columnstore indexes before migrating the database back to the supported edition environment.

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

Troubleshooting Guide: SQL Server Error 979 – Read-Only Routing Failure in Availability Group

Why This Error Happens

This error occurs when a client application connects to an Availability Group (AG) listener using ApplicationIntent=ReadOnly, but the secondary replica it lands on is not configured to accept read-only workloads. This is typically caused by a missing or misconfigured Read-Only Routing List, an incorrect Availability Group Listener configuration, or the secondary replica’s Readable Secondary property being set to “No” instead of “Yes” or “Read-intent only.” Additionally, the connection may be hitting the Primary replica directly while the AG’s READ_ONLY_ROUTING_LIST points elsewhere, causing a routing mismatch.

Step-by-Step Resolution Guide

Step 1: Verify the Readable Secondary Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the Primary replica.
  • Navigate to Always On High Availability > Availability Groups > [Your AG] > Availability Replicas.
  • Right-click the secondary replica, select Properties, and confirm the Readable Secondary setting is set to Yes or Read-intent only (not No).
  • Alternatively, run this T-SQL command on the Primary:
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'SecondaryReplicaName'
WITH (SECONDARY_ROLE (ALLOW_CONNECTIONS = READ_ONLY));

Step 2: Configure the Read-Only Routing URL

  • Each replica needs a valid READ_ONLY_ROUTING_URL so the listener knows where to direct read-intent traffic.
  • Run the following on the Primary replica for every participating replica (including itself if it hosts read-only workloads):
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'ReplicaInstanceName'
WITH (SECONDARY_ROLE (READ_ONLY_ROUTING_URL = 'TCP://ReplicaFQDN:1433'));
  • Ensure the FQDN resolves correctly via DNS on both Windows Server 2025 and Windows 11 client machines (test with nslookup ReplicaFQDN).

Step 3: Define the Read-Only Routing List

  • The routing list tells the Primary which secondaries can serve read-only traffic when a client connects.
  • Execute this on the Primary replica:
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'PrimaryReplicaName'
WITH (PRIMARY_ROLE (READ_ONLY_ROUTING_LIST = ('SecondaryReplica1', 'SecondaryReplica2')));
  • Double-check replica names match exactly as registered in sys.availability_replicas.

Step 4: Validate the Connection String and Firewall Rules

  • Confirm the client connection string includes both ApplicationIntent=ReadOnly; and MultiSubnetFailover=True; if applicable.
  • On Windows Server 2025, open Windows Defender Firewall with Advanced Security and ensure TCP port 1433 (or custom port) is allowed for inbound/outbound traffic on all replica nodes.
  • Restart the SQL Server (MSSQLSERVER) service after any firewall or routing changes via services.msc or:
Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Run SELECT * FROM sys.availability_read_only_routing_lists; on the Primary to confirm the routing list is correctly populated and matches your intended topology.
  • Test connectivity directly using sqlcmd -S YourListenerName -E -K ReadOnly to simulate a read-intent connection and verify it routes to the correct secondary without throwing Error 979.

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

Troubleshooting Guide: SQL Server Error 977 – Missing Associated Index for Constraint

Why This Error Happens

Error 977 occurs when SQL Server’s metadata for a constraint (such as a primary key, unique key, or foreign key) references an index that no longer exists in the sys.indexes catalog view, typically due to system catalog corruption. This inconsistency often arises from improper index drops, interrupted DDL operations, abrupt server shutdowns during schema changes, or disk-level corruption affecting system metadata pages. It is frequently surfaced during DBCC CHECKDB operations, indicating that the internal relationship between sys.key_constraints/sys.foreign_keys and sys.indexes has broken down.

Step-by-Step Resolution Guide

Step 1: Run a Full Consistency Check

  • Open SQL Server Management Studio (SSMS) or connect via sqlcmd on Windows Server 2025/Windows 11.
  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output to confirm whether Error 977 is isolated or accompanied by additional allocation or consistency errors (e.g., Error 8928 or 8944).
  • Note the exact object_id and constraint name referenced in the warning for targeted remediation.

Step 2: Identify and Validate the Orphaned Constraint

  • Query the system catalog to cross-reference the constraint and its missing index:
  • SELECT name, object_id, parent_object_id FROM sys.key_constraints WHERE object_id = <reported_object_id>;
  • SELECT * FROM sys.indexes WHERE object_id = <reported_object_id>;
  • If the index entry is absent or index_id is NULL/mismatched, this confirms metadata desynchronization rather than physical data loss.
  • Check the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for correlating timestamps of the corruption event.

Step 3: Restore from a Clean Backup (Preferred Method)

  • If a recent, verified backup exists, restore the affected database to a new instance:
  • RESTORE DATABASE YourDatabaseName FROM DISK = 'D:\Backups\YourDatabase.bak' WITH REPLACE, RECOVERY;
  • Run DBCC CHECKDB again on the restored copy to confirm the constraint-index relationship is intact before promoting it to production.
  • This avoids data loss associated with repair operations in Step 4.

Step 4: Use Repair Options as a Last Resort

  • If no backup is available, first attempt DBCC CHECKDB ('YourDatabaseName') WITH REPAIR_REBUILD; in single-user mode, as this does not discard data.
  • Set the database to single-user mode first: ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Only if REPAIR_REBUILD fails to resolve the issue, consider REPAIR_ALLOW_DATA_LOSS as a final option, understanding this may drop the orphaned constraint and associated data permanently.
  • Revert to multi-user mode afterward: ALTER DATABASE YourDatabaseName SET MULTI_USER;

Alternative or Verification Steps

  • Re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS; after remediation to confirm Error 977 no longer appears and no new integrity issues were introduced.
  • If the error persists or recurs frequently, run CHKDSK /F on the underlying Windows Server 2025 volume and check Windows Event Viewer (System/Application logs) for disk I/O errors that may indicate failing storage hardware.

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

Troubleshooting Guide: SQL Server Error 978 – Database Inaccessible with Read-Only Application Intent

Why This Error Happens

This error occurs because the client connection string explicitly specifies ApplicationIntent=ReadOnly, but the database being targeted is the primary replica in an Availability Group, not a readable secondary. In SQL Server 2025, primary replicas do not serve read-only intent requests unless the Availability Group’s read-only routing list or routing URL is misconfigured, pointing connections to a replica that cannot currently service that intent. This can also happen if the secondary replica is not configured with ALLOW_CONNECTIONS = READ_ONLY or ALL.

Step-by-Step Resolution Guide

Step 1: Verify the Availability Group Replica Roles

  • Open SQL Server Management Studio (SSMS) and connect to the Availability Group listener.
  • Run the following query to check replica roles and connection states:
SELECT ar.replica_server_name, ars.role_desc, ars.connected_state_desc, rcs.connection_modes_desc
FROM sys.dm_hadr_availability_replica_states ars
JOIN sys.availability_replicas ar ON ars.replica_id = ar.replica_id
JOIN sys.dm_hadr_database_replica_cluster_states rcs ON ar.replica_id = rcs.replica_id;
  • Confirm whether the current connection is landing on the Primary or Secondary replica.

Step 2: Correct the Read-Only Routing Configuration

  • Navigate to SSMS > Always On High Availability > Availability Group > Availability Replicas.
  • Right-click the Primary Replica properties and select the Read-Only Routing tab.
  • Ensure the secondary replica has a valid READ_ONLY_ROUTING_URL set via T-SQL:
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'SecondaryNodeName'
WITH (SECONDARY_ROLE (READ_ONLY_ROUTING_URL = 'TCP://SecondaryNode.domain.com:1433'));
  • Verify the Primary replica’s READ_ONLY_ROUTING_LIST includes the secondary node name.

Step 3: Update Secondary Replica Connection Permissions

  • On the secondary node, confirm ALLOW_CONNECTIONS is set correctly to avoid blocking read intent traffic:
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'SecondaryNodeName'
WITH (SECONDARY_ROLE (ALLOW_CONNECTIONS = READ_ONLY));
  • Restart the SQL Server service on the secondary node via Services.msc (Windows Server 2025) to apply changes if the setting was previously NO.

Step 4: Validate Client Connection String

  • Check the application or driver connection string (e.g., ODBC, ADO.NET) for the ApplicationIntent=ReadOnly parameter.
  • Ensure the server name points to the AG Listener, not a specific node, so routing logic can correctly redirect the read-only request.

Alternative or Verification Steps

  • Use sqlcmd -S AGListenerName -d DatabaseName -K ReadOnly from the command line to manually test routing; a successful connection confirms the fix.
  • If routing continues to fail, bypass the listener temporarily by connecting directly to the secondary replica’s instance name to confirm the database itself is accessible for read workloads.

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

Troubleshooting Guide: SQL Server Error 976 — “The target database is in availability group and is currently accessible for connection when the database replica is the primary replica”

Why This Error Happens

Error 976 occurs when an application or user attempts to connect to a database that is part of an Availability Group (AG), but the connection is being routed to a secondary replica that is not configured for read access. This typically happens due to a misconfigured Read-Only Routing List, an incorrect connection string missing the ApplicationIntent=ReadOnly parameter, or a recent failover event that changed which node is currently the primary replica. In SQL Server 2025 running on Windows Server 2025, this is often exacerbated by stale DNS/listener cache entries after a role change.

Step-by-Step Resolution Guide

Step 1: Verify the Current Primary Replica

  • Open SQL Server Management Studio (SSMS) and connect to any node in the AG.
  • Run the following query to identify the current primary:
SELECT ag.name AS AGName, ar.replica_server_name, ars.role_desc 
FROM sys.dm_hadr_availability_replica_states ars
JOIN sys.availability_replicas ar ON ars.replica_id = ar.replica_id
JOIN sys.availability_groups ag ON ar.group_id = ag.group_id;
  • Confirm whether the client is attempting to write to a node reporting SECONDARY.

Step 2: Check and Correct the Connection String

  • Inspect the application’s connection string for the ApplicationIntent property.
  • If the app needs read-write access, ensure it is not set to ApplicationIntent=ReadOnly.
  • If read access is intended, confirm the secondary replica is configured with READ_ONLY or READ_INTENT access mode under AG replica properties in SSMS (Availability Group Properties > Replicas tab).

Step 3: Validate the Read-Only Routing List

  • In SSMS, navigate to Always On High Availability > Availability Groups > [Your AG] > Availability Replicas.
  • Right-click the primary replica, select Properties, and review the Read-Only Routing URL and Read-Only Routing List under each replica’s connection properties.
  • Update the routing list using T-SQL if entries are outdated:
ALTER AVAILABILITY GROUP [YourAGName]
MODIFY REPLICA ON 'PrimaryNodeName'
WITH (PRIMARY_ROLE (READ_ONLY_ROUTING_LIST = ('SecondaryNode1', 'SecondaryNode2')));

Step 4: Clear Cached Listener and DNS Entries

  • On the Windows Server 2025 host, flush the DNS resolver cache to remove stale listener IP mappings:
ipconfig /flushdns
  • Restart the Cluster Service (ClusSvc) on the affected node via services.msc to force re-registration of the AG listener’s virtual network name (VNN).

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

  • If the issue persists after routing corrections, restart the SQL Server (MSSQLSERVER) service on the affected secondary node via SQL Server Configuration Manager.
  • Monitor the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for AG state transition messages confirming successful rejoin.

Alternative or Verification Steps

  • Verify the fix by reconnecting the application and confirming successful read/write operations; check sys.dm_hadr_database_replica_states to ensure is_primary_replica = 1 for the target database on the correct node.
  • If the error persists, manually fail over the AG to a healthy node using ALTER AVAILABILITY GROUP [YourAGName] FAILOVER; (run on the target secondary) to force a clean primary role reassignment.

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

Troubleshooting Guide: Error 975 – System Objects Could Not Be Updated Because Database Is Read-Only

Why This Error Happens

This error occurs when SQL Server attempts to update internal system objects (such as statistics, system metadata, or automatic maintenance structures) but the database has been placed into a READ_ONLY state. This typically happens after a database restore operation that defaults to read-only, a manual configuration change, an Availability Group secondary replica receiving unexpected write attempts, or a database residing on read-only storage media or a file system with restricted write permissions. In some cases, it can also surface when the database is part of a Basic Availability Group or a storage tier policy that enforces read-only access at the volume level.

Step-by-Step Resolution Guide

Step 1: Confirm the Current Database State

  • Open SSMS or a query window and run:
  SELECT name, is_read_only, state_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • Confirm is_read_only returns 1, verifying the database is indeed in read-only mode.
  • Check if the database is part of an Availability Group and confirm whether you are connected to the Primary or Secondary replica.

Step 2: Change the Database to Read-Write Mode

  • Ensure no active user connections are using the database before proceeding.
  • Run the following command to switch modes (requires sysadmin or dbcreator role):
  ALTER DATABASE YourDatabaseName SET READ_WRITE WITH ROLLBACK IMMEDIATE;
  • If the database is in an Availability Group, perform a manual failover instead, promoting the Secondary to Primary via SSMS or:
  ALTER AVAILABILITY GROUP [YourAGName] FAILOVER;

Step 3: Verify File System and Storage Permissions

  • Navigate to the .mdf and .ldf file location, typically:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\
  • Right-click the database files, select Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control or Modify permissions.
  • If the files reside on a SAN, cloud-tiered storage (e.g., Azure Blob via Stretch DB), or a mounted read-only volume/snapshot, confirm the underlying disk is writable in Disk Management and not marked as “Read-Only” under disk attributes (diskpart > attributes disk clear readonly).

Step 4: Restart SQL Server Service and Validate

  • Restart the SQL Server (MSSQLSERVER) service via Services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Re-run the SELECT query from Step 1 to confirm is_read_only now returns 0.

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to ensure no corruption exists that could be forcing the engine to protect the database in a read-only state.
  • If the issue persists and the database belongs to an Availability Group or Log Shipping configuration, manually force a role change/failover rather than altering the database state directly, as system-level replication settings will override manual READ_WRITE commands.

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

Troubleshooting Guide: SQL Server Error 974 – Resource Database Attach Failure

Why This Error Happens

This error occurs when SQL Server 2025 cannot locate the mssqlsystemresource.mdf and mssqlsystemresource.ldf files in the Binn directory alongside sqlservr.exe. The root cause is typically that the resource database files have been accidentally deleted, moved, corrupted, or were never properly installed due to an interrupted setup, a failed patch/Cumulative Update installation, or incorrect manual file restoration. Since the resource database is a critical system database containing all system objects, SQL Server will refuse to start the service entirely until the files are restored to their expected location.

Step-by-Step Resolution Guide

Step 1: Verify the Expected File Location

  • Navigate to the instance-specific Binn folder, typically located at: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\
  • Confirm whether mssqlsystemresource.mdf and mssqlsystemresource.ldf are present.
  • Check the exact path referenced in the error message (the %.*ls placeholder in the actual log will show the specific directory SQL Server attempted to use).
  • Cross-reference this path with the registry key at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\Setup\SQLBinRoot to ensure the service is pointing to the correct Binn directory.

Step 2: Restore the Resource Database Files from Backup Media

  • Locate your original SQL Server 2025 installation media or ISO.
  • Copy mssqlsystemresource.mdf and mssqlsystemresource.ldf from the \x64\Setup\ directory on the installation source.
  • Paste these files directly into the Binn folder identified in Step 1.
  • Ensure you are not grabbing a mismatched version (e.g., from a different CU/Build), as a version mismatch will trigger a separate schema version error.

Step 3: Correct File System Permissions

  • Right-click the Binn folder and select Properties, then navigate to the Security tab.
  • Ensure the SQL Server service account (e.g., NT SERVICE\MSSQLSERVER or a custom domain service account) has Read, Write, and Modify permissions on the resource database files.
  • Run the following PowerShell command to grant access if permissions are stripped:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\mssqlsystemresource.*" /grant "NT SERVICE\MSSQLSERVER:(F)"

Step 4: Check for Antivirus or Endpoint Protection Interference

  • Open your antivirus or Windows Defender console and check the Quarantine/Threat history logs.
  • Add an exclusion for the entire MSSQL\Binn directory to prevent real-time scanning engines from locking or deleting the .mdf/.ldf files during the boot sequence.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net start MSSQLSERVER in an elevated Command Prompt.

Step 5: Re-run Setup Repair (If Files Remain Missing)

  • If the files cannot be located on any backup media, launch the SQL Server Installation Center.
  • Select Maintenance > Repair and choose the affected instance.
  • Allow the Setup wizard to re-extract and reconfigure the system databases, including the resource database files.

Alternative or Verification Steps

  • Verify the Fix: Attempt to start the SQL Server service via services.msc; if successful, connect via SQL Server Management Studio (SSMS) and run SELECT SERVERPROPERTY('ResourceVersion'); to confirm the resource database loaded correctly.
  • Alternative Fix: If Step 5 fails due to a corrupted installation cache, perform a full Uninstall of the Database Engine component followed by a clean re-installation, ensuring you select a fresh, unblemished installation media source to avoid copying over corrupted setup cache files from C:\Program Files\Microsoft SQL Server\170\Setup Bootstrap\.

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

Why This Error Happens

Error 973 occurs when SQL Server 2025 successfully mounts a database during startup, but the internal version upgrade script fails to complete against that database, leaving it in a restricted or read-only state. This is most commonly triggered by an interrupted upgrade process (power loss, forced service termination, or disk I/O timeout) while SQL Server was migrating system catalog metadata to the new engine version. It can also happen if the service account lacks sufficient NTFS permissions on the data/log files, preventing the upgrade scripts from writing changes back to disk.

Step-by-Step Resolution Guide

Step 1: Check the SQL Server Error Log for the Exact Failure Point

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025/Windows 11.
  • Search for the line immediately preceding Error 973 — it usually references a specific upgrade step number (e.g., “Error executing upgrade step…”).
  • Note the database name and the last successful upgrade script version listed.

Step 2: Validate File and Folder Permissions

  • Confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER or a domain service account) has Full Control on the .mdf, .ndf, and .ldf files and their parent directory.
  • Open Services.msc, confirm the SQL Server service is running under the expected account, then right-click the data folder → Properties → Security tab to verify permissions.
  • If permissions were recently changed (e.g., by a Group Policy update on Windows Server 2025), reset them to match the default SQL Server installation ACLs.

Step 3: Restart the Instance in Minimal Configuration Mode

  • Stop the SQL Server service via net stop MSSQLSERVER.
  • Start the instance with the -f (minimal configuration) flag using sqlservr.exe -f from an elevated Command Prompt, or add -f as a startup parameter in SQL Server Configuration Manager.
  • This allows the engine to retry the upgrade scripts without interference from third-party startup procedures or resource contention.

Step 4: Manually Re-run the Upgrade Against the Affected Database

  • Once the instance starts, run:
ALTER DATABASE [YourDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS;
ALTER DATABASE [YourDatabaseName] SET MULTI_USER;
  • If DBCC CHECKDB reports allocation or metadata corruption, this confirms the upgrade script failed due to underlying page-level corruption rather than a permissions issue.

Step 5: Restore From a Pre-Upgrade Backup if Corruption Is Confirmed

  • If corruption is detected, restore the last known-good full backup taken before the SQL Server 2025 upgrade.
  • Re-apply transaction log backups up to the point of failure, then re-trigger the version upgrade cleanly by restarting the service without the -f flag.

Alternative or Verification Steps

  • Run SELECT name, state_desc, compatibility_level FROM sys.databases; — the affected database should show state_desc = ONLINE and the compatibility level matching SQL Server 2025 (170) once resolved.
  • If the database remains stuck in RECOVERY_PENDING or SUSPECT state after these steps, detach and re-attach the database files manually, or use sp_resetstatus as a last resort before restoring from backup.

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

Troubleshooting Guide: SQL Server Error 971 – Resource Database Location Conflict

Why This Error Happens

This error occurs when SQL Server 2025 detects more than one copy of mssqlsystemresource.mdf and mssqlsystemresource.ldf on the system, causing a mismatch between the registry-defined path and the directory where sqlservr.exe actually resides. This typically happens after a manual migration, a failed patch/upgrade, or a restore operation that copied the resource database files to a new instance directory without cleaning up the old ones. Because the resource database is tied to the binary version of the engine, SQL Server refuses to start until it can confirm which copy is authoritative, defaulting to the one co-located with the executable.

Step-by-Step Resolution Guide

Step 1: Identify Both Resource Database Locations

  • Check the error log for the two file paths listed in the Error 971 message ('%.*ls' placeholders will show actual paths in the real log).
  • Navigate to the default instance binary folder, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Search the entire system for duplicate copies using PowerShell:
  • Get-ChildItem -Path C:\ -Recurse -Filter "mssqlsystemresource.*" -ErrorAction SilentlyContinue

Step 2: Confirm the Correct Version-Matched Copy

  • Compare the file version of each mssqlsystemresource.mdf against your installed SQL Server 2025 build number (check via SELECT @@VERSION).
  • Use File Explorer properties (Details tab) or PowerShell (Get-Item "path\to\file.mdf").VersionInfo to confirm which copy matches the currently installed engine build.
  • Discard or rename the mismatched/older copy only after confirming you have a backup.

Step 3: Remove or Relocate the Duplicate Files

  • Stop the SQL Server service first via services.msc or net stop MSSQLSERVER.
  • Move the outdated resource database files (both .mdf and .ldf) out of the SQL Server data directory to a backup folder, e.g., D:\SQLBackup\OldResourceDB\.
  • Ensure only one valid pair remains in the Binn\ folder matching the installed engine version.

Step 4: Restart the SQL Server Service and Validate Startup

  • Start the service again: net start MSSQLSERVER.
  • Monitor the SQL Server Error Log (ERRORLOG file in the Log folder) for successful startup messages instead of Error 971.
  • Confirm no other conflicting paths are referenced by checking the registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\Setup\SQLDataRoot.

Step 5: Reapply the Latest Cumulative Update (If Issue Persists)

  • Download and reinstall the latest CU for SQL Server 2025 to force regeneration of a clean, version-matched resource database.
  • Run the installer in repair mode via Control Panel > Programs > SQL Server 2025 > Uninstall/Change > Repair.

Alternative or Verification Steps

  • Verify the fix by running SELECT SERVERPROPERTY('ResourceLastUpdateDateTime') in SSMS — a successful query confirms the resource database loaded correctly with no conflict.
  • If the error persists, perform a full uninstall/reinstall of the SQL Server instance binaries while preserving user databases, ensuring only one resource database copy is created during setup.

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

Why This Error Happens

SQL Server Error 972 occurs when a stored procedure attempts to access a database that is in a transitional state—such as being set offline, auto-closed, restored, or locked by another session performing an exclusive operation (like ALTER DATABASE, a backup, or a DBCC command). Because the database engine cannot grant a stable connection to the database while it changes state, any procedure call referencing it fails immediately. This is commonly seen in Windows Server 2025 environments where aggressive auto-close settings or concurrent maintenance jobs compete for the same database lock.

Step-by-Step Resolution Guide

Step 1: Check Current Database State

  • Open SQL Server Management Studio (SSMS) and run:
    SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm the state_desc is not OFFLINE, RESTORING, or RECOVERY_PENDING.
  • If it shows OFFLINE, bring it back online with:
    ALTER DATABASE [YourDatabaseName] SET ONLINE;

Step 2: Identify Blocking Sessions or Maintenance Jobs

  • Run sp_who2 or query sys.dm_exec_requests to check for active sessions holding exclusive locks on the database.
  • Check SQL Server Agent Job History (via SSMS > SQL Server Agent > Jobs) for overlapping backup, restore, or shrink operations scheduled at the same time as the procedure execution.
  • Kill any long-running blocking session only after confirming it’s safe:
    KILL <session_id>;

Step 3: Disable Auto-Close on the Database

  • Navigate to Database Properties > Options in SSMS, or run:
    ALTER DATABASE [YourDatabaseName] SET AUTO_CLOSE OFF;
  • Auto-close forces SQL Server to release the database after the last connection closes, causing transitional locks when a new procedure call arrives immediately after.

Step 4: Review Windows Server 2025 File and Service Permissions

  • Confirm the SQL Server service account has full read/write access to the .mdf/.ldf files under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Use Services.msc to ensure the SQL Server (MSSQLSERVER) service is running under the correct domain/service account, not a restricted local account.
  • Restart the SQL Server service after any permission change:
    net stop MSSQLSERVER && net start MSSQLSERVER

Step 5: Rebuild or Validate Database Integrity

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption as the root cause of state instability.
  • Address any reported allocation or consistency errors before retrying the procedure.

Alternative or Verification Steps

  • Re-run the failing stored procedure manually in SSMS immediately after confirming state_desc = ONLINE to verify resolution.
  • If the error persists, create a minimal repro procedure (SELECT 1) against the same database to isolate whether the issue is procedure-specific or database-wide, then review SQL Server error logs (ERRORLOG in the MSSQL\Log folder) for concurrent state-change events.

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

Troubleshooting Guide: SQL Server Error 970 – Negative Date/DateTime Values in XML Column

Why This Error Happens

This warning occurs because SQL Server 2025’s internal XML storage engine uses an unsigned representation for the year component of xs:date and xs:dateTime values, which cannot natively accommodate negative (BCE) year values stored in the XML instance. When such data exists in an xml typed column, the engine flags it because any attempt to build a primary or selective XML index, or run XQuery methods (.query(), .value(), .nodes()) against that data, will fail or produce incorrect results. This is not a corruption issue but a data-type boundary limitation surfaced during index creation or schema validation on the XML column.

Step-by-Step Resolution Guide

Step 1: Identify the Offending XML Column and Rows

  • Run the following query to locate the column referenced in the error message (replace TableName/ColumnName with values from the error text):
  SELECT object_name(object_id) AS TableName, name AS ColumnName
  FROM sys.columns
  WHERE system_type_id = (SELECT system_type_id FROM sys.types WHERE name = 'xml');
  • Use .exist() or .value() XQuery expressions in a SELECT statement to scan rows for negative year patterns (e.g., values like -0001-01-01).

Step 2: Extract and Audit Negative Date Values

  • Query suspect rows using a pattern match against the XML node text:
  SELECT PrimaryKeyColumn, XmlColumn
  FROM TableName
  WHERE XmlColumn.exist('//*[contains(text(), "-")]') = 1;
  • Manually inspect returned rows in SQL Server Management Studio (SSMS) 21 or Azure Data Studio to confirm negative xs:date or xs:dateTime values (e.g., -0044-03-15).
  • Document each instance for correction, since these values violate the XML Schema Definition (XSD) boundary expected by SQL Server’s XML indexing engine.

Step 3: Correct or Normalize the Negative Date Values

  • Update the XML instances to remove or adjust negative year values using .modify():
  UPDATE TableName
  SET XmlColumn.modify('
    replace value of (//DateNode/text())[1]
    with "0001-01-01"
  ')
  WHERE PrimaryKeyColumn = @AffectedRowId;
  • Alternatively, if negative dates are business-critical (e.g., historical/archaeological data), store them as a separate varchar or decimal representation outside the native xs:date type instead of relying on XML Schema date types.

Step 4: Rebuild the XML Index After Correction

  • Once all negative date instances are resolved, attempt to create or rebuild the index:
  CREATE PRIMARY XML INDEX PXML_TableName_XmlColumn
  ON TableName(XmlColumn);
  • Confirm no Error 970 warnings appear in the Messages tab of SSMS 21 during execution.

Step 5: Validate Application-Level XML Generation

  • Check the upstream application or ETL process (e.g., SSIS packages, .NET XmlSerializer, or third-party XML generators) that produces this XML data.
  • Ensure date-serialization logic does not emit negative-year xs:date/xs:dateTime values going forward, preventing recurrence.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE PRIMARY XML INDEX or CREATE XML INDEX statement — if no Error 970 warning is returned, the negative date values have been successfully remediated.
  • As an alternative if correcting all historical data is not feasible, avoid building primary/selective XML indexes on that column entirely and instead use XML indexes on a computed, shredded column that extracts only the safe (non-date) portions of the XML for indexing purposes.

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

Why This Error Happens

This warning (Error 969) occurs because SQL Server 2025’s XML Schema Collection validator strictly enforces the W3C XML Schema specification for xs:date and xs:dateTime data types, which does not support negative year values (e.g., years before 0001 or BCE dates). When an XSD schema is registered or updated with a default or fixed value containing a negative year, SQL Server automatically truncates or adjusts that value to the nearest valid representation it supports. This typically happens when schemas are migrated from third-party systems, legacy databases, or historical/astronomical data models that allow extended date ranges, including BCE (Before Common Era) timestamps.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection and Element

  • Run the following query to locate the affected XML Schema Collection:
  SELECT name, xml_schema_namespace, schema_collection_id 
  FROM sys.xml_schema_collections 
  WHERE name = '<SchemaCollectionNameFromError>';
  • Cross-reference the element or attribute name reported in the error message (the %.*ls placeholder) with your .xsd source file.
  • Open the source .xsd file in a text editor or Visual Studio to locate the exact default= or fixed= attribute causing the conflict.

Step 2: Correct the Negative Year Value in the XSD Definition

  • Edit the XSD file and locate the problematic element, which will look similar to this:
  <xs:element name="HistoricalDate" type="xs:date" default="-0044-03-15"/>
  • Remove the negative sign or reformat the date to use a supported positive-year equivalent (SQL Server 2025 supports years 0001 through 9999 only):
  <xs:element name="HistoricalDate" type="xs:date" default="0001-01-01"/>
  • Save the corrected .xsd file to a working directory, e.g., C:\SQLSchemas\Corrected\.

Step 3: Drop and Re-Register the XML Schema Collection

  • Since XML Schema Collections cannot be edited in place, drop the existing collection:
  DROP XML SCHEMA COLLECTION [dbo].[YourSchemaCollectionName];
  • Re-create it using the corrected .xsd file:
  CREATE XML SCHEMA COLLECTION [dbo].[YourSchemaCollectionName]
  AS N'<paste corrected XSD content here>';
  • If the schema is referenced by existing XML-typed columns, you may need to temporarily drop that dependency or use ALTER XML SCHEMA COLLECTION to add the corrected namespace instead.

Step 4: Apply SQL Server 2025 Cumulative Updates

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm the current build version via:
  SELECT @@VERSION;
  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as early 2025 builds had stricter XSD validation bugs around date boundary handling that were patched in later CUs.
  • Restart the SQL Server service (MSSQLSERVER) via Services.msc or net stop/start after patching.

Step 5: Validate Application-Layer Date Handling

  • Check the upstream application or ETL process (SSIS, Azure Data Factory, etc.) generating the XML payloads to ensure it does not emit BCE or negative-year timestamps into xs:date/xs:dateTime fields.
  • Add input validation or a transformation step to normalize historical dates into SQL Server’s supported range before insertion.

Alternative or Verification Steps

  • Re-run the original CREATE XML SCHEMA COLLECTION or ALTER XML SCHEMA COLLECTION statement and confirm no Error 969 warning appears in SQL Server Management Studio’s Messages tab or the SQL Server Error Log (Management > SQL Server Logs).
  • If negative-year historical data is a hard business requirement, consider storing those specific date fields as VARCHAR or a custom string-based format instead of xs:date/xs:dateTime, bypassing XML Schema date-type validation entirely.

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

Troubleshooting Guide: SQL Server Error 968 — XML Facet Updated Due to Unsupported Negative Years

Why This Error Happens

This warning occurs because SQL Server’s XML Schema Collection validation engine does not support the xs:date or xs:dateTime values that specify negative years (years with a leading minus sign, representing BCE dates), which are technically valid per the W3C XML Schema specification. When a schema collection is registered or compiled and contains a facet (such as a minInclusive, maxInclusive, or pattern restriction) that implicitly or explicitly allows negative-year date values, SQL Server automatically rewrites the facet boundary to the nearest supported value. This is not a corruption issue but a compatibility limitation between the ISO 8601 subset SQL Server implements internally and the broader XML Schema date-time specification.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Schema Collection and Type

  • Run the following query to locate the affected XML schema collection by name:
  • SELECT name, xml_collection_id FROM sys.xml_schema_collections WHERE name = 'YourSchemaCollectionName';
  • Cross-reference the schema collection name and type reported in the Error 968 message text (the %.*ls placeholders will show the actual type and collection name in your SQL Server error log).
  • Check the SQL Server Error Log (via SSMS > Management > SQL Server Logs, or EXEC sp_readerrorlog;) to capture the exact before/after facet values reported.

Step 2: Review and Correct the XSD Source File

  • Open the original .xsd file used to create or alter the schema collection.
  • Search for any <xs:minInclusive>, <xs:maxInclusive>, or <xs:pattern> facets applied to elements of type xs:date or xs:dateTime.
  • Remove or correct any date boundary values that include a negative year prefix (e.g., -0001-01-01), replacing them with a SQL Server–supported minimum such as 0001-01-01T00:00:00.
  • Save the corrected .xsd file to a controlled path, for example: C:\SQLSchemas\Corrected\YourSchema.xsd.

Step 3: Drop and Recreate the Schema Collection

  • Script out dependent objects (tables, columns, or stored procedures) that reference the XML schema collection, since it cannot be altered once in use in some configurations.
  • Drop the existing collection:
  • DROP XML SCHEMA COLLECTION dbo.YourSchemaCollectionName;
  • Recreate it using the corrected XSD:
  • CREATE XML SCHEMA COLLECTION dbo.YourSchemaCollectionName AS 'contents_of_corrected_xsd_file';
  • Reapply any dependent object bindings that were scripted out in the first sub-step.

Step 4: Apply Latest Cumulative Update

  • Confirm you are running the latest Cumulative Update (CU) for SQL Server 2025, since XML validation engine behavior is periodically patched.
  • Check current build version:
  • SELECT @@VERSION;
  • Download and apply the latest CU from the Microsoft Update Catalog if your build is behind, then restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Alternative or Verification Steps

  • After recreating the schema collection, re-run any INSERT/UPDATE operations that previously triggered Error 968, and confirm the warning no longer appears in sp_readerrorlog output or SSMS Messages pane.
  • If modifying the XSD is not feasible (e.g., third-party schema), wrap the operation in a TRY...CATCH block to suppress and log the warning silently, since it is non-fatal and SQL Server will auto-correct the facet regardless.