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

Troubleshooting Guide: Error 12842 – “The COLLATE CATALOG_DEFAULT clause cannot be used in a constraint”

Why This Error Happens

This error occurs because COLLATE CATALOG_DEFAULT is a dynamic collation reference that resolves its value based on the database catalog at the time of query execution, but constraints (such as CHECK, DEFAULT, or computed column constraints) require a static, deterministic collation to be evaluated and stored at creation time. SQL Server 2025 enforces stricter validation during constraint binding, rejecting any collation clause that cannot be resolved to a fixed value during the CREATE TABLE or ALTER TABLE operation. This typically surfaces when scripts migrated from contained databases (which rely heavily on CATALOG_DEFAULT) are deployed against a non-contained or differently configured database.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Constraint Definition

  • Open the T-SQL script or stored procedure that triggered Error 12842.
  • Search for any CHECK, DEFAULT, or computed column definitions containing COLLATE CATALOG_DEFAULT.
  • Run the following query in SSMS to locate the table/column if the error occurred during deployment:
  SELECT object_name(object_id), definition FROM sys.check_constraints WHERE definition LIKE '%CATALOG_DEFAULT%';

Step 2: Replace CATALOG_DEFAULT with an Explicit Collation

  • Determine the actual collation your database is using by running:
  SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Collation');
  • Edit the constraint definition to replace COLLATE CATALOG_DEFAULT with the explicit collation name returned above (e.g., COLLATE SQL_Latin1_General_CP1_CI_AS).
  • Drop and recreate the constraint using ALTER TABLE YourTable DROP CONSTRAINT ConstraintName; followed by the corrected ADD CONSTRAINT statement.

Step 3: Verify Database Containment Settings

  • Check whether the database was intended to be a Contained Database, since CATALOG_DEFAULT is only valid in that context for certain operations.
  • In SSMS, right-click the database → Properties → Options → verify the Containment Type field.
  • If containment was accidentally set to NONE on Windows Server 2025, either enable partial containment via:
  ALTER DATABASE YourDatabaseName SET CONTAINMENT = PARTIAL;

or permanently remove the CATALOG_DEFAULT reference if containment is not required.

Step 4: Redeploy the Schema Change

  • Re-run the corrected CREATE TABLE or ALTER TABLE script.
  • Confirm no other dependent objects (views, triggers) still reference the old constraint logic with CATALOG_DEFAULT.

Alternative or Verification Steps

  • Verify the fix by querying sys.check_constraints or sys.default_constraints again to confirm the definition column no longer contains CATALOG_DEFAULT and instead shows a static collation name.
  • If the error persists, as an alternative, move the collation logic out of the constraint entirely and enforce it at the application layer or via a scalar function with a hardcoded COLLATE clause instead of relying on catalog-level defaults.

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

Microsoft SQL Server 2025 Troubleshooting Guide: Replication Error 12839

Why This Error Happens

Error 12839 typically occurs when the Replication Distribution Agent or Log Reader Agent loses its connection while attempting to pull data from the Publisher, often due to a timeout threshold being exceeded on large transactions. This is frequently caused by network latency between the Publisher and Subscriber, insufficient QueryTimeout values in the agent profile, or a corrupted/stale snapshot that prevents the agent from synchronizing schema changes. In Windows Server 2025 environments, this can also stem from the new stricter TLS 1.3 enforcement blocking legacy agent connection strings.

Step-by-Step Resolution Guide

Step 1: Verify Agent Connectivity and Timeout Settings

  • Open SQL Server Management Studio (SSMS) and navigate to Replication > Monitor.
  • Check the specific agent profile (Log Reader/Distribution) for the -QueryTimeout parameter; increase it from the default 1800 seconds to 3600 if large transactions are timing out.
  • Run sp_helpdistributor to confirm the distributor connection is active and not blocked by a firewall rule in Windows Defender Firewall.

Step 2: Clear the Agent Cache and Re-initialize the Snapshot

  • Navigate to the Snapshot folder path (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\ReplData).
  • Delete any corrupted .sch or .bcp files associated with the failing publication.
  • Right-click the subscription in SSMS and select Reinitialize Subscription to force a new snapshot generation.

Step 3: Validate SQL Server Service Account Permissions

  • Open Services.msc and locate the “SQL Server Agent” service.
  • Ensure the service account running the Agent has db_owner rights on both the Publisher and Subscriber databases.
  • Confirm the account is not locked out via Active Directory Users and Computers if using a domain service account on Windows Server 2025.

Step 4: Check Windows Server 2025 TLS/Network Policies

  • Open Group Policy Editor (gpedit.msc) and verify that SChannel settings allow the specific cipher suites required by SQL Server 2025 Native Client.
  • Update the connection string in the Publication properties to explicitly allow TLS 1.2 fallback if TLS 1.3 negotiation is failing between legacy Subscribers and the 2025 Publisher.

Alternative or Verification Steps

  • Verify the fix by checking the Replication Monitor for a green status icon on the specific publication and confirm the Latency metric drops below 10 seconds.
  • If the error persists, use sp_replmonitorhelppublication via T-SQL to manually inspect the warning_text column for lingering timeout flags, or roll back to a previous valid snapshot using the Restore Database wizard.

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

Troubleshooting Guide: Error 12840 – CREATE DATABASE Failed During Recollation

Why This Error Happens

Error 12840 occurs when SQL Server 2025 attempts to create a partially contained database and fails during the recollation process, which aligns the database’s collation with the specified containment settings. This typically happens due to an unsupported or invalid collation being specified for the partially contained database, insufficient permissions on system catalogs, or a conflict between the server-level collation and the requested database-level collation. Corrupted system metadata or an incomplete SQL Server installation/update (particularly after an in-place upgrade on Windows Server 2025) can also trigger this failure.

Step-by-Step Resolution Guide

Step 1: Verify the Collation Being Specified

  • Check the exact COLLATE clause used in your CREATE DATABASE statement for typos or deprecated collation names.
  • Run the following query to confirm the collation is valid and supported:
  SELECT * FROM sys.fn_helpcollations() WHERE name = 'Your_Collation_Name';
  • Ensure the collation is compatible with contained database features (avoid binary collations known to cause conflicts in SQL Server 2025 contained mode).

Step 2: Confirm Contained Database Authentication is Enabled

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following to check and enable contained database authentication:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Restart the SQL Server service via Services.msc or run net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025.

Step 3: Check Permissions on System Databases

  • Ensure the login executing CREATE DATABASE has CREATE ANY DATABASE or sysadmin permissions.
  • Verify that the model database (used as the template) is not corrupted or has conflicting collation settings:
  SELECT name, collation_name FROM sys.databases WHERE name = 'model';
  • If model has a mismatched collation, consider resetting it to the server default collation.

Step 4: Repair or Reinstall SQL Server Components

  • Launch SQL Server Installation Center from C:\Program Files\Microsoft SQL Server\160\Setup Bootstrap\ (adjust path for SQL Server 2025 build).
  • Select Repair for the instance exhibiting the issue to fix corrupted binaries or metadata.
  • Apply the latest Cumulative Update (CU) for SQL Server 2025, as collation-handling bugs are often patched in CUs.

Alternative or Verification Steps

  • After applying fixes, re-run the CREATE DATABASE statement with explicit CONTAINMENT = PARTIAL and a known-good collation (e.g., SQL_Latin1_General_CP1_CI_AS) to confirm success.
  • If the error persists, create the database without containment first, then use ALTER DATABASE to enable CONTAINMENT = PARTIAL separately—this isolates whether the failure is containment-specific or collation-specific.

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

Troubleshooting Guide: SQL Server Error 12838 – Replication Data Retrieval Failure

Why This Error Happens

Error 12838 typically occurs when SQL Server’s replication agents (Snapshot, Log Reader, or Distribution Agent) cannot retrieve data because the connection to the publisher or distributor database has been interrupted or improperly authenticated. This is commonly caused by expired or misconfigured SQL Server Agent proxy credentials, network latency between replicated nodes, or a corrupted snapshot folder on the file share used for replication. In Windows Server 2025 environments, this error is frequently exacerbated by stricter default security policies (SMB signing/encryption) that block the replication agent’s access to the snapshot share.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Agent Service Account Permissions

  • Open Services.msc on Windows Server 2025 and confirm the SQL Server Agent service is running under a domain account with sufficient privileges.
  • Ensure this account has db_owner rights on both the publisher and distribution databases.
  • Check that the account has Read/Write access to the snapshot folder path (e.g., \\ServerName\repldata).

Step 2: Reset and Validate the Replication Snapshot Folder

  • Navigate to the snapshot folder defined in Publication Properties (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\ReplData).
  • Delete any orphaned .cab or .bcp files that may be locked or corrupted from a previous failed sync.
  • Run EXEC sp_browsereplcmds in SQL Server Management Studio (SSMS) to confirm no pending stuck commands are blocking retrieval.

Step 3: Adjust SMB and Firewall Settings for Windows Server 2025

  • Since Windows Server 2025 enforces SMB signing by default, verify this setting isn’t blocking the Distribution Agent’s access to the share.
  • Open Local Group Policy Editor > Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options and check Microsoft network client: Digitally sign communications.
  • Ensure Windows Defender Firewall allows inbound/outbound traffic on port 1433 (SQL Engine) and 445 (SMB) between the Publisher, Distributor, and Subscriber nodes.

Step 4: Re-initialize the Subscription

  • In SSMS, right-click the subscription under the Replication folder and select Reinitialize.
  • This forces a new snapshot generation, bypassing potentially corrupted transaction log markers that triggered the original 12838 error.
  • Monitor the Replication Monitor for the “Getting Data” status to ensure it progresses past the previous failure point.

Alternative or Verification Steps

  • Verify the Fix: Open Replication Monitor, select the problematic publication, and check the Agent Status tab. If the status reads “Running” with a recent timestamp and no red error icons, the data retrieval is successful.
  • Alternative Solution: If the error persists after reinitialization, manually recreate the publication via sp_droppublication followed by sp_addpublication, ensuring the @retention period is increased to prevent timeout-related data retrieval failures.

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

Troubleshooting Guide: Error 12836 — ALTER DATABASE Containment Option Failure

Why This Error Happens

This error occurs because SQL Server 2025 performs a validation pass against every SQL module (stored procedures, functions, views, triggers) in the database when switching containment modes, and one or more modules reference objects or syntax incompatible with partial containment rules. Common root causes include modules referencing three-part or four-part names, cross-database queries, uncontained collations, or deprecated system objects that are disallowed under contained database semantics. The underlying cause is almost always a schema-binding or dependency validation failure, not a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Compilation Errors

  • Re-run the ALTER DATABASE statement and scroll up in SSMS or the error log to capture the full chain of errors preceding Error 12836.
  • Example command:
  ALTER DATABASE [YourDB] SET CONTAINMENT = PARTIAL;
  • Note the specific object names and line numbers reported (e.g., “Msg 2812” or “Msg 4121” referencing an invalid object).

Step 2: Audit SQL Modules for Containment-Breaking References

  • Query sys.sqlmodules and sys.sqlexpression_dependencies to find modules with external references:
  SELECT referencing_entity_name, referenced_database_name, referenced_entity_name
  FROM sys.sql_expression_dependencies
  WHERE referenced_database_name IS NOT NULL
     OR is_ambiguous = 1;
  • Look specifically for cross-database three/four-part names, references to master/tempdb system objects, and usage of uncontained collations (e.g., CONVERT with collation not matching database default).

Step 3: Correct or Isolate the Offending Modules

  • Rewrite cross-database calls using linked server syntax or move shared logic into the contained database itself.
  • Replace any uncontained collation references with the database’s contained collation, or explicitly specify a supported collation in the COLLATE clause.
  • For objects that cannot be made compliant (e.g., legacy cross-database triggers), temporarily disable or drop them before conversion, and recreate them post-migration using contained-compatible logic.

Step 4: Validate Compilation Manually Before Re-Attempting

  • Force a recompilation check on all modules without altering containment, using:
  EXEC sp_refreshsqlmodule 'YourSchema.YourProcedure';
  • Alternatively, run DBCC CHECKDB WITH DATAPURITY and sys.dmsqlreferencedentities against each module to confirm no unresolved external dependencies remain.

Step 5: Re-Run the ALTER DATABASE Statement

  • Once all flagged modules are corrected, re-execute:
  ALTER DATABASE [YourDB] SET CONTAINMENT = PARTIAL;
  • Confirm the command completes without raising Error 12836 or any preceding compilation errors.

Alternative or Verification Steps

  • Verify success by querying SELECT containment, containment_desc FROM sys.databases WHERE name = 'YourDB'; and confirming the value reflects PARTIAL (1) as expected.
  • If specific modules cannot be made contained-compliant due to legitimate cross-database business logic, consider keeping the database in NONE containment mode and instead use Contained Database Users selectively, or refactor the cross-database dependency into an ETL/service-layer process outside of T-SQL modules.

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

Troubleshooting Guide: Error 12837 — Contained Database Creation Failure Due to SQL Module Compilation Errors

Why This Error Happens

This error occurs when SQL Server 2025 attempts to validate all SQL modules (stored procedures, functions, views, triggers) during the creation of a contained database, and one or more modules reference objects, schemas, or collations that are not resolvable within the contained database’s isolated scope. Since contained databases cannot reference objects outside their own boundary (such as cross-database references, server-level collations, or objects in master/msdb), any module that violates containment rules will throw a compilation error during the validation pass. This is frequently caused by legacy T-SQL scripts, restored database schemas, or deployment packages that were originally authored for non-contained databases and migrated without containment compliance checks.

Step-by-Step Resolution Guide

Step 1: Review the Full Error Log for Underlying Compilation Errors

  • Error 12837 is a summary error — the actual root cause is listed in preceding error messages in the same batch.
  • Open SQL Server Management Studio (SSMS) and re-run the CREATE DATABASE statement, then scroll up in the Messages tab to capture all errors above 12837.
  • Alternatively, check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the detailed stack of compilation failures.

Step 2: Identify and Fix Containment Violations in SQL Modules

  • Search flagged modules for references to USE [OtherDatabase], three-part or four-part naming (Server.Database.Schema.Object), or sp_ procedures that rely on master.
  • Replace cross-database calls with sys.sp_execute_remote or restructure the logic to avoid breaching the containment boundary.
  • Check for collation mismatches by running:
  SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('dbo.YourProcedureOrTable');

Step 3: Validate Contained Database Authentication and Catalog Settings

  • Ensure CONTAINMENT = PARTIAL is correctly set in your CREATE DATABASE statement syntax.
  • Confirm the contained database authentication server-level configuration is enabled:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025 if the setting was just changed.

Step 4: Recompile and Re-test Modules in Isolation

  • Before re-running CREATE DATABASE, test each flagged module individually in a scratch contained database to confirm it compiles cleanly.
  • Use sys.sql_modules to extract and audit the definitions of all procedures/functions being deployed:
  SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('dbo.FlaggedModule');

Alternative or Verification Steps

  • After applying fixes, re-run the original CREATE DATABASE ... CONTAINMENT = PARTIAL statement and confirm it completes without error 12837 or subsequent warnings.
  • If the error persists, create the database as a non-contained database first, deploy and validate all modules under CONTAINMENT = NONE, then use ALTER DATABASE SET CONTAINMENT = PARTIAL once all containment violations have been resolved.

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

Troubleshooting Guide: Error 12834 — Database Could Not Be Created or Altered to a Contained Database

Why This Error Happens

Error 12834 occurs when SQL Server 2025 attempts to create or alter a database with CONTAINMENT = PARTIAL (or FULL) while the contained database authentication server-level configuration option is disabled. This is a security safeguard, as contained databases allow users to authenticate directly against the database without a corresponding login at the server/instance level, which administrators may want to restrict. The error also surfaces if the instance-level setting was reverted after a configuration change but RECONFIGURE was never executed, leaving the runtime value out of sync with the configured value.

Step-by-Step Resolution Guide

Step 1: Verify the Current Containment Configuration

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance on Windows Server 2025 / Windows 11.
  • Run the following query to check the current state:
  SELECT name, value, value_in_use 
  FROM sys.configurations 
  WHERE name = 'contained database authentication';
  • If value_in_use returns 0, this confirms the feature is disabled at the instance level.

Step 2: Enable Contained Database Authentication at the Instance Level

  • Open a new query window with sysadmin privileges and execute:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Ensure you run RECONFIGURE (not RECONFIGURE WITH OVERRIDE) unless you have validated no conflicting settings exist.
  • Close and reopen your query session to ensure the connection picks up the updated server state.

Step 3: Retry the Database Creation or Alteration

  • Re-run your original command, for example:
  CREATE DATABASE MyContainedDB 
  CONTAINMENT = PARTIAL;

or

  ALTER DATABASE MyExistingDB 
  SET CONTAINMENT = PARTIAL;
  • If altering an existing database, ensure no active connections are blocking the ALTER by setting the database to SINGLE_USER mode temporarily if needed:
  ALTER DATABASE MyExistingDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Step 4: Check Group Policy or Registry Restrictions (Windows Server 2025 Specific)

  • On locked-down Windows Server 2025 environments, Group Policy or third-party security baselines (e.g., CIS, DISA STIG) may re-enforce sp_configure restrictions via SQL Server Policy-Based Management.
  • Navigate to SSMS > Management > Policy Management > Policies and check for any policy named similarly to “Disable Contained Databases” or “Database Containment Restriction.”
  • Disable or modify the policy if it conflicts with your requirement, then repeat Step 2.

Alternative or Verification Steps

  • Verify the fix: Re-run SELECT value_in_use FROM sys.configurations WHERE name = 'contained database authentication'; — it should now return 1. Then confirm the database shows containment_desc = 'PARTIAL' in sys.databases.
  • Alternative: If enabling containment is against organizational security policy, migrate your authentication to server-level logins with mapped database users instead of using contained database users, avoiding the need for this feature entirely.

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

Troubleshooting Guide: SQL Server Error 12835

Why This Error Happens

This informational message is raised automatically when SQL Server alters the containment option of a database (switching it to PARTIAL or NONE). The engine must refresh the definitions of objects—such as views, stored procedures, or functions—that depend on a builtin function, because contained databases resolve collations and metadata differently than non-contained ones. This typically occurs during a containment state transition and is often benign, but it can surface unexpectedly if automated deployment scripts or migration tools change containment settings without accounting for dependent object recompilation.

Step-by-Step Resolution Guide

Step 1: Confirm the Context of the Message

  • Check whether Error 12835 appeared during a deliberate ALTER DATABASE ... SET CONTAINMENT operation.
  • Run the following to check current containment status:
  SELECT name, containment, containment_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If this message appeared unexpectedly (not tied to a containment change), investigate the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the triggering statement.

Step 2: Validate Dependent Object Definitions

  • Identify objects referencing builtin functions that may have been refreshed:
  SELECT referencing_schema_name, referencing_entity_name, referenced_entity_name
  FROM sys.dm_sql_referenced_entities('dbo.YourObjectName', 'OBJECT');
  • Script out and compare the object definitions before and after containment change using SSMS “Generate Scripts” to ensure no unintended logic changes occurred.
  • Pay special attention to objects using functions like SUSER_SNAME(), USER_NAME(), or collation-sensitive string functions, as these are most affected by containment changes.

Step 3: Re-run the Containment Change in a Controlled Window

  • Schedule the containment change during a maintenance window:
  ALTER DATABASE YourDatabaseName SET CONTAINMENT = PARTIAL;
  • Immediately after, recompile affected objects explicitly to force metadata validation:
  EXEC sp_recompile 'dbo.YourObjectName';
  • Review the SQL Server Error Log again to confirm Error 12835 entries correspond only to expected objects.

Step 4: Update Deployment and Migration Scripts

  • If using DACPAC/BACPAC deployment or Azure Data Studio migration tools on Windows Server 2025, add a post-deployment step to validate object recompilation.
  • Avoid toggling containment settings repeatedly in automated CI/CD pipelines without a verification gate.

Alternative or Verification Steps

  • Query sys.messages for message ID 12835 to confirm it is a Level 10 informational message (not a failure), ensuring no rollback or application impact occurred.
  • If object behavior seems incorrect post-refresh, drop and recreate the specific dependent object manually, then re-apply the containment change to force a clean metadata refresh.

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

Troubleshooting Guide: Error 12832 – Database Could Not Be Created or Altered to a Contained Database

Why This Error Happens

Error 12832 occurs when SQL Server 2025 attempts to create or alter a database as a “contained database,” but the contained database authentication server-level configuration option is disabled. This setting acts as a security gatekeeper, preventing databases from using partial or full containment features unless explicitly enabled by a system administrator. Additionally, this can occur if the instance has Policy-Based Management (PBM) policies actively blocking containment changes, or if the SQL Server service account lacks the necessary permissions to modify server-level configurations.

Step-by-Step Resolution Guide

Step 1: Verify Current Containment Configuration

  • Open SQL Server Management Studio (SSMS) or connect via sqlcmd on your Windows Server 2025/Windows 11 machine.
  • Run the following query to check the current state:
  EXEC sp_configure 'contained database authentication';
  • Check the run_value column; if it reads 0, this confirms the feature is disabled.

Step 2: Enable Contained Database Authentication

  • Execute the following T-SQL script to enable the feature at the server level:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  GO
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  GO
  • Ensure you run this in the context of a login with sysadmin server role permissions.

Step 3: Retry the Database Creation/Alteration

  • Navigate back to your database creation script or SSMS wizard.
  • Re-attempt the operation using the correct containment syntax:
  CREATE DATABASE [YourDbName] CONTAINMENT = PARTIAL;
  • If altering an existing database, use:
  ALTER DATABASE [YourDbName] SET CONTAINMENT = PARTIAL;

Step 4: Check for Policy-Based Management (PBM) Restrictions

  • Open SSMS and navigate to Management > Policy Management > Policies.
  • Look for any active policies named similarly to “Contained Database Restriction” or “Surface Area Configuration.”
  • Disable or modify these policies if they are set to Prevent evaluation mode, as they may override your manual configuration changes.

Alternative or Verification Steps

  • Verify the Fix: Run SELECT name, containment, containment_desc FROM sys.databases; to confirm the target database now shows PARTIAL instead of NONE.
  • Alternative Fix: If sp_configure changes do not persist after a service restart, check for Group Policy Objects (GPOs) on the Windows Server 2025 domain controller that might be resetting registry-based SQL configurations, and restart the SQL Server (MSSQLSERVER) service via services.msc to apply changes immediately.

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

Troubleshooting Guide: SQL Server Error 12833

Why This Error Happens

Error 12833 occurs when SQL Server cannot convert a database to a contained database because the contained database authentication server-level configuration option is disabled. This setting acts as a gatekeeper that must be explicitly enabled before any database on the instance can be created or altered with CONTAINMENT = PARTIAL or CONTAINMENT = FULL. Without this flag enabled via sp_configure, SQL Server 2025 blocks the containment operation entirely to prevent unauthorized use of contained database authentication, which has distinct security implications.

Step-by-Step Resolution Guide

Step 1: Verify the Current Configuration State

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to your SQL Server 2025 instance.
  • Run the following query to check the current value:
EXEC sp_configure 'contained database authentication';
  • If the run_value column shows 0, this confirms the setting is disabled and is the cause of Error 12833.

Step 2: Enable the “Show Advanced Options” Flag

  • Since contained database authentication is an advanced option, you must unlock advanced settings first.
  • Execute the following commands in a new query window:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;

Step 3: Enable Contained Database Authentication

  • With advanced options visible, turn on the specific feature required for containment.
  • Run the following T-SQL command:
EXEC sp_configure 'contained database authentication', 1;
RECONFIGURE;
  • Unlike some server-level settings, this does not require a service restart; it takes effect immediately upon RECONFIGURE.

Step 4: Re-attempt the Database Creation or Alteration

  • Navigate back to your original script or Windows Server 2025 management console task.
  • Re-run the CREATE DATABASE or ALTER DATABASE statement with the CONTAINMENT = PARTIAL clause.
  • Example syntax to test:
ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = PARTIAL;

Alternative or Verification Steps

  • Verification: Query the sys.databases system view (SELECT name, containment, containment_desc FROM sys.databases;) to confirm the containment_desc column now reads PARTIAL or FULL for your target database instead of NONE.
  • Alternative: If sp_configure changes are rejected due to permissions, ensure your login has the ALTER SETTINGS server-level permission or is a member of the sysadmin fixed server role, as standard db_owner roles cannot modify server-wide containment policies.

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

Why This Error Happens

This warning occurs because a database has been marked as “contained” (CONTAINMENT = PARTIAL), but the server-level configuration option contained database authentication is still disabled (set to 0). SQL Server 2025 restricts the creation of users with passwords inside contained databases unless this server-wide flag is explicitly enabled, as it introduces a security boundary that bypasses the traditional login-mapping model. Essentially, the database schema supports containment, but the instance-level security gate has not been opened to allow it.

Step-by-Step Resolution Guide

Step 1: Verify the Current Server Configuration

  • Open SQL Server Management Studio (SSMS) or a query tool connected to the instance.
  • Run the following T-SQL command to check the current state of the configuration:
EXEC sp_configure 'contained database authentication';
  • Look at the run_value column. If it returns 0, this confirms the root cause.

Step 2: Enable Contained Database Authentication

  • Execute the following commands to enable the “advanced options” view and turn on the specific setting:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'contained database authentication', 1;
RECONFIGURE;
GO
  • Note: Unlike many sp_configure changes, this specific setting does not require a service restart; it takes effect immediately upon reconfiguration.

Step 3: Validate the Database-Specific Containment Setting

  • Ensure the specific database you are working with is actually set to PARTIAL containment (required for contained users).
  • Check the setting via the GUI: Right-click the Database -> Properties -> Options -> Verify “Containment type” is set to Partial.
  • Alternatively, verify via query:
SELECT name, containment, containment_desc 
FROM sys.databases 
WHERE name = 'YourDatabaseName';

Step 4: Create or Re-Map the Contained User

  • If the user previously failed to create due to the error, re-attempt creating the contained user with a password directly in the context of the specific database (not master):
USE YourDatabaseName;
GO
CREATE USER ContainedUser WITH PASSWORD = 'StrongP@ssw0rd!';

Alternative or Verification Steps

  • Verification: Attempt to log in using the newly created contained user credentials via a new connection in SSMS, selecting the specific database name in the “Connect to Database” field under Connection Properties. If the login succeeds without being prompted for a Windows Login mapping, the fix is successful.
  • Alternative: If enterprise security policies strictly prohibit enabling contained database authentication at the server level (due to compliance/hardening standards), do not override this setting. Instead, migrate the strategy to use traditional SQL Logins mapped to Windows Server 2025 Active Directory accounts or standard SQL Server logins mapped at the instance level.

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

Troubleshooting Guide: Error 12829 – Numbered Stored Procedures Not Supported in Contained Databases

Why This Error Happens

This error occurs because SQL Server 2025 does not support numbered stored procedures (procedures using the ;1, ;2 naming convention) when the database is configured as a contained database. Contained databases isolate metadata and dependencies from the instance level, and numbered stored procedures rely on instance-level system catalog behaviors that conflict with this isolation model. The error is triggered the moment a CREATE, ALTER, or EXECUTE statement references a numbered procedure group inside a database with CONTAINMENT = PARTIAL or CONTAINMENT = FULL.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Stored Procedure

  • Run the following query to locate numbered stored procedures in the affected database:
  SELECT name, number FROM sys.sysobjects WHERE number > 0;
  • Cross-reference the procedure name returned in the error message (the %.*ls placeholder) with your deployment scripts or migration package.
  • Check your application’s object creation scripts for patterns like CREATE PROCEDURE dbo.MyProc;2.

Step 2: Refactor Numbered Procedures into Standard Procedures

  • Numbered stored procedures have been deprecated since SQL Server 2008 and are fully unsupported in contained databases, so the only permanent fix is to split them into individually named procedures.
  • Replace CREATE PROCEDURE dbo.MyProc;1 and dbo.MyProc;2 with distinct objects such as dbo.MyProc_Step1 and dbo.MyProc_Step2.
  • Update any application connection strings or EXEC calls referencing the old numbered syntax (e.g., EXEC dbo.MyProc;2) to use the new procedure names.

Step 3: Verify Database Containment Settings

  • Open SQL Server Management Studio (SSMS) on your Windows Server 2025 or Windows 11 machine and connect to the instance.
  • Right-click the database in Object Explorer, select Properties, then navigate to the Options page to confirm the Containment Type value.
  • If containment was enabled unintentionally, you can revert it via:
  ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = NONE;
  • Only revert containment if your application does not depend on contained database features like contained users.

Step 4: Redeploy and Re-test the Procedure Creation Scripts

  • Drop any failed/partial numbered procedure objects using:
  DROP PROCEDURE IF EXISTS dbo.MyProc;
  • Re-run your corrected deployment script that creates individually named procedures instead of numbered groups.
  • Confirm no errors are thrown during the CREATE PROCEDURE execution in the Messages pane of SSMS.

Alternative or Verification Steps

  • Re-run the query SELECT name, number FROM sys.sysobjects WHERE number > 0; — it should return zero rows if all numbered procedures have been successfully refactored.
  • If immediate remediation isn’t feasible, set CONTAINMENT = NONE as a temporary workaround to restore legacy numbered procedure support, but plan to migrate away from this deprecated feature before any future SQL Server upgrade.

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

Troubleshooting Guide: Error 12830 – ‘user options’ Must Be Zero With Contained Databases

Why This Error Happens

This error occurs because SQL Server 2025 enforces a restriction where the server-level user options configuration value must remain at 0 when one or more contained databases exist on the instance. The user options setting controls default server-wide session behaviors (such as ANSI_WARNINGS or ARITHABORT), but contained databases are designed to manage these session-level settings independently to ensure portability between instances. When a non-zero value is detected alongside an enabled contained database, the Database Engine blocks the configuration change or database operation to prevent conflicting session behaviors, triggering Error 12830.

Step-by-Step Resolution Guide

Step 1: Verify the Current Server Configuration

  • Open SQL Server Management Studio (SSMS) or a query tool connected to your instance.
  • Run the following T-SQL command to check the current value:
  EXEC sp_configure 'user options';
  • Look at the run_value and config_value columns; if the value is anything other than 0, this is the root cause.

Step 2: Reset the ‘user options’ Value to Zero

  • Execute the following commands to reset the configuration:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'user options', 0;
  RECONFIGURE;
  • This resets the bitmask value governing default connection settings back to the required default.

Step 3: Restart the SQL Server Service

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

Step 4: Re-enable Contained Database Authentication

  • Once the server restarts, verify that the contained database authentication setting is still correctly enabled at the instance level:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Check the specific database property to ensure CONTAINMENT = PARTIAL is still intact:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';

Alternative or Verification Steps

  • Verification: Re-run EXEC sp_configure 'user options'; and confirm the run_value is 0. Attempt to create or alter a contained database again to ensure Error 12830 no longer appears.
  • Alternative Fix: If application connection strings rely on specific SET options (like ARITHABORT ON), move these settings into the application’s connection string or login trigger rather than the server-wide user options setting to maintain compliance with contained database requirements.

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

Troubleshooting Guide: SQL Server Error 12827

Why This Error Happens

Error 12827 occurs because contained databases in SQL Server restrict certain operations on temporary tables for cross-database compatibility reasons. Specifically, SQL Server does not allow user-named constraints (such as PRIMARY KEY, UNIQUE, DEFAULT, or CHECK constraints with explicit names) on temp tables when the database containment level is set to PARTIAL or FULL. This restriction exists because user-named constraints on temp tables could create naming collisions or dependency issues across sessions in a contained database environment, where metadata isolation is strictly enforced.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Code

  • Locate the script, stored procedure, or application code creating the temp table (prefixed with # or ##).
  • Search specifically for CONSTRAINT keywords followed by a user-defined name, such as CONSTRAINT PK_MyTempTable_ID PRIMARY KEY.
  • Note the exact line number referenced in the SQL Server error log or SSMS query results pane.

Step 2: Remove the User-Defined Constraint Name

  • Modify the CREATE TABLE #TempTable statement to remove the explicit constraint name.
  • Change syntax from CONSTRAINT PK_Temp PRIMARY KEY (ID) to simply PRIMARY KEY (ID).
  • Allow SQL Server to generate a system-named constraint automatically, which is permitted in contained databases.
  • Re-run the script in SQL Server Management Studio (SSMS) connected to the Windows Server 2025 instance to confirm the syntax change resolves the error.

Step 3: Verify the Database Containment Setting

  • Open SSMS and navigate to Databases > [Your Database] > Properties > Options.
  • Check the Containment Type field; if it is set to Partial, this behavior is expected and by design.
  • If containment was enabled unintentionally, you can reset it by running:
  ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = NONE;
  • Note: Changing containment type requires exclusive database access and may require closing active connections first.

Step 4: Update Application or ORM-Generated Scripts

  • If the temp table creation script is generated by an ORM (e.g., Entity Framework, Dapper) or a third-party application, check the data access layer or migration scripts.
  • Update any hardcoded CREATE TABLE templates to exclude named constraints for temporary table objects specifically.
  • Redeploy the updated application binaries or scripts to the Windows Server 2025 environment.

Alternative or Verification Steps

  • Verify the Fix: Re-execute the original stored procedure or script; successful execution without Error 12827 confirms the constraint naming issue is resolved.
  • Alternative Workaround: If renaming constraints is not feasible due to legacy code dependencies, set the database containment back to NONE using the ALTER DATABASE command in Step 3, provided contained database features (like contained users) are not required for that specific database.

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

Troubleshooting Guide: Error 12828 – User-Defined Type Reference in Contained Databases

Why This Error Happens

This error occurs when a local temporary table (#table) being created inside a contained database attempts to reference a user-defined data type (UDT) or user-defined type alias that resides in tempdb. Because contained databases are designed to minimize dependencies on the system/global tempdb context for collation, metadata, and type resolution, SQL Server 2025 blocks this cross-database reference to preserve containment boundaries. Essentially, the engine cannot resolve the type definition because it refuses to “break out” of the contained database scope to look it up in tempdb.

Step-by-Step Resolution Guide

Step 1: Verify the Containment Status of the Database

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the containment setting:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If containment_desc returns PARTIAL, this confirms the restriction is active and expected.

Step 2: Relocate or Redefine the User-Defined Type

  • Instead of creating the UDT in tempdb, create the type directly within the contained database itself.
  • Use CREATE TYPE scoped to the local database rather than relying on a global tempdb definition:
  USE YourDatabaseName;
  GO
  CREATE TYPE dbo.MyUserType FROM INT NOT NULL;
  GO
  • Update your temp table creation script to reference this new local type instead of the tempdb version.

Step 3: Refactor Temp Table Creation Logic

  • Modify the T-SQL script creating the local temp table (#MyTempTable) to avoid implicit dependencies on tempdb..sys.types.
  • Explicitly define the schema of the temp table without casting to the now-inaccessible tempdb type:
  CREATE TABLE #MyTempTable (
      ID INT,
      Value dbo.MyUserType -- Must reference the type created in Step 2
  );
  • Save and re-deploy the stored procedure or script.

Step 4: Adjust Containment Settings (If Immediate Fix is Required)

  • If migrating the type definition is not immediately feasible, you can temporarily disable containment to allow the cross-database reference (Not recommended for production security policies).
  • Navigate to Database Properties > Options > Containment Type in SSMS and set it to None.
  • Alternatively, run:
  ALTER DATABASE YourDatabaseName SET CONTAINMENT = NONE;

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific stored procedure or script that triggered Error 12828. If the temp table creation completes without the 12828 error referencing tempdb, the type resolution is successful.
  • Alternative Check: Query sys.types within the specific contained database (not tempdb) to ensure the is_user_defined flag is set to 1 for the newly created type, confirming it no longer relies on an external system reference.

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

Troubleshooting Guide: Error 12824 — Contained Database Authentication Not Enabled

Why This Error Happens

This error occurs because the contained database authentication server-level configuration option is disabled (set to 0) by default in SQL Server 2025 for security hardening purposes. When you attempt to create, alter, or connect to a contained database without this setting enabled at the instance level, SQL Server blocks the operation since contained databases rely on this flag to manage authentication independently of the master database. This is a safeguard to prevent unintended exposure of contained users who bypass traditional login-based authentication.

Step-by-Step Resolution Guide

Step 1: Verify Current Configuration State

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the instance using an account with sysadmin privileges.
  • Run the following query to check the current value:
EXEC sp_configure 'contained database authentication';
  • Look at the config_value and run_value columns; if both show 0, this confirms the setting is disabled.

Step 2: Enable the Advanced Options Flag

  • Since this is an advanced configuration option, you must first unlock advanced settings visibility.
  • Run the following commands in a new query window:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
  • This step is required before SQL Server will allow modification of contained database authentication.

Step 3: Enable Contained Database Authentication

  • Execute the following commands to turn the setting on at the server level:
EXEC sp_configure 'contained database authentication', 1;
RECONFIGURE;
  • Ensure no syntax errors are returned; SQL Server should respond with “Configuration option changed” messages for both commands.

Step 4: Restart Dependent Services (If Applicable)

  • On Windows Server 2025, open Services.msc and confirm the SQL Server (MSSQLSERVER or named instance) service did not require a restart (this setting is dynamic and typically does not need one).
  • If using Always On Availability Groups, repeat Steps 1–3 on every replica in the AG, as this is a server-level (not database-level) setting and does not replicate automatically.

Step 5: Retry the Original Operation

  • Re-run the CREATE DATABASE ... CONTAINMENT = PARTIAL or ALTER DATABASE statement that originally triggered Error 12824.
  • Confirm the operation completes without raising the error again.

Alternative or Verification Steps

  • Verify the fix: Run EXEC sp_configure 'contained database authentication'; again and confirm run_value now equals 1. You can also check sys.configurations for the is_dynamic and value_in_use columns to confirm the change took effect without a service restart.
  • Alternative approach: If you lack sysadmin rights to run sp_configure, use PowerShell with the SqlServer module (Set-SqlConfiguration or Invoke-Sqlcmd cmdlet) from an elevated session on Windows Server 2025, provided the executing account has the appropriate SQL Server server-level permissions (ALTER SETTINGS).

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

Troubleshooting Guide: Error 12826 – Contained Database Authentication Disabled via RECONFIGURE WITH OVERRIDE

Why This Error Happens

This error occurs when an administrator runs sp_configure 'contained database authentication', 0 followed by RECONFIGURE WITH OVERRIDE while one or more contained databases are actively attached to the SQL Server 2025 instance. The WITH OVERRIDE clause forces the configuration change without validating whether contained databases currently depend on that setting, effectively bypassing the normal safety check. As a result, contained users who authenticate directly against the database (rather than the server-level login) lose their ability to connect, and no new contained databases can be created until the setting is reverted.

Step-by-Step Resolution Guide

Step 1: Identify Affected Contained Databases

  • Open SQL Server Management Studio (SSMS) or a query window connected to the instance.
  • Run the following query to list all contained databases on the server:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE containment <> 0;
  • Note each database name, as these are the ones currently impacted by the authentication disruption.

Step 2: Re-Enable Contained Database Authentication

  • Reverse the misconfiguration by setting the option back to enabled (1) at the server level.
  • Execute the following in a query window with sysadmin privileges:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Avoid using WITH OVERRIDE this time, since it is unnecessary when enabling the feature.

Step 3: Validate Contained User Logins

  • Confirm that contained users can authenticate directly against the affected database without referencing a server-level login.
  • Use the following test connection string pattern (via sqlcmd or application connection):
  sqlcmd -S <ServerName> -d <ContainedDBName> -U <ContainedUser> -P <Password>
  • If login still fails, check sys.database_principals in the specific contained database to ensure the user account exists with authentication_type_desc = 'DATABASE'.

Step 4: Audit and Restrict Future Use of WITH OVERRIDE

  • Review SQL Server Agent jobs, deployment scripts, or DevOps pipelines (e.g., Azure DevOps, GitHub Actions) that may have issued the original RECONFIGURE WITH OVERRIDE command.
  • Add a safeguard check before any future reconfiguration, such as querying sys.databases for containment <> 0 and halting the script if contained databases are found.
  • Update internal runbooks to require explicit approval before using WITH OVERRIDE on any authentication or security-related configuration option.

Alternative or Verification Steps

  • Verify the fix by re-running EXEC sp_configure 'contained database authentication'; and confirming the run_value column shows 1.
  • If contained users still cannot authenticate after re-enabling the setting, restart the SQL Server service via Services.msc (Windows Server 2025/Windows 11) or run NET STOP MSSQLSERVER && NET START MSSQLSERVER from an elevated PowerShell session to force the configuration to take full effect.

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

Troubleshooting Guide: Error 12822 — spmigrateusertocontained Password Hash Algorithm Failure

Why This Error Happens

Error 12822 occurs because sp_migrate_user_to_contained attempts to copy the password hash from a login to a contained database user, but the source login’s password was hashed using a legacy algorithm (such as SHA-1) that SQL Server 2025 no longer supports for this migration path. SQL Server 2025 enforces stronger password hashing standards (SHA-256 or higher) by default, and the stored procedure will refuse to transfer a hash it considers cryptographically weak. This typically affects logins created on older SQL Server versions (2012 or earlier) that were later upgraded or migrated without a password reset.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Login’s Hash Algorithm

  • Run the following query to inspect the password hash version for the login in question:
  • SELECT name, LOGINPROPERTY(name, 'PasswordHash') AS HashValue FROM sys.sql_logins WHERE name = 'YourLoginName';
  • Check the length and prefix of the hash value — legacy SHA-1 hashes are shorter and begin with 0x0100, while SHA-256 hashes begin with 0x0200.
  • Cross-reference the SQL Server version the login was originally created on, if known.

Step 2: Reset the Login Password to Force Rehashing

  • Since you cannot force a hash upgrade without resetting the credential, issue an ALTER LOGIN command to reset the password:
  • ALTER LOGIN [YourLoginName] WITH PASSWORD = 'NewStrongP@ssw0rd!';
  • This forces SQL Server 2025 to regenerate the password hash using the current supported algorithm (SHA-256).
  • Notify the affected user or application owner of the password change before proceeding, as this will invalidate the old credential.

Step 3: Re-run the Containment Migration Procedure

  • Execute sp_migrate_user_to_contained again against the target contained database now that the login has a modern hash:
  • EXEC sp_migrate_user_to_contained @username = 'YourLoginName', @rebind_indexes = 1, @print_log = 1;
  • Confirm the @print_log output shows a successful hash copy with no 12822 errors.

Step 4: Validate Contained Database Compatibility Level

  • Ensure the target database’s compatibility level is set to 170 (SQL Server 2025) or higher, as older compatibility levels can misreport hash support:
  • ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025 / Windows 11 if changes don’t take effect immediately.

Step 5: Audit for Bulk Legacy Logins

  • If multiple logins are affected, query all SQL logins for outdated hash prefixes to batch-remediate before they cause repeated 12822 errors:
  • SELECT name FROM sys.sql_logins WHERE LOGINPROPERTY(name, 'PasswordHash') IS NOT NULL AND LEFT(CONVERT(VARCHAR(10), LOGINPROPERTY(name, 'PasswordHash'), 1), 6) = '0x0100';
  • Schedule a maintenance window to reset passwords for all flagged accounts.

Alternative or Verification Steps

  • Verify the fix by querying the contained user’s password hash directly in the target database using SELECT name, LOGINPROPERTY(name, 'PasswordHash') FROM sys.database_principals WHERE name = 'YourLoginName'; and confirming it now shows a 0x0200 prefix.
  • If resetting the password is not feasible immediately, use CREATE USER [YourLoginName] WITH PASSWORD = 'TempP@ss123!' directly in the contained database as a manual workaround, then synchronize credentials later through your application’s standard password rotation process.

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

Troubleshooting Guide: Error 12823 – spmigrateusertocontained Cannot Find Login

Why This Error Happens

This error occurs when the database user you are attempting to migrate to a contained user is not mapped to a valid SQL Server login at the instance level, meaning the SID link between sys.database_principals and sys.server_principals is broken or missing. This commonly happens with orphaned users, users created directly in the database without a corresponding login, or users whose login was dropped after the user was created. It can also occur if the user is a built-in principal (like guest or dbo) that the stored procedure does not support for containment conversion.

Step-by-Step Resolution Guide

Step 1: Verify the User-to-Login Mapping

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the following query to check for orphaned users:
  EXEC sp_change_users_login 'Report';
  • Confirm whether the specific user referenced in the error has a matching SID in sys.server_principals.

Step 2: Re-Link or Recreate the Missing Login

  • If the login is missing, create a new SQL login matching the user’s existing SID using:
  CREATE LOGIN [LoginName] WITH PASSWORD = 'StrongPassword123!', SID = 0x0101000000000000...;
  • Alternatively, if the login exists but is mismatched, remap it using:
  ALTER USER [UserName] WITH LOGIN = [LoginName];
  • Ensure the SID value is copied exactly from the sys.database_principals table for that user.

Step 3: Exclude Unsupported System Principals

  • Check if the user causing the error is dbo, guest, sys, or INFORMATION_SCHEMA.
  • If so, exclude these from your migration script since sp_migrate_user_to_contained does not support converting built-in principals.
  • Update your migration script path (typically located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Scripts\) to filter these out using a WHERE clause on type_desc = 'SQL_USER'.

Step 4: Re-run the Migration Procedure

  • Execute the stored procedure again against the specific user:
  EXEC sp_migrate_user_to_contained 
      @username = N'UserName', 
      @rename = N'copy_login_name', 
      @disablelogin = N'true';
  • Confirm the Database Engine service account under Windows Server 2025 has sufficient permissions (ALTER ANY USER and CONTROL on the database).

Alternative or Verification Steps

  • Verify: Query sys.database_principals and check that the authentication_type_desc column now reads DATABASE instead of INSTANCE, confirming successful containment.
  • Alternative: If the login truly cannot be recovered, drop the orphaned user entirely using DROP USER [UserName] and recreate it fresh as a contained database user with CREATE USER [UserName] WITH PASSWORD = 'StrongPassword123!'.

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

Troubleshooting Guide: Error 12821 in SQL Server 2025

Why This Error Happens

This error occurs because the user specified in the sp_migrate_user_to_contained procedure is referenced in an EXECUTE AS clause within a module (such as a stored procedure, function, or trigger) that has been digitally signed with a certificate or asymmetric key. SQL Server blocks this migration because converting the user to a contained database user would break the security context binding established by the signature, since contained users cannot be mapped the same way to signed module executions. Essentially, the engine is protecting the integrity of the signed module’s execution context, which relies on the login/user existing in its original, non-contained state.

Step-by-Step Resolution Guide

Step 1: Identify the Signed Module and Associated User

  • Run the following query to find modules signed with certificates or asymmetric keys that reference the user in question:
  • SELECT * FROM sys.crypt_properties WHERE major_id = OBJECT_ID('YourModuleName');
  • Cross-reference this with sys.database_principals to confirm the user tied to the EXECUTE AS clause.
  • Note the certificate or asymmetric key name used for signing, as you will need it in Step 3.

Step 2: Drop the Existing Signature from the Module

  • Before migrating the user, you must remove the digital signature temporarily.
  • Execute the following command in SQL Server Management Studio (SSMS) or Azure Data Studio:
  • DROP SIGNATURE FROM [YourModuleName] BY CERTIFICATE [YourCertificateName];
  • If an asymmetric key was used instead, substitute BY ASYMMETRIC KEY [YourKeyName] in the command above.

Step 3: Execute the User Migration

  • With the signature removed, the user is no longer locked to the signed execution context.
  • Run the migration procedure again:
  • EXEC sp_migrate_user_to_contained @username = 'YourUserName', @rebind_messages = 1;
  • Verify the command completes without throwing Error 12821.

Step 4: Re-Apply the Digital Signature

  • Once the user has been successfully migrated to a contained user, restore the security signature to the module.
  • Use the following syntax to re-sign the module:
  • ADD SIGNATURE TO [YourModuleName] BY CERTIFICATE [YourCertificateName] WITH PASSWORD = 'YourStrongPassword';
  • Ensure the certificate still exists in the master database or user database depending on your original configuration.

Alternative or Verification Steps

  • To verify the fix, query sys.database_principals and check that the authentication_type_desc for the user now reads DATABASE instead of INSTANCE, confirming successful containment.
  • If re-signing fails due to a missing certificate, restore the certificate from a backup file using CREATE CERTIFICATE... FROM FILE before attempting Step 4 again.

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

Troubleshooting Guide: Error 12819 – spmigrateusertocontained Fails on Non-Contained Database

Why This Error Happens

Error 12819 occurs because the stored procedure sp_migrate_user_to_contained is designed exclusively for partially or fully contained databases, and it checks the database’s CONTAINMENT property before executing. If the target database was created or left with CONTAINMENT = NONE (the default setting), SQL Server 2025 blocks the migration of logins to contained users since there is no containment boundary to migrate them into. This is not a corruption or permissions issue, but rather a configuration mismatch between the procedure’s requirements and the database’s current containment state.

Step-by-Step Resolution Guide

Step 1: Verify the Current Containment Status

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to check the containment level of the target database:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • Confirm that containment_desc returns NONE, which confirms the root cause.

Step 2: Enable Contained Database Authentication at the Instance Level

  • Before altering the database, ensure the instance-level setting allows contained databases.
  • Run the following in a query window with sysadmin privileges:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • This step is mandatory on both Windows Server 2025 and Windows 11 local instances, as the feature is disabled by default for security hardening.

Step 3: Alter the Database Containment Setting

  • Change the database containment level from NONE to PARTIAL (the only supported containment type in SQL Server 2025).
  • Execute the following T-SQL command:
  ALTER DATABASE YourDatabaseName 
  SET CONTAINMENT = PARTIAL;
  • Ensure no active connections are blocking the ALTER statement; if necessary, set the database to SINGLE_USER mode temporarily:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Step 4: Re-run the Migration Procedure

  • Once containment is set to PARTIAL, execute the original migration command again.
  • Use the following syntax to migrate the specific login to a contained user:
  EXEC sp_migrate_user_to_contained 
      @username = 'YourUserName', 
      @rename = 'copy_login', 
      @disablelogin = 'true';
  • Switch the database back to MULTI_USER mode if you changed it in Step 3:
  ALTER DATABASE YourDatabaseName SET MULTI_USER;

Alternative or Verification Steps

  • Verification: Query sys.database_principals for the migrated user and check that the authentication_type_desc column now reads DATABASE instead of INSTANCE, confirming the user is fully contained.
  • Alternative: If altering containment is not permitted due to organizational policy (e.g., high-availability groups requiring uniform containment settings across replicas), manually create a contained user with a password using CREATE USER [UserName] WITH PASSWORD = 'StrongPassword123!'; instead of relying on the migration procedure.

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

Troubleshooting Guide: Error 12820 — spmigrateusertocontained Fails on SQL Login with Password

Why This Error Happens

Error 12820 occurs because sp_migrate_user_to_contained is designed to migrate database users that map to Windows logins or Windows groups into contained database users. When the stored procedure encounters a database user backed by a SQL Server Authentication login with a password, or a user type other than a standard SQL Login mapping (such as a certificate-mapped or asymmetric key-mapped user), it cannot safely migrate the authentication context into the contained database boundary. This restriction exists because contained database users require explicit password assignment at the user level, and the migration procedure does not automatically transfer or re-hash login credentials for security reasons.

Step-by-Step Resolution Guide

Step 1: Identify the User Type Causing the Conflict

  • Run the following query against the target database to inspect user mappings:
  SELECT dp.name, dp.type_desc, sp.name AS login_name, sp.type_desc AS login_type
  FROM sys.database_principals dp
  LEFT JOIN sys.server_principals sp ON dp.sid = sp.sid
  WHERE dp.type IN ('S', 'U', 'G');
  • Confirm whether the user is tied to a SQL Login (type_desc = 'SQL_LOGIN') rather than a Windows Login or Group.

Step 2: Manually Create a Contained Database User Instead

  • Since sp_migrate_user_to_contained only supports Windows-based principals, manually convert the SQL Login user by creating a contained user with a password:
  CREATE USER [YourUserName] WITH PASSWORD = 'StrongPassword123!';
  • If the user already exists as a non-contained SQL user, drop and recreate it:
  DROP USER [YourUserName];
  CREATE USER [YourUserName] WITH PASSWORD = 'StrongPassword123!';

Step 3: Verify Database Containment Settings

  • Ensure the database containment type is set to PARTIAL before attempting any contained user operations:
  SELECT name, containment, containment_desc
  FROM sys.databases
  WHERE name = 'YourDatabaseName';
  • If containment is set to NONE, update it:
  ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = PARTIAL;

Step 4: Re-Run Migration Only for Eligible Windows-Based Users

  • Filter your migration script to exclude SQL Logins and only target Windows logins/groups:
  EXEC sp_migrate_user_to_contained
      @username = N'DOMAIN\WindowsUser',
      @rebind_indexes = 1,
      @print_info = 1;
  • Confirm the @username parameter never references a SQL Login account.

Step 5: Update Application Connection Strings (If Applicable)

  • If the SQL Login user was migrated manually with a new password, update any application or service connection strings in web.config, appsettings.json, or ODBC/DSN configurations on Windows Server 2025 to reflect the new contained user credentials.

Alternative or Verification Steps

  • Verify the fix by querying sys.database_principals again and confirming the authentication_type_desc column shows DATABASE for the migrated or newly created user.
  • If manual creation is not feasible for bulk users, consider scripting a loop that filters only Windows-authenticated accounts from sys.server_principals before invoking sp_migrate_user_to_contained, avoiding SQL Login entries entirely.

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

Troubleshooting Guide: SQL Server Error 12817 — “The Reference to the Variable…”

Why This Error Happens

Error 12817 in SQL Server typically occurs when a Transact-SQL batch or stored procedure references a local variable that is out of scope, malformed, or was declared within a different batch separated by a GO statement. This is commonly caused by a corrupted or incomplete script deployment, a mismatch between variable declaration and usage scope, or an interrupted session during execution of a parameterized query. In some cases, this error surfaces on Windows Server 2025 / Windows 11 due to incompatible client driver versions (such as an outdated ODBC or OLE DB provider) mishandling variable binding during remote procedure calls.

Step-by-Step Resolution Guide

Step 1: Validate the T-SQL Script Scope

  • Open the script or stored procedure in SQL Server Management Studio (SSMS) and check for any GO statements that may be splitting variable declarations from their usage.
  • Ensure variables declared with DECLARE @VariableName exist within the same batch where they are referenced.
  • Look for copy-paste errors where variable names may have mismatched casing or extra whitespace (SQL Server treats @Var1 and @var1 differently in some collation contexts).

Step 2: Check Client Driver and Connection Provider Versions

  • Navigate to Control Panel > Programs and Features on Windows Server 2025 / Windows 11 and verify the installed version of “Microsoft OLE DB Driver for SQL Server” or “ODBC Driver 18 for SQL Server.”
  • Update to the latest driver via the official Microsoft Download Center if the version is older than 18.x.
  • Restart the SQL Server service after updating: run services.msc, locate “SQL Server (MSSQLSERVER),” and select Restart.

Step 3: Repair or Redeploy the Stored Procedure

  • Use SSMS to script out the affected stored procedure (Right-click > Script Stored Procedure as > ALTER To).
  • Manually inspect the CREATE PROCEDURE syntax for missing parameter declarations in the header.
  • Drop and recreate the procedure using:
  DROP PROCEDURE IF EXISTS dbo.YourProcedureName;
  GO
  CREATE PROCEDURE dbo.YourProcedureName
      @VariableName INT
  AS
  BEGIN
      -- procedure body
  END
  GO

Step 4: Clear the Plan Cache and Retest

  • Run DBCC FREEPROCCACHE; in a new query window to eliminate any cached execution plans referencing the broken variable scope.
  • Re-execute the original query or procedure call to confirm the error no longer appears.

Alternative or Verification Steps

  • Run the query independently (outside of any wrapping application code) in SSMS to confirm whether the error originates from the T-SQL itself or from the client-side application layer.
  • If the error persists, use sp_helptext 'YourProcedureName' to extract the exact stored procedure definition stored in SQL Server and compare it line-by-line against your source control version to detect silent corruption during deployment.

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

Troubleshooting Guide: Error 12818 — RECONFIGURE Failed for ‘Contained Database Authentication’

Why This Error Happens

This error occurs because SQL Server 2025 enforces a safety check that prevents administrators from disabling the contained database authentication server-level setting while one or more contained databases still exist on the instance. The engine blocks the standard RECONFIGURE command because doing so silently could break authentication for users who rely on database-level logins within those contained databases. SQL Server requires an explicit WITH OVERRIDE clause to confirm that the administrator understands this risk and wants to proceed anyway.

Step-by-Step Resolution Guide

Step 1: Identify Existing Contained Databases

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to list all databases with containment enabled:
  • SELECT name, containment, containment_desc FROM sys.databases WHERE containment <> 0;
  • Note down the database names, as you will need to decide whether to keep or convert them before disabling the feature.

Step 2: Decide Whether to Convert or Override

  • If the contained databases are no longer needed in contained mode, change them back to NONE containment using: ALTER DATABASE [YourDBName] SET CONTAINMENT = NONE;
  • If the contained databases must remain as-is, proceed directly to the override method in Step 3 instead of modifying each database.

Step 3: Apply the RECONFIGURE WITH OVERRIDE Command

  • Open a new query window in SSMS with sysadmin privileges.
  • Execute the following T-SQL block exactly:
  • EXEC sp_configure 'contained database authentication', 0;
  • RECONFIGURE WITH OVERRIDE;
  • This forces the server-level setting to apply immediately, bypassing the safety check, even though contained databases still exist.

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

  • On Windows Server 2025 or Windows 11, open SQL Server Configuration Manager.
  • Navigate to SQL Server Services, right-click your instance (e.g., SQL Server (MSSQLSERVER)), and select Restart.
  • This ensures the configuration change is fully propagated to all connected sessions and cached execution plans.

Alternative or Verification Steps

  • Verify the setting took effect by running EXEC sp_configure 'contained database authentication'; and confirming the run_value column now shows 0.
  • If users in contained databases suddenly lose the ability to authenticate after this change, consider reverting with EXEC sp_configure 'contained database authentication', 1; RECONFIGURE; until you can properly migrate those logins to server-level authentication.

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

Troubleshooting Guide: SQL Server Error 12816

Why This Error Happens

This error occurs when a user-defined type (UDT) or XML schema collection was created under a database collation that differs from the collation currently active in the context of the operation (such as during replication, database mirroring, Always On Availability Groups, or cross-database queries). Because collation affects how identifiers, string comparisons, and schema validation rules resolve, SQL Server cannot guarantee the type or schema will behave identically on the target, so it blocks the operation to prevent silent data corruption or logic mismatches. This commonly surfaces after a database restore/migration where the source and destination instances were installed with different default collations, or when tempdir/model database collations diverge from a newly created or moved user database.

Step-by-Step Resolution Guide

Step 1: Identify the Collation Mismatch

  • Run the following query on both the source and target databases to compare metadata collation:
  SELECT name, collation_name FROM sys.databases;
  • Check the specific type/schema referenced in the error using:
  SELECT name, collation_name FROM sys.types WHERE name = 'YourTypeName';
  • Note the exact collation strings reported in the error message (%.*ls placeholders will show the actual collation names in your SQL Server error log).

Step 2: Align Database and Instance Collations

  • Open SQL Server Configuration Manager (Windows Server 2025 / Windows 11) and verify the instance-level collation under instance properties.
  • If the user database collation differs from the instance/tempdb collation, you cannot simply ALTER DATABASE collation if the database already contains incompatible objects — instead, script out the affected types/XML schema collections.
  • Drop and recreate the type or XML schema collection explicitly specifying the matching collation:
  CREATE XML SCHEMA COLLECTION dbo.MySchemaCollection AS N'<schema definition>' ;
  • Ensure you use COLLATE clauses on any character-based columns feeding into the type definition to force alignment.

Step 3: Rebuild or Migrate the Affected Database

  • If the mismatch stems from a cross-server migration (e.g., restoring a .bak file from a server with a different default collation), export data using SQL Server Import/Export Wizard instead of a raw restore, which re-maps collation-dependent metadata.
  • Alternatively, rebuild system databases with the correct collation using the setup command line:
  setup.exe /QUIET /ACTION=rebuilddatabase /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=BUILTIN\Administrators /SQLCOLLATION=SQL_Latin1_General_CP1_CI_AS
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after rebuilding.

Step 4: Validate Replication and AG Configurations

  • If this occurs in a replication topology or Always On Availability Group, confirm the Publisher, Distributor, and Subscriber (or Primary/Secondary replicas) all share identical server-level collations.
  • Reconfigure replication using matching collation settings before re-initializing snapshots.

Alternative or Verification Steps

  • Verify the fix by re-running the operation that originally triggered Error 12816 (e.g., re-execute the replication snapshot, mirroring setup, or cross-database query) and confirm no error is thrown.
  • As a quick validation, run SELECT DATABASEPROPERTYEX('YourDB', 'Collation'); against both source and target databases — the returned collation strings must match exactly before retrying the operation.

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

Troubleshooting Guide: SQL Server Error 12814 – Metadata Collation Mismatch

Why This Error Happens

Error 12814 occurs when a database, replicated object, or contained database references a table, column, or object name whose binary resolution depends on collation, and the collation configured on the target instance or database differs from the collation on the source or current metadata context. This is common during cross-database queries, replication setup, database migration, or restoring a database between servers with different default collations. Since collation affects how characters are sorted and compared, SQL Server cannot guarantee the object name resolves to the same underlying object on both ends, so it blocks the operation to prevent data corruption or incorrect object binding.

Step-by-Step Resolution Guide

Step 1: Identify the Collation Mismatch

  • Run SELECT name, collation_name FROM sys.databases; on both the source and target instances to compare collation settings.
  • Check the server-level collation using SELECT SERVERPROPERTY('Collation'); on both Windows Server 2025 / Windows 11 SQL instances involved.
  • Note the exact object named in the error message (the %.*ls placeholders will show the real object and collation names in your actual error output).

Step 2: Align Database or Column-Level Collation

  • Alter the specific column collation to match using: ALTER TABLE dbo.YourTable ALTER COLUMN YourColumn VARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS;
  • If the mismatch is database-wide, modify the database default collation (note: this does not retroactively change existing column collations): ALTER DATABASE YourDatabase COLLATE SQL_Latin1_General_CP1_CI_AS;
  • For contained databases, verify collation consistency under Database Properties > Options > Collation in SQL Server Management Studio (SSMS) 21.

Step 3: Rebuild or Recreate Affected Objects

  • If the object (view, stored procedure, or synonym) was created under the old collation context, drop and recreate it after the collation change is applied.
  • Use sp_helptext 'YourObjectName' to extract the original definition before dropping it, then redeploy the script.
  • Refresh any linked server metadata using EXEC sp_refreshsqlmodule 'YourObjectName'; to force SQL Server to re-resolve references.

Step 4: Update Linked Servers and Replication Configurations

  • If the error surfaces during replication, open Replication Monitor and verify the Publisher and Subscriber collation settings match under Publication Properties > Articles.
  • For linked servers, run EXEC sp_serveroption 'YourLinkedServer', 'collation compatible', 'true'; only if collations are confirmed identical; otherwise, set to 'false' to force safe runtime comparisons.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear cached metadata plans.

Alternative or Verification Steps

  • Re-run the original query, replication job, or restore operation that triggered Error 12814 and confirm it completes without the collation resolution error in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • If the error persists, use DBCC FREEPROCCACHE; to clear the plan cache and eliminate stale execution plans that may still reference the old collation metadata, then retry the operation.

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

Troubleshooting Guide: SQL Server Error 12815

Why This Error Happens

This error occurs when a column referenced in a cross-database or cross-server query (often during replication, Change Data Capture, or linked server operations) resolves to a different collation in the target database’s metadata than in the source or current session metadata. This typically happens after a database or server collation change, a database restore from an instance with a different default collation, or when columns were created under inconsistent collation settings during schema migration. SQL Server’s metadata resolution engine detects this mismatch and halts the operation to prevent silent data corruption or incorrect comparison/sorting behavior.

Step-by-Step Resolution Guide

Step 1: Identify the Collation Mismatch Source

  • Run the following query to check the collation of the server, database, and the specific column in question:
SELECT SERVERPROPERTY('Collation') AS ServerCollation;
SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Collation') AS DatabaseCollation;
SELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID('YourTableName');
  • Note the discrepancy between the “target metadata collation” and the “current metadata collation” referenced in the error message text.

Step 2: Align the Column Collation

  • Use the ALTER TABLE statement to force the column to match the expected collation (replace with your actual target collation, e.g., SQL_Latin1_General_CP1_CI_AS):
ALTER TABLE YourTableName
ALTER COLUMN YourColumnName NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS;
  • If this is affecting a linked server or distributed query, verify the linked server’s collation compatibility settings via sp_serveroption with the collation compatible flag set to true.

Step 3: Rebuild Affected Metadata Objects

  • If the error surfaces during replication or CDC, drop and reinitialize the replication publication/subscription or disable and re-enable CDC on the affected table so metadata is regenerated under the correct collation.
  • For general schema objects, drop and recreate any views, computed columns, or indexes that reference the mismatched column to force metadata refresh.

Step 4: Validate Database-Level Collation Consistency

  • If the issue is widespread across many columns, consider running a full collation realignment using ALTER DATABASE ... COLLATE (only if application compatibility allows this):
ALTER DATABASE YourDatabaseName COLLATE SQL_Latin1_General_CP1_CI_AS;
  • Confirm this change does not break existing stored procedures or constraints that rely on the prior collation.

Alternative or Verification Steps

  • Re-run the original query, replication job, or CDC capture process that triggered Error 12815 and confirm it completes without collation warnings.
  • If the error persists, use DBCC CHECKDB and sys.dm_exec_describe_first_result_set to cross-verify that all metadata layers (table, view, and procedure) now report a consistent collation value.

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

Troubleshooting Guide: SQL Server Error 12811

Why This Error Happens

This error occurs when the user options configuration value at the SQL Server instance level is set to a non-zero value while attempting to enable or interact with a contained database. Contained databases require full control over connection-level default settings (such as ANSIWARNINGS, ANSIPADDING, etc.) because they must be able to define these settings independently of the instance. When the instance-wide user options bitmask overrides these defaults, SQL Server blocks the operation to prevent configuration conflicts between the instance and the contained database.

Step-by-Step Resolution Guide

Step 1: Check the Current user options Value

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to check the current configuration value:
EXEC sp_configure 'user options';
  • Look at the run_value and config_value columns. If the value is anything other than 0, this is the root cause.

Step 2: Reset the user options Value to 0

  • Run the following T-SQL commands to reset the value and apply the change:
EXEC sp_configure 'user options', 0;
GO
RECONFIGURE WITH OVERRIDE;
GO
  • Note that this is a dynamic setting in most cases, but a service restart is recommended to ensure it takes full effect across all sessions.

Step 3: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance (e.g., SQL Server (SQLEXPRESS)).
  • Right-click and select Restart to apply the configuration change fully.
  • Alternatively, use PowerShell as an Administrator:
Restart-Service -Name "MSSQLSERVER" -Force

Step 4: Enable the Contained Database Setting

  • Once the user options value is confirmed to be 0, re-enable contained database authentication at the instance level:
EXEC sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO
  • Verify that the specific database you are working with has its CONTAINMENT property set correctly:
ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = PARTIAL;

Alternative or Verification Steps

  • Verification: Re-run EXEC sp_configure 'user options'; and confirm that both the run_value and config_value columns display 0. Attempt to create or alter the contained database again to ensure Error 12811 no longer appears.
  • Alternative: If RECONFIGURE WITH OVERRIDE does not resolve the issue immediately, check for connection-string level overrides (e.g., applications setting SET options like ARITHABORT or QUOTED_IDENTIFIER manually), as these can sometimes mimic the symptoms of a non-zero user options value even after the server-side fix.

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

Troubleshooting Guide: SQL Server Error 12813

Why This Error Happens

Error 12813 occurs when SQL Server encounters stored procedures, functions, or other compiled objects that reference database-level containment features (such as contained users or collation settings tied to containment) after the database’s containment option has been altered or reverted. This typically happens when a database is switched from PARTIAL or FULL containment back to NONE while objects still depend on containment-specific metadata or catalog views. It can also surface after a database restore, upgrade migration, or replication process that leaves cached execution plans referencing outdated containment configurations.

Step-by-Step Resolution Guide

Step 1: Verify Current Containment Setting

  • Run the following query to check the database’s containment status:
  • SELECT name, containment, containment_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the value is 0 (NONE), 1 (PARTIAL), or 2 (FULL) and compare it against what your application expects.

Step 2: Identify the Failing Object and Dependencies

  • Query sys.sql_modules or use sp_depends to locate the exact procedure or function referenced in the error message.
  • Open the object definition in SQL Server Management Studio (SSMS) and look for references to contained database users, sys.database_principals, or cross-database queries that assume containment.
  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for additional stack trace context.

Step 3: Realign Containment Settings with Object Requirements

  • If objects require containment, re-enable it using:
  • ALTER DATABASE YourDatabaseName SET CONTAINMENT = PARTIAL;
  • If containment should remain disabled, recompile the affected objects using:
  • EXEC sp_recompile 'SchemaName.ObjectName';
  • Ensure the contained database authentication server-level setting is correctly configured via sp_configure if PARTIAL containment is required.

Step 4: Clear Cached Plans and Rebuild Objects

  • Flush the procedure cache for the specific database to remove stale execution plans:
  • DBCC FREEPROCCACHE;
  • Drop and recreate the failing stored procedure or function to force a clean compilation against the current containment state.

Step 5: Restart SQL Server Service (If Needed)

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to clear any lingering metadata cache issues tied to containment.

Alternative or Verification Steps

  • Re-run the original query or stored procedure call that triggered Error 12813 and confirm it compiles and executes without exception.
  • As an alternative, restore the database from a pre-change backup if containment was altered unintentionally during a migration, then reapply schema changes incrementally while testing compilation after each step.

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

Why This Error Happens

This error occurs because SQL Server 2025 prevents you from disabling database containment (setting it to NONE) while contained users with passwords still exist in the database. Contained users rely on the containment boundary for authentication, so removing that boundary while they still exist would orphan their credentials and create a security inconsistency. SQL Server blocks the operation at the metadata level until every contained user with a password is explicitly dropped.

Step-by-Step Resolution Guide

Step 1: Identify All Contained Users With Passwords

  • Connect to the target database using SQL Server Management Studio (SSMS) or sqlcmd on Windows Server 2025 / Windows 11.
  • Run the following query to list offending users:
SELECT name, type_desc, authentication_type_desc
FROM sys.database_principals
WHERE authentication_type = 2; -- 2 = DATABASE authentication (contained user)
  • Note every name returned — these are the contained users with passwords that are blocking the containment change.

Step 2: Remove or Migrate the Contained Users

  • For each user identified, decide whether to drop them or migrate them to login-based (Windows or SQL Server) authentication.
  • To drop a contained user:
DROP USER [ContainedUserName];
  • If the user’s access must be preserved, create a corresponding server-level login first, then re-map the user to that login before dropping the contained version:
CREATE LOGIN [LoginName] WITH PASSWORD = 'StrongPassword!123';
USE [YourDatabase];
ALTER USER [ContainedUserName] WITH LOGIN = [LoginName];

Step 3: Re-Run the Containment Change

  • After all contained users with passwords are removed, re-attempt the containment property change:
ALTER DATABASE [YourDatabase] SET CONTAINMENT = NONE;
  • If the error persists, re-run the query from Step 1 to confirm no contained users remain — sometimes system-generated or replicated users are missed on the first pass.

Step 4: Check for Replication or Availability Group Dependencies

  • On Windows Server 2025 environments running Always On Availability Groups, verify the database isn’t part of a group that enforces contained authentication for failover logins.
  • Temporarily remove the database from the availability group (if safe to do so) before changing containment, then re-add it afterward.

Alternative or Verification Steps

  • Verify the fix by querying sys.databases and confirming the containment column shows 0 (NONE) for the target database: SELECT name, containment_desc FROM sys.databases WHERE name = 'YourDatabase';
  • If the error still occurs, check for orphaned contained users in system views like sys.database_principals with type_desc = 'SQL_USER' and authentication_type_desc = 'DATABASE', as these can sometimes be hidden behind custom schemas or ownership chains.

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

Troubleshooting Guide: SQL Server Error 12810

Why This Error Happens

Error 12810 occurs when a T-SQL statement, command-line utility, or configuration script includes the same option or argument more than once within a single command. This is commonly triggered by syntax errors in BACKUP, RESTORE, or CREATE/ALTER statements where a WITH clause option (such as COMPRESSION, CHECKSUM, or STATS) is duplicated. It can also occur when automated scripts, maintenance plans, or third-party backup tools concatenate parameters without validating for duplicates, especially after migration to SQL Server 2025’s updated parser.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement

  • Check the SQL Server Error Log or Event Viewer (Windows Logs > Application) for the exact statement that triggered Error 12810.
  • Note the placeholder value %.*ls in the error message — SQL Server will substitute this with the actual duplicated option name at runtime (e.g., “COMPRESSION”, “STATS”, or “NAME”).
  • Use SQL Server Management Studio (SSMS) Activity Monitor or sys.dm_exec_query_stats to trace the query if it originates from an application.

Step 2: Review and Correct the T-SQL Syntax

  • Open the script in SSMS or Azure Data Studio and locate the WITH clause in the command (common in BACKUP DATABASE, RESTORE DATABASE, or CREATE INDEX statements).
  • Manually scan for repeated keywords, for example:
  BACKUP DATABASE [YourDB]
  TO DISK = 'C:\Backups\YourDB.bak'
  WITH COMPRESSION, CHECKSUM, COMPRESSION;
  • Remove the duplicate option, keeping only a single instance of each parameter.

Step 3: Audit Maintenance Plans and Automated Scripts

  • Open SQL Server Agent (in SSMS) and inspect any Maintenance Plans or Jobs under SQL Server Agent > Jobs.
  • Check the generated T-SQL in the Job Step properties (right-click Job Step > Edit > Command) for auto-generated duplicate flags, which often occurs after upgrading maintenance plan templates to SQL Server 2025.
  • If using PowerShell (SqlServer module) or sqlcmd, review scripts for repeated -C, -E, or -S flags passed to the executable.

Step 4: Update or Reinstall Affected Tools

  • If a third-party backup or ETL tool is generating the malformed command, check for a vendor patch compatible with SQL Server 2025’s stricter parser validation.
  • Navigate to C:\Program Files\Microsoft SQL Server\160\DTS\Binn\ (or the relevant version path) and verify SSIS packages aren’t injecting duplicate connection string parameters.
  • Reinstall or update the tool, then re-run the job to confirm the parameter list is clean.

Step 5: Test the Corrected Statement

  • Execute the cleaned-up T-SQL statement directly in SSMS against a test database.
  • Confirm no Error 12810 appears and the operation completes successfully.

Alternative or Verification Steps

  • Run SELECT * FROM sys.messages WHERE message_id = 12810; in SSMS to confirm the exact error text and severity level, ensuring your fix aligns with the expected syntax.
  • If the error persists after correcting the script, enable SQL Server extended events (sqlserver.error_reported) to capture the full raw statement text in real time for deeper inspection.

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

Troubleshooting Guide: Error 12807 — “The option ‘%.*ls’ cannot be set on non-contained database”

Why This Error Happens

This error occurs when a T-SQL statement attempts to configure a containment-specific database option (such as DB_CHAINING, AUTHENTICATION, or CONTAINMENT-related settings) on a database where containment is set to NONE. SQL Server 2025 strictly validates that certain options are only applicable to partially or fully contained databases, and it rejects the operation if the target database was never converted or created with containment enabled. This commonly happens after migrating scripts from a contained database environment to a standard one, or when an automated deployment pipeline applies a uniform set of ALTER DATABASE options across multiple databases without checking each database’s containment state.

Step-by-Step Resolution Guide

Step 1: Verify the Current Containment Status of the Database

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check the containment setting:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If containment_desc returns NONE, this confirms the root cause of Error 12807.

Step 2: Enable Database Containment (If Business Requirements Allow)

  • Ensure the contained database authentication server-level configuration is enabled first:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • Alter the database to set partial containment:
  ALTER DATABASE [YourDatabaseName] SET CONTAINMENT = PARTIAL;
  • Confirm no active connections are blocking the change; use SET SINGLE_USER WITH ROLLBACK IMMEDIATE if necessary before altering.

Step 3: Remove or Modify the Conflicting Option in Your Script

  • If containment should not be enabled for this database (e.g., due to security policy on Windows Server 2025 environments), locate the offending ALTER DATABASE statement in your deployment script or application code.
  • Remove the specific containment-dependent option (e.g., DB_CHAINING ON, AUTHENTICATION = DATABASE) from the script.
  • Re-run the deployment pipeline or script against the non-contained database without that clause.

Step 4: Audit Deployment Scripts for Environment-Specific Logic

  • Check your CI/CD pipeline (Azure DevOps, GitHub Actions, or SSDT publish profiles) for hardcoded ALTER DATABASE commands.
  • Add conditional logic to check containment_desc before applying containment-specific options:
  IF (SELECT containment FROM sys.databases WHERE name = DB_NAME()) <> 0
  BEGIN
      ALTER DATABASE [YourDatabaseName] SET DB_CHAINING ON;
  END
  • Save and version-control the updated script to prevent recurrence in future deployments.

Step 5: Restart SQL Server Service to Clear Cached Configuration (If Issue Persists)

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart.
  • Alternatively, use PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • After applying the fix, re-run the original ALTER DATABASE statement that triggered Error 12807 and confirm it executes without error.
  • If the issue persists, use sys.dm_exec_requests to check for blocking sessions preventing containment changes, or review the SQL Server Error Log (Management > SQL Server Logs in SSMS) for additional context around Error 12807.

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

Troubleshooting Guide: Error 12808 in SQL Server 2025

Why This Error Happens

This error occurs when a transactional command attempts to modify database-containment-specific options (such as DB_CHAINING, TRUSTWORTHY exceptions, or contained user authentication settings) within the same batch or transaction that is setting the database containment level to NONE. SQL Server 2025 enforces strict sequencing because containment-related metadata must be fully cleared before other dependent options can be evaluated, preventing the engine from reaching an inconsistent state. This typically happens when migration scripts or automated deployment tools (like DACPAC deployments) bundle ALTER DATABASE statements together instead of sequencing them properly.

Step-by-Step Resolution Guide

Step 1: Isolate the ALTER DATABASE Statements

  • Open the failing script in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Locate the ALTER DATABASE [YourDB] SET CONTAINMENT = NONE statement.
  • Ensure this statement is executed as a standalone batch, separated by a GO statement from any other ALTER DATABASE commands that modify options like DB_CHAINING ON/OFF or TRUSTWORTHY ON/OFF.

Step 2: Re-sequence the Script Execution Order

  • Execute the containment change first in its own transaction and commit it.
  • Example sequence to type into a New Query window in SSMS:
  • ALTER DATABASE [YourDB] SET CONTAINMENT = NONE;
  • GO
  • ALTER DATABASE [YourDB] SET DB_CHAINING ON;
  • GO

Step 3: Check for Blocking Automated Deployment Scripts

  • If the error originates from a DACPAC or Redgate deployment, check the generated deployment script (usually found in the build output folder, e.g., C:\Builds\Latest\Deploy\Script.PostDeployment.sql).
  • Manually edit the publish profile XML to exclude “Block on possible data loss” containment batching, or manually split the generated script using the sqlpackage.exe /p:GenerateSmartDefaults=true flag to force separate batches.

Step 4: Restart the Target Service and Clear Cache

  • Navigate to the Windows Server 2025 Services console (services.msc).
  • Restart the SQL Server (MSSQLSERVER) service to clear any cached execution plans that might be holding a lock on the previous containment state.
  • Re-run the corrected script.

Alternative or Verification Steps

  • Verification: Run SELECT name, containment, containment_desc FROM sys.databases WHERE name = 'YourDB'; to confirm the containment value has successfully changed to 0 (NONE) before verifying the subsequent options were applied correctly.
  • Alternative: If the script cannot be edited, wrap the containment change in its own explicit transaction block (BEGIN TRAN... COMMIT;) separate from the options change to force SQL Server to process them sequentially rather than as a single parsed batch.

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

Troubleshooting Guide: SQL Server Error 12805 – Index Name Too Long for Temp Table

Why This Error Happens

This error occurs when an explicitly named index on a temporary table (#table or ##table) exceeds SQL Server’s maximum character limit for temp table index identifiers. Because SQL Server internally appends a unique numeric suffix to temp table object names to distinguish them across sessions, the effective namespace available for the index name itself is shorter than the standard 128-character identifier limit. This typically surfaces in dynamically generated SQL scripts, ORM-generated queries, or migration scripts where index names are concatenated from variables without length validation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Index Definition

  • Locate the exact CREATE INDEX or inline index statement referenced in the error message %.*ls.
  • Check stored procedures, ETL packages (SSIS), or application code that dynamically builds temp table DDL.
  • Search for # or ## table creation scripts in your codebase or SQL Server Profiler/Extended Events trace output.

Step 2: Shorten the Index Name

  • Rename the index to stay within the safe limit (generally under 116 characters to account for SQL Server’s internal suffixing of temp objects).
  • Use abbreviated, standardized naming conventions, e.g., IX_Temp_ColName instead of fully descriptive concatenated names.
  • If the name is dynamically generated (e.g., via sp_executesql or string concatenation in C#/PowerShell), add a truncation function:
  SET @IndexName = LEFT(@IndexName, 100);

Step 3: Update Dynamic SQL Generation Logic

  • If using an ORM (Entity Framework, Dapper) or a migration tool (Flyway, DbUp), inspect the naming convention templates used for index generation on temp tables.
  • Add a validation check in your build pipeline or stored procedure to raise a custom error before execution if the generated name exceeds 100 characters:
  IF LEN(@IndexName) > 100
      RAISERROR('Index name exceeds safe temp table limit', 16, 1);

Step 4: Apply the Fix in SQL Server Management Studio (SSMS) or Azure Data Studio

  • Open the affected script in SSMS 21 (compatible with SQL Server 2025) on your Windows Server 2025 or Windows 11 machine.
  • Replace the long index name and re-run the script in a test environment (tempdb) first to confirm the CREATE INDEX statement succeeds.
  • Deploy the corrected script to production once validated.

Alternative or Verification Steps

  • Verify the fix by running the corrected script against tempdb and confirming the index is created without Error 12805 using SELECT name FROM tempdb.sys.indexes WHERE object_id = OBJECT_ID('tempdb..#YourTable').
  • As an alternative, let SQL Server auto-generate the index name by omitting an explicit name in the CREATE INDEX clause (where applicable), avoiding manual length management entirely.

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

Troubleshooting Guide: Error 12803 – Containment Cannot Be Enabled for System Database

Why This Error Happens

Error 12803 occurs because SQL Server 2025 does not permit database containment to be enabled on system databases such as master, model, msdb, or tempdb. The CONTAINMENT property is a database-scoped setting designed exclusively for user databases, allowing them to be more portable and isolated from instance-level metadata. When an administrator or an automated deployment script attempts to run ALTER DATABASE with a CONTAINMENT clause against a system database, the SQL Server Engine rejects the operation at the parser/validation layer, throwing this error as a hard-coded restriction rather than a configurable permission issue.

Step-by-Step Resolution Guide

Step 1: Identify the Target Database in Your Script

  • Open the T-SQL script or deployment job that triggered the error.
  • Locate the ALTER DATABASE [DatabaseName] SET CONTAINMENT = PARTIAL (or FULL) statement.
  • Confirm whether [DatabaseName] resolves to master, model, msdb, or tempdb.
  • If using a variable or parameter (e.g., @DBName), print its runtime value using PRINT @DBName; to verify it isn’t accidentally pointing to a system database.

Step 2: Correct the Script to Target a User Database

  • Replace the system database reference with the intended user database name.
  • Example corrected syntax:
  ALTER DATABASE [YourUserDB]
  SET CONTAINMENT = PARTIAL;
  • If the intent was to create a new contained database, use CREATE DATABASE with containment specified at creation time instead of altering an existing system database:
  CREATE DATABASE [YourUserDB] CONTAINMENT = PARTIAL;

Step 3: Validate Instance-Level Containment Settings

  • If containment is required broadly, ensure the contained database authentication server configuration is enabled first:
  EXEC sp_configure 'contained database authentication', 1;
  RECONFIGURE;
  • This setting does not affect system databases but is a prerequisite for any user database to support containment.

Step 4: Re-run the Deployment or Migration Script

  • Execute the corrected script against the proper user database.
  • Check SQL Server Error Logs via SQL Server Management Studio (SSMS) > Management > SQL Server Logs or the path C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025 to confirm no further containment-related errors appear.

Alternative or Verification Steps

  • Verify the fix by querying the containment status of the target database: SELECT name, containment, containment_desc FROM sys.databases WHERE name = 'YourUserDB'; — the containment_desc column should return PARTIAL (not NONE).
  • If the script is part of a third-party tool or automated DACPAC/BACPAC deployment, inspect the deployment contributor or publish profile (.publish.xml) to ensure it isn’t incorrectly flagging system databases for containment during provisioning.

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

Troubleshooting Guide: SQL Server Error 12804 – Contained Database Containment Breach

Why This Error Happens

This error occurs because SQL Server 2025 enforces strict containment boundaries for databases configured with CONTAINMENT = PARTIAL, blocking any feature that relies on instance-level (uncontained) objects or settings. Common triggers include using cross-database queries, referencing server-level logins, linked servers, or features like replication and CDC that inherently depend on metadata stored outside the database boundary. Essentially, the engine detects that a T-SQL statement, stored procedure, or configuration option is trying to “reach outside” the contained database into the instance scope, which violates the isolation model designed to make contained databases portable.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Feature Causing the Breach

  • Check the SQL Server Error Log or the client application error message for the %ls placeholder value, which names the specific offending feature (e.g., CHANGE_TRACKING, xp_cmdshell, or a three-part name query).
  • Run the query that triggered the error in SSMS/Azure Data Studio connected directly to the instance to capture the full error text, including the object name.
  • Use Extended Events with the containment_change or error_reported event to log containment violations in real time:
  CREATE EVENT SESSION [ContainmentDebug] ON SERVER
  ADD EVENT sqlserver.error_reported(WHERE ([error_number]=(12804)));

Step 2: Review and Modify the Offending T-SQL Code

  • Replace any cross-database references (e.g., OtherDB.dbo.TableName) with contained alternatives like Elastic Query, synonyms pointed to a linked server, or data replication into the contained database itself.
  • If the issue stems from server-level logins, migrate authentication to a contained database user (SQL authentication or Windows principal) using:
  CREATE USER [AppUser] WITH PASSWORD = 'StrongPassword!123';
  • Remove dependencies on instance-level objects like master..sysxlogins, global temp tables (##temp), or OPENROWSET/OPENQUERY calls that aren’t permitted in contained mode.

Step 3: Validate Database Containment Settings

  • Open SSMS, right-click the database → Properties → Options, and confirm the Containment Type is set correctly (None or Partial) based on intended use.
  • Alternatively, verify via T-SQL:
  SELECT name, containment, containment_desc 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If the feature absolutely requires instance-level scope (e.g., certain replication topologies), consider setting CONTAINMENT = NONE temporarily, understanding this sacrifices portability.

Step 4: Apply the Latest Cumulative Update

  • Navigate to the Microsoft Update Catalog and confirm Windows Server 2025 / Windows 11 has the latest SQL Server 2025 Cumulative Update installed, as early builds had stricter (sometimes over-aggressive) containment checks later relaxed via patches.
  • Check your current build number:
  SELECT @@VERSION;
  • Install the update via SQL Server Setup → Maintenance → Edition Upgrade/Patch or through Windows Update if integrated.

Alternative or Verification Steps

  • After making changes, re-run the original failing query/application workflow and confirm Error 12804 no longer appears in the SQL Server Error Log (EXEC sp_readerrorlog 0, 1, '12804';).
  • If the feature is mission-critical and cannot be made contained-compliant, switch the database CONTAINMENT property back to NONE as a fallback, then re-architect the dependent process using Elastic Database Queries or Service Broker for cross-boundary communication instead.

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

Troubleshooting Guide: SQL Server Error 12800 – Ambiguous Temp Table Reference

Why This Error Happens

This error occurs when multiple temporary tables with the same name exist in different scopes (such as nested stored procedures or batches) within the same session, causing SQL Server’s name resolution engine to be unable to determine which #tempTable instance to reference. It is typically triggered by deeply nested procedure calls where a temp table created in an outer scope shares an identical name with one created in an inner scope. This naming collision is a logical/coding issue rather than a server configuration failure, but it can also surface due to connection pooling reusing a session where temp tables were not properly cleaned up.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Temp Table Scope

  • Open SQL Server Management Studio (SSMS) and locate the exact stored procedure or script referenced in the error message.
  • Use sp_helptext 'ProcedureName' to review the full definition of the procedure for nested #TempTable declarations.
  • Check if the procedure calls other nested procedures that also declare a temp table with the identical name.

Step 2: Rename Ambiguous Temp Tables

  • Edit the T-SQL script to assign unique names to temp tables in nested scopes (e.g., change #Data in the child procedure to #Data_Child).
  • Save the modified script and redeploy the stored procedure using ALTER PROCEDURE.
  • Ensure no global temporary tables (##TempTable) are inadvertently colliding with local session-based temp tables across concurrent connections.

Step 3: Clear Stale Connection Pool Sessions

  • Navigate to the Windows Server 2025 application connecting to the database and restart the application pool (if using IIS) to flush cached connections.
  • In SSMS, run DBCC FREEPROCCACHE to clear the plan cache, as stale execution plans can sometimes reference outdated temp table structures.
  • Restart the SQL Server Service via services.msc if the issue persists across multiple sessions.

Step 4: Validate T-SQL Code Standards

  • Implement a coding standard that requires explicit DROP TABLE IF EXISTS #TempTable statements at the beginning of every stored procedure.
  • Use SQL Server’s built-in IntelliSense or a linting tool to scan for duplicate temp table declarations before deployment.

Alternative or Verification Steps

  • To verify the fix, execute the specific stored procedure or query directly in SSMS against a test environment and confirm the code compiles and runs without throwing Error 12800.
  • If the error persists, use sys.dm_exec_requests and tempdb.sys.objects to query active temp tables in tempdb during execution to manually spot any remaining naming conflicts in real-time.

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

Troubleshooting Guide: SQL Server Error 12801 — Ambiguous Cursor Name Reference

Why This Error Happens

This error occurs when a T-SQL script or stored procedure declares two or more cursors with identical names in overlapping scopes, such as one declared locally and another declared with the GLOBAL keyword, or duplicate declarations across nested batches. SQL Server 2025’s parser cannot determine which cursor object you intend to reference (for operations like FETCH, CLOSE, or DEALLOCATE) because the name resolves to multiple valid candidates. This is purely a code-logic/naming conflict rather than a server configuration or permissions issue, and it typically surfaces after merging scripts, copy-pasting procedure logic, or running nested procedures that both declare a cursor with the same identifier.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Cursor Declarations

  • Open the stored procedure, trigger, or script referenced in the error message using SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Search the entire batch (and any nested procedure calls) for multiple DECLARE CURSOR statements using the exact same cursor name mentioned in the error text.
  • Pay special attention to cursors declared as GLOBAL versus local-scope cursors sharing the same name — this is the most common trigger of Error 12801.

Step 2: Rename or Scope the Duplicate Cursors

  • Rename one of the conflicting cursors to a unique, descriptive name (e.g., cur_OrderDetails_Local vs. cur_OrderDetails_Global).
  • Update every corresponding OPEN, FETCH, CLOSE, and DEALLOCATE statement to match the renamed cursor.
  • If the duplication is intentional (e.g., a global cursor needed across sessions), explicitly qualify the reference using the GLOBAL keyword:
  FETCH NEXT FROM GLOBAL MyCursor INTO @Variable;

Step 3: Audit Nested Procedures and Dynamic SQL

  • Check any nested stored procedures or EXEC/sp_executesql calls invoked within the same session, since GLOBAL cursors persist across procedure boundaries and can collide with cursors declared deeper in the call stack.
  • Remove unnecessary GLOBAL declarations if cross-procedure cursor sharing isn’t actually required — defaulting to LOCAL cursors prevents most scope collisions.
  • Save the corrected script and redeploy the stored procedure using ALTER PROCEDURE or CREATE OR ALTER PROCEDURE.

Step 4: Clear Cached Execution Plans (If Error Persists)

  • Run DBCC FREEPROCCACHE (in a test/dev environment only) to ensure SQL Server isn’t executing a stale cached plan referencing the old cursor definitions.
  • Re-execute the corrected procedure to confirm the ambiguous reference no longer triggers.

Alternative or Verification Steps

  • Verify the fix by executing the procedure in SSMS with SET NOCOUNT ON; and confirming it completes without Error 12801, then check sys.dm_exec_cursors to confirm only the expected cursor names are active during execution.
  • As an alternative, add DEALLOCATE statements immediately after each CLOSE call throughout the script to ensure no orphaned cursors with duplicate names remain in scope during subsequent executions.

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

Why This Error Happens

Error 12712 occurs when SQL Server 2025 parses a BACKUP or RESTORE statement targeting S3-compatible object storage and encounters a connection option in the WITH S3 clause that it does not recognize. This typically results from a typo in the option name, use of a parameter deprecated or not yet supported in the current Cumulative Update, or copy-pasting syntax from a different storage provider’s documentation (such as Azure Blob syntax mixed into an S3 connection string). It can also surface if the S3 endpoint configuration was defined using an older syntax version before the S3 integration feature was finalized in a preview or RTM build.

Step-by-Step Resolution Guide

Step 1: Validate the T-SQL Syntax Against Current Documentation

  • Open the T-SQL script containing your BACKUP DATABASE ... TO URL or CREATE CREDENTIAL statement.
  • Compare every key inside the WITH ( S3 = ( ... ) ) block against the officially supported list (e.g., ENDPOINT, REGION, BUCKET, ACCESS_KEY_ID, SECRET_ACCESS_KEY).
  • Remove or correct any unexpected option such as ACCESS_KEY (incorrect) vs. ACCESS_KEY_ID (correct).

Step 2: Confirm SQL Server Build and Apply Latest Cumulative Update

  • Run SELECT @@VERSION; in SSMS to check your current build number.
  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update (CU) for SQL Server 2025.
  • Install the CU on Windows Server 2025 / Windows 11, since early S3 connector builds had a smaller accepted parameter set that was expanded in later patches.

Step 3: Recreate the Credential or Database Scoped Credential

  • Drop the existing credential using:
DROP CREDENTIAL [S3_Credential_Name];
  • Recreate it using only currently valid parameters:
CREATE CREDENTIAL [S3_Credential_Name]
WITH IDENTITY = 'S3 Access Key',
SECRET = '<AccessKeyID>:<SecretAccessKey>';
  • Re-run your backup/restore statement to confirm the option list is now accepted by the parser.

Step 4: Check for Configuration File or Registry Overrides

  • Inspect C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\sqlservr.exe config dependencies and any custom startup parameters in SQL Server Configuration Manager.
  • Ensure no legacy .ini or XML config file is injecting outdated S3 parameter names into the connection pipeline.

Alternative or Verification Steps

  • Run a test BACKUP DATABASE [TestDB] TO URL = 's3://your-bucket/testfile.bak' WITH S3 = (ENDPOINT = '...', REGION = '...') on a non-production database to confirm the statement completes without raising Error 12712.
  • If the error persists, enable trace flag 3605 and check the SQL Server ERRORLOG (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact parameter name flagged as unexpected, then cross-reference it with the release notes for your specific build.

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

Troubleshooting Guide: Error 12713 – OPENROWSET is Not Allowed to Read Local Files

Why This Error Happens

Error 12713 occurs when SQL Server’s OPENROWSET bulk function is blocked from accessing local file paths due to the ad hoc distributed queries advanced option being disabled, or because the BULK import feature requires explicit enabling at the instance level. This is a security hardening default in SQL Server 2025 designed to prevent unauthorized local file system reads through T-SQL queries. Additionally, the error can surface if the SQL Server service account lacks NTFS permissions on the target file path, even after the feature is enabled.

Step-by-Step Resolution Guide

Step 1: Enable Ad Hoc Distributed Queries

  • Open SQL Server Management Studio (SSMS) and connect to your instance using an account with sysadmin privileges.
  • Run the following T-SQL script to enable the required advanced option:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'ad hoc distributed queries', 1;
RECONFIGURE;
  • Confirm no errors are returned in the Messages pane after execution.

Step 2: Verify File System Permissions on Windows Server 2025 / Windows 11

  • Navigate to the folder containing the target file (e.g., C:\SQLData\ImportFiles\).
  • Right-click the folder, select Properties > Security > Edit, and ensure the SQL Server service account (e.g., NT SERVICE\MSSQLSERVER) has at least Read & Execute permissions.
  • If running SQL Server in a containerized or locked-down environment, check Windows Defender Application Control (WDAC) or AppLocker policies that may silently block file access.

Step 3: Restart the SQL Server Service to Apply Changes

  • Open Services.msc on Windows Server 2025.
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart.
  • Alternatively, use PowerShell as Administrator:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Re-Test the OPENROWSET Query

  • Run a sample query against the same file path to confirm the fix:
SELECT * FROM OPENROWSET(BULK 'C:\SQLData\ImportFiles\test.csv', SINGLE_CLOB) AS DataFile;
  • If the error persists, check whether the path uses a UNC network share instead of a local path, as this requires additional xp_cmdshell or linked server configuration rather than local OPENROWSET access.

Alternative or Verification Steps

  • Run SELECT * FROM sys.configurations WHERE name = 'ad hoc distributed queries'; and confirm the value_in_use column shows 1.
  • If the error still occurs after enabling the option, try moving the target file to a non-system drive (avoid C:\Program Files\ or C:\Windows\ paths) since Windows Server 2025 enforces stricter UAC virtualization on protected directories.

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

Troubleshooting Guide: Error 12711 – Invalid S3 Connection Options JSON Structure

Why This Error Happens

This error occurs when SQL Server 2025’s S3_CONNECTION or backup/restore OPTIONS clause receives a JSON object that is empty or malformed, typically due to an empty {} payload being passed instead of required key-value pairs. SQL Server’s native JSON parser for S3 integration strictly validates that at least one recognized parameter (such as REGION, ENDPOINT, or ACCESS_KEY_ID) is present before it will construct the connection object. This is commonly caused by a copy-paste error in T-SQL scripts, a misconfigured credential object, or an automation/orchestration tool (like PowerShell or Azure Data Studio) generating a blank JSON string when a variable fails to populate correctly.

Step-by-Step Resolution Guide

Step 1: Validate the JSON Syntax in Your T-SQL Script

  • Open the script or stored procedure that defines the S3_CONNECTION or BACKUP ... TO URL statement.
  • Confirm the JSON is not empty: it should look like {"region":"us-east-1","endpoint":"s3.amazonaws.com"} rather than {} or "".
  • Run SELECT ISJSON('your_json_string_here'); in SSMS to confirm the string returns 1 (valid JSON) before troubleshooting further.

Step 2: Check the Credential or Connection Object Source

  • Navigate to SQL Server Management Studio (SSMS) > Security > Credentials and verify the SQL Credential used for S3 access actually has a populated secret/identity field.
  • If using a PowerShell variable or Azure Key Vault reference to build the JSON dynamically, print the variable value to console (Write-Output $jsonPayload) before it’s passed to SQL Server to confirm it isn’t null or empty.
  • Ensure environment variables (e.g., AWS_ACCESS_KEY_ID, AWS_REGION) referenced by automation scripts are correctly set in System Properties > Environment Variables on Windows Server 2025.

Step 3: Rebuild the S3 Connection Statement with Required Parameters

  • Reconstruct the JSON manually, ensuring at minimum the REGION and ENDPOINT keys are included, for example:
    {"region":"us-east-1","endpoint":"s3.us-east-1.amazonaws.com","access_key_id":"<value>","secret_access_key":"<value>"}
  • Re-run the CREATE CREDENTIAL or BACKUP DATABASE ... TO URL command with this corrected JSON string.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm Error 12711 no longer appears on the next execution attempt.

Step 4: Restart the Dependent SQL Server Service (If Cached Config Persists)

  • Open Services.msc on Windows Server 2025 and restart the SQL Server (MSSQLSERVER) service to clear any cached invalid connection metadata.
  • Alternatively, run net stop MSSQLSERVER && net start MSSQLSERVER from an elevated Command Prompt.

Alternative or Verification Steps

  • Verify the fix by executing a test connection: RESTORE VERIFYONLY FROM URL = 'https://<bucket>.s3.amazonaws.com/<file>.bak' WITH CREDENTIAL = 'YourS3Credential'; — a successful verification confirms the JSON structure is now valid.
  • If the error persists, bypass dynamic JSON generation entirely and hard-code a known-good JSON string directly in a test query to isolate whether the issue lies in the application layer or SQL Server configuration itself.

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

Troubleshooting Guide: Error 12709 – Invalid JSON Structure for S3 Connection Options

Why This Error Happens

This error occurs when SQL Server 2025’s native S3 integration (used for BACKUP TO URL, BULK INSERT, or PolyBase-style external data sources) attempts to parse a JSON configuration string that does not contain a valid top-level "s3" object. Typically, this is caused by malformed JSON syntax (missing braces, incorrect nesting, or trailing commas), a typo in the key name (e.g., "S3" with incorrect casing, or "s3config" instead of "s3"), or the JSON string being passed as an empty or NULL value. Because SQL Server’s JSON parser performs strict schema validation on connection option objects, even a single misplaced character will cause it to fail to locate the required subobject.

Step-by-Step Resolution Guide

Step 1: Validate the Raw JSON Syntax

  • Copy the exact JSON string being passed to the CREATE EXTERNAL DATA SOURCE or BACKUP ... TO URL command.
  • Paste it into a JSON linter (such as jsonlint.com or VS Code with a JSON extension) to confirm there are no syntax errors like unclosed brackets or trailing commas.
  • Confirm the root object is wrapped correctly, e.g.:
{
  "s3": {
    "endpoint": "s3.amazonaws.com",
    "region": "us-east-1",
    "accessKeyId": "YOUR_KEY",
    "secretAccessKey": "YOUR_SECRET"
  }
}

Step 2: Check Key Casing and Nesting Level

  • Verify the key is lowercase "s3" — SQL Server 2025’s parser is case-sensitive for this subobject.
  • Ensure "s3" is not nested inside another wrapper object (e.g., "options": { "s3": {...} } will fail; it must be at the root level).
  • Remove any extra wrapping objects or arrays that may have been introduced by application code or PowerShell string serialization.

Step 3: Inspect How the JSON String Is Being Passed in T-SQL

  • If using a variable, confirm it is declared as NVARCHAR(MAX) and not truncated:
DECLARE @s3json NVARCHAR(MAX) = N'{"s3":{"endpoint":"s3.amazonaws.com","region":"us-east-1"}}';
  • Check for double-escaping issues if the JSON was generated by an application layer (e.g., C#, Python) — escaped quotes (\") left in the final string will break SQL Server’s parser.
  • On Windows Server 2025, verify the SQL Server error log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for the exact malformed string it received.

Step 4: Rebuild the Credential or External Data Source Object

  • Drop and recreate the affected object to rule out metadata corruption:
DROP EXTERNAL DATA SOURCE MyS3Source;
CREATE EXTERNAL DATA SOURCE MyS3Source
WITH (
  LOCATION = 's3://mybucket/',
  CONNECTION_OPTIONS = '{"s3":{"endpoint":"s3.amazonaws.com","region":"us-east-1"}}'
);
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after recreation to clear any cached connection metadata.

Alternative or Verification Steps

  • Run SELECT ISJSON(@s3json); in SQL Server Management Studio — it should return 1. If it returns 0, the JSON is malformed before it even reaches the S3 parser.
  • If the issue persists, test the same JSON payload against a minimal AWS CLI S3 call (aws s3 ls --endpoint-url ...) to confirm the credentials/endpoint structure is valid outside of SQL Server, isolating whether the fault is in SQL Server’s parsing or the JSON content itself.

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

Troubleshooting Guide: SQL Server Error 12710 — Unsupported S3 URL Style

Why This Error Happens

This error occurs when SQL Server 2025’s S3 integration feature (used for BACKUP TO URL, BULK INSERT, or external data sources referencing S3-compatible object storage) receives an invalid value for the S3_URL_STYLE parameter. SQL Server 2025 only recognizes two valid addressing schemes — Path and Virtual_Hosted — and any other string (including typos, lowercase mismatches in older syntax expectations, or deprecated values like Host or Virtual) will cause the engine to reject the credential or external location object during validation. This is typically a configuration/syntax issue rather than a connectivity or permissions problem, since the error is thrown before SQL Server attempts to reach the S3 endpoint.

Step-by-Step Resolution Guide

Step 1: Locate the S3 URL Style Configuration

  • Identify where the S3 URL style is being set — this is usually inside a CREATE CREDENTIAL, CREATE EXTERNAL DATA SOURCE, or BACKUP ... TO URL T-SQL statement.
  • Run the following to inspect existing credentials:
  SELECT name, credential_identity, target_type FROM sys.credentials;
  • Check any PowerShell or sqlcmd automation scripts that may be passing the S3_URL_STYLE parameter programmatically.

Step 2: Correct the Parameter Value

  • Edit the T-SQL statement so that S3_URL_STYLE is set to exactly one of the two supported literal values (case-sensitive as documented): Path or Virtual_Hosted.
  • Example corrected syntax:
  CREATE CREDENTIAL [s3://my-bucket.s3.amazonaws.com]
  WITH IDENTITY = 'S3 Access Key',
  SECRET = '<AccessKey>:<SecretKey>',
  S3_URL_STYLE = 'Virtual_Hosted';
  • If using Path style, confirm your S3-compatible endpoint (e.g., MinIO, Wasabi, AWS S3) actually supports path-style requests, as AWS has deprecated path-style for many newer buckets.

Step 3: Drop and Recreate the Credential or Data Source

  • If the credential was already created with an invalid value, drop it before recreating it:
  DROP CREDENTIAL [s3://my-bucket.s3.amazonaws.com];
  • Recreate it using the corrected S3_URL_STYLE value from Step 2.
  • Restart the SQL Server service only if the change was made at the instance-level configuration (not typically required for credential-level changes).

Step 4: Validate Endpoint Compatibility

  • Confirm with your storage provider (AWS, MinIO, Azure-compatible gateway, etc.) which addressing style their endpoint expects.
  • Update any firewall, proxy, or DNS configuration on Windows Server 2025 if switching from Path to Virtual_Hosted style, since virtual-hosted style requires DNS resolution of bucket-name.s3.amazonaws.com.

Alternative or Verification Steps

  • Test the fix by running a small BACKUP DATABASE ... TO URL command against the S3 target and confirm it completes without throwing Error 12710.
  • If the error persists, enable extended events or check the SQL Server error log (ERRORLOG in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for the exact string passed to S3_URL_STYLE, ensuring no hidden whitespace or encoding issues exist in the script.

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

Troubleshooting Guide: SQL Server 2025 Error 12707 — Azure File Share Dynamic Scaling Failed

Why This Error Happens

Error 12707 typically occurs when SQL Server 2025 attempts to dynamically scale an Azure File Share used for database storage, but the operation fails due to insufficient Shared Access Signature (SAS) permissions or an expired Storage Account Key. This can also happen when the Azure File Sync agent or the underlying SMB client on Windows Server 2025 loses connectivity mid-transaction, causing the quota adjustment request to time out. Additionally, corrupted credential caches in the Windows Credential Manager can prevent SQL Server from re-authenticating with the Azure endpoint to request additional storage space.

Step-by-Step Resolution Guide

Step 1: Verify Azure Storage Credentials and Permissions

  • Open Credential Manager on Windows Server 2025 and check for stale or expired Azure Storage credentials under “Windows Credentials.”
  • Run the following T-SQL command to check the current credential mapped to the file share:
  SELECT * FROM sys.credentials WHERE name LIKE '%core.file.core.windows.net%';
  • Ensure the Shared Access Signature (SAS) token has not expired and includes “Update” (u) and “Container Create” (c) permissions.

Step 2: Re-authenticate and Refresh the Storage Key

  • Drop and recreate the SQL Server credential object to force a refresh of the authentication token:
  DROP CREDENTIAL [https://<storageaccount>.file.core.windows.net/<sharename>];
  CREATE CREDENTIAL [https://<storageaccount>.file.core.windows.net/<sharename>]
  WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
  SECRET = '<NewSASToken>';
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to apply the new credential immediately.

Step 3: Check Network and Firewall Configuration

  • Verify that outbound traffic on Port 445 (SMB) is not blocked by the Windows Defender Firewall or a corporate network appliance.
  • Use the Test-NetConnection PowerShell cmdlet to validate connectivity:
  Test-NetConnection -ComputerName <storageaccount>.file.core.windows.net -Port 445
  • If the test fails, check your VPN or ExpressRoute configuration to ensure Azure Files traffic is being routed correctly.

Step 4: Manually Trigger a Scale Operation

  • Force SQL Server to re-evaluate the file share capacity by running the dynamic scaling stored procedure manually:
  EXEC sys.sp_cloud_update_file_share_capacity @share_name = '<sharename>';
  • Monitor the SQL Server Error Log for a successful “Capacity Updated” confirmation message instead of Error 12707.

Alternative or Verification Steps

  • Verification: Check the SQL Server Error Log (via SSMS Object Explorer > Management > SQL Server Logs) for the entry “Dynamic Scaling Succeeded” following the service restart.
  • Alternative: If dynamic scaling continues to fail, manually increase the Azure File Share quota via the Azure Portal (Storage Account > File Shares > Scale) and restart the SQL Server instance to sync the new static capacity limit.

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

Troubleshooting Guide: SQL Server Error 12708 – Malformed S3 Connection Options JSON

Why This Error Happens

Error 12708 occurs when SQL Server 2025’s S3 integration feature (used for BACKUP TO URL, BULK INSERT, or external data sources pointing to S3-compatible storage) receives a connection options string that does not conform to valid JSON syntax. This is typically caused by manual editing errors such as unescaped quotes, trailing commas, mismatched braces, or incorrect encoding when the JSON payload is passed through T-SQL scripts, PowerShell variables, or configuration files. It can also happen if the credential or endpoint string was copied from a source (like a web browser or Word document) that introduced smart quotes or hidden Unicode characters instead of standard ASCII characters.

Step-by-Step Resolution Guide

Step 1: Validate the Raw JSON Syntax

  • Copy the exact S3 connection options string from your T-SQL script or application config.
  • Paste it into a strict JSON linter (e.g., jsonlint.com or VS Code with a JSON extension) to pinpoint the exact character causing the parsing failure.
  • Look specifically for trailing commas after the last key-value pair, such as {"region": "us-east-1",}.

Step 2: Check for Hidden Unicode and Smart Quotes

  • Open the script in a plain text editor like Notepad++ or VS Code rather than Word or Outlook.
  • Enable “Show Symbols” or “Render Whitespace” to detect curly quotes (“ ”) that look like standard quotes (” “) but break the parser.
  • Re-type the quotation marks manually using a US-standard keyboard layout to ensure they are the straight double-quote character ("), not the Unicode variant (U+201C/U+201D).

Step 3: Verify Credential and Endpoint Formatting

  • Open SQL Server Management Studio (SSMS) and review the CREATE CREDENTIAL or sp_configure command used for the S3 endpoint.
  • Ensure the JSON string strictly follows the required schema: {"endpoint": "s3.amazonaws.com", "accesskey": "KEY", "secretkey": "SECRET"}.
  • Confirm there are no line breaks inside the string values, as multi-line strings inside JSON values will trigger a parsing failure in the native SQL Server JSON engine.

Step 4: Rebuild the Connection String Programmatically

  • Instead of manually typing the JSON, use PowerShell’s ConvertTo-Json cmdlet or a scripting language to generate the string automatically.
  • Example: @{endpoint="s3.amazonaws.com"; accesskey="xxx"; secretkey="yyy"} | ConvertTo-Json -Compress
  • Insert this programmatically generated output directly into your SQL script to eliminate manual syntax errors.

Step 5: Restart the SQL Server Service

  • Navigate to services.msc on your Windows Server 2025 or Windows 11 machine.
  • Locate the SQL Server (MSSQLSERVER) service (or the named instance) and perform a restart to clear any cached, malformed configuration states.
  • Re-run the BACKUP or RESTORE command that triggered the original 12708 error.

Alternative or Verification Steps

  • Verification: Run the query again using SELECT ISJSON('your_string_here'); in a new SSMS query window; a return value of 1 confirms the string is now valid JSON before you attempt the S3 operation again.
  • Alternative: If the error persists despite valid syntax, bypass manual string creation entirely by using the SQL Server Configuration Manager’s GUI-based “External Storage” wizard (new in SQL Server 2025) to generate the connection metadata automatically.

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

Troubleshooting Guide: SQL Server Error 12705 — Invalid External Data Source Type for Azure Blob Storage

Why This Error Happens

This error occurs when an EXTERNAL DATA SOURCE object has been created with an incorrect TYPE value (such as HADOOP or RDBMS) while its LOCATION string points to an Azure Blob Storage endpoint (e.g., wasbs:// or a blob.core.windows.net URL). SQL Server 2025 enforces strict validation between the location protocol and the data source type, meaning any Blob Storage location must explicitly declare TYPE = BLOB_STORAGE. This mismatch is typically caused by legacy scripts being reused from older environments, migrated PolyBase configurations, or manual typos in T-SQL CREATE EXTERNAL DATA SOURCE statements.

Step-by-Step Resolution Guide

Step 1: Identify the Faulty External Data Source

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to inspect current configurations:
SELECT name, location, type_desc FROM sys.external_data_sources;
  • Look for any row where location contains blob.core.windows.net but type_desc is not BLOB_STORAGE.

Step 2: Drop the Incorrectly Configured Data Source

  • Before dropping, ensure no active external tables are currently referencing this source, as this will cause a dependency error.
  • Execute the drop command in a new query window:
DROP EXTERNAL DATA SOURCE [YourDataSourceName];

Step 3: Recreate the Data Source with the Correct Type

  • Use the BLOB_STORAGE type explicitly in the creation script.
  • Ensure you are using a valid Shared Access Signature (SAS) token or Managed Identity credential compatible with Windows Server 2025 security policies.
CREATE EXTERNAL DATA SOURCE [YourDataSourceName]
WITH (
    LOCATION = 'wasbs://yourcontainer@youraccount.blob.core.windows.net',
    CREDENTIAL = [YourDatabaseScopedCredential],
    TYPE = BLOB_STORAGE
);

Step 4: Verify Associated Credentials

  • Check that the DATABASE SCOPED CREDENTIAL used in Step 3 utilizes SHARED ACCESS SIGNATURE as the identity, as standard SQL logins are incompatible with BLOB_STORAGE types.
  • Navigate to Object Explorer > Security > Credentials in SSMS to confirm the credential exists and is mapped correctly.

Alternative or Verification Steps

  • Re-run the SELECT * FROM sys.external_data_sources query to confirm the type_desc column now reads BLOB_STORAGE for the updated row.
  • If the error persists after recreation, verify that the firewall settings on your Azure Storage Account allow traffic from your Windows Server 2025 public IP address, as a blocked connection can sometimes trigger cascading configuration errors.

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

Why This Error Happens

Error 12706 occurs when SQL Server’s metadata incorrectly references a file ID that conflicts with another file already registered to the same database, typically caused by a corrupted or improperly restored transaction log, a botched file-add operation during a crash, or manual manipulation of system catalog views like sys.master_files. This can also surface after a failed ALTER DATABASE ADD FILE command that partially committed, or when a database is attached from a backup where file ID sequences were duplicated due to replication or mirroring misconfigurations. In rare cases, antivirus or backup software locking the .mdf/.ldf files during a file-add operation on Windows Server 2025 triggers this inconsistency.

Step-by-Step Resolution Guide

Step 1: Verify the Current File ID Mapping

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to inspect file IDs for the problem database:
  SELECT file_id, name, physical_name, state_desc FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  • Look for duplicate or missing file_id entries, especially around the ID mentioned in the error (%d).

Step 2: Take the Database Offline and Check File Locks

  • Set the database to single-user mode to prevent concurrent access:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • On Windows Server 2025/Windows 11, open Resource Monitor (resmon.exe) and search the CPU tab for handles locking the .mdf or .ldf files under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Terminate any third-party backup agent or antivirus process holding a lock on these files, then restart the SQL Server service via services.msc.

Step 3: Rebuild or Correct the File Metadata

  • If a duplicate file ID is confirmed, remove the conflicting file reference using:
  ALTER DATABASE YourDatabaseName REMOVE FILE DuplicateLogicalFileName;
  • Re-add the file with a clean, unused file ID path:
  ALTER DATABASE YourDatabaseName ADD FILE (NAME = 'NewFileName', FILENAME = 'D:\SQLData\NewFile.ndf');
  • If the database won’t come online at all, restore the last known good full backup and replay transaction logs instead of repairing in place.

Step 4: Return Database to Multi-User Mode

  • Once the file structure is corrected, switch the database back:
  ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Confirm no error messages appear in SQL Server Error Log (ERRORLOG file located in the MSSQL\Log directory).

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm there is no remaining corruption after the fix.
  • If the error persists after metadata correction, perform a full restore from backup onto a new database name and redirect application connections, as this guarantees a clean file ID sequence.

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

Troubleshooting Guide: SQL Server Error 12704 – “Bad or inaccessible location specified in external data source”

Why This Error Happens

Error 12704 typically occurs when SQL Server 2025 cannot validate or reach the LOCATION parameter defined in an EXTERNAL DATA SOURCE object, usually due to an incorrect file path, unreachable network share, or malformed URL syntax (missing protocol prefix like https:// or abfss://). This can also stem from the SQL Server service account lacking NTFS or share-level permissions on Windows Server 2025, or from PolyBase/Data Virtualization components not being properly installed or started. Additionally, corrupted credential mappings tied to the external data source scope can cause the engine to misinterpret the location as invalid even when the path itself is correct.

Step-by-Step Resolution Guide

Step 1: Validate the External Data Source Syntax

  • Run SELECT * FROM sys.external_data_sources; to review the exact LOCATION string stored in metadata.
  • Confirm the path uses correct prefixes (e.g., https://, abfss://, odbc://, or sqlserver://) with no trailing slashes or typos.
  • Drop and recreate the external data source if the LOCATION value appears malformed:
  DROP EXTERNAL DATA SOURCE MyDataSource;
  CREATE EXTERNAL DATA SOURCE MyDataSource
  WITH (LOCATION = 'https://correctpath.blob.core.windows.net/container');

Step 2: Verify Network and Firewall Accessibility

  • From the SQL Server host, use Test-NetConnection -ComputerName <target_host> -Port <port> in PowerShell to confirm reachability.
  • Check Windows Defender Firewall on Windows Server 2025 for outbound rules blocking the target port (common ports: 1433, 443, or 445 for SMB shares).
  • If using a UNC path (e.g., \\fileserver\share), confirm the share is accessible from the SQL Server service account context, not just your own login.

Step 3: Confirm PolyBase / Data Virtualization Feature Status

  • Open SQL Server Configuration Manager and ensure the SQL Server PolyBase Engine and PolyBase Data Movement services are running.
  • If disabled, enable via Setup: Setup.exe /ACTION=REBUILDDATABASE or add the feature through Add Roles and Features in Server Manager (Windows Server 2025).
  • Restart the SQL Server instance after enabling the feature:
  Restart-Service MSSQLSERVER

Step 4: Check Service Account Permissions

  • Open Services.msc, locate the SQL Server service, and confirm the “Log On As” account.
  • Grant that account Read/Write NTFS permissions on the local or network folder referenced by the external data source.
  • For Azure Blob or ADLS Gen2 sources, confirm the associated DATABASE SCOPED CREDENTIAL has a valid SAS token or managed identity with correct role assignments (Storage Blob Data Contributor).

Step 5: Rebuild the Scoped Credential

  • Drop and recreate the credential tied to the external data source in case of token expiration or corruption:
  DROP DATABASE SCOPED CREDENTIAL MyCredential;
  CREATE DATABASE SCOPED CREDENTIAL MyCredential
  WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
  SECRET = '<new_valid_sas_token>';
  • Re-link the credential to the external data source using the CREDENTIAL = MyCredential clause.

Alternative or Verification Steps

  • Run a simple test query against an external table tied to the data source (SELECT TOP 1 * FROM ExternalTableName;) to confirm connectivity is restored.
  • If the issue persists, use SQL Server Error Logs (EXEC sp_readerrorlog) combined with Event Viewer > Applications and Services Logs > SQL Server on Windows Server 2025 to capture a more detailed stack trace pointing to DNS resolution or authentication failures.

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

Troubleshooting Guide: Error 12702 – Failed to Lock External Data Source Manager

Why This Error Happens

This error occurs when SQL Server 2025 is unable to acquire an internal lock on the External Data Source Manager, typically because a concurrent DDL operation (such as CREATE EXTERNAL DATA SOURCE or PolyBase configuration changes) is already holding that resource. It can also surface when the PolyBase engine service or the underlying metadata cache becomes unresponsive due to resource contention, orphaned transactions, or a corrupted internal state after an unexpected service restart. In some cases, this is a cascading symptom of insufficient memory or CPU throttling on Windows Server 2025, preventing the lock manager thread from responding within the timeout window.

Step-by-Step Resolution Guide

Step 1: Identify Blocking Sessions

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a Dedicated Administrator Connection (DAC) if the instance is unresponsive.
  • Run the following query to check for blocking locks related to external resources:
  SELECT * FROM sys.dm_tran_locks WHERE resource_type = 'EXTERNAL_DATA_SOURCE';
  • Identify the session_id holding the lock and note whether it corresponds to a stalled PolyBase or external table operation.

Step 2: Restart the PolyBase and SQL Server Launchpad Services

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate and restart the following services in order:
  • SQL Server PolyBase Engine
  • SQL Server PolyBase Data Movement Service
  • SQL Server Launchpad (MSSQLSERVER)
  • Alternatively, use PowerShell (Run as Administrator):
  Restart-Service "MSSQLSERVER" -Force
  Restart-Service "SQLBrowser" -Force

Step 3: Clear Orphaned Metadata Cache

  • Execute DBCC FREESYSTEMCACHE('ALL') to clear stale metadata entries that may be holding onto the lock reference.
  • If the error persists, drop and recreate the specific external data source definition:
  DROP EXTERNAL DATA SOURCE [YourDataSourceName];
  CREATE EXTERNAL DATA SOURCE [YourDataSourceName] WITH (...);

Step 4: Check System Resource Allocation

  • Navigate to Task Manager > Performance tab on Windows Server 2025 to verify CPU and Memory usage isn’t maxed out, as resource starvation can cause lock manager timeouts.
  • Adjust the max server memory setting in SQL Server Configuration Manager if the instance is competing with other Windows services for RAM.

Step 5: Apply the Latest Cumulative Update

  • Check Windows Update or the Microsoft Download Center for the latest Cumulative Update (CU) for SQL Server 2025, as lock manager deadlocks in the External Data Source Manager are often patched in service releases.
  • Install the update and perform a full server reboot to ensure driver-level dependencies are refreshed.

Alternative or Verification Steps

  • To verify the fix, re-run the specific query or external table creation script that originally triggered Error 12702; if it completes without a timeout, the lock has been successfully released.
  • If the error recurs immediately, use sp_who2 to check for “AWAITING COMMAND” statuses on system session IDs (SPIDs) and manually kill any zombie processes using KILL [spid].

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

Troubleshooting Guide: Error 12703 – “Referenced External Data Source Not Found”

Why This Error Happens

Error 12703 occurs when SQL Server 2025 cannot locate the EXTERNAL DATA SOURCE object referenced in a query, typically because it was dropped, renamed, or was never created in the current database context. This can also happen if the external data source exists in a different database than the one currently selected, since external data sources are scoped at the database level, not the server level. Additionally, PolyBase or Elastic Query configurations that are disabled or improperly initialized can cause SQL Server to fail to resolve the reference even when the object technically exists in metadata.

Step-by-Step Resolution Guide

Step 1: Verify the External Data Source Exists in the Current Database

  • Run the following query to check for existing external data sources:
  SELECT name, location, type_desc FROM sys.external_data_sources;
  • Confirm you are connected to the correct database using SELECT DB_NAME(); since external data sources do not carry over between databases.
  • If the result set is empty, the object does not exist and must be recreated.

Step 2: Recreate or Correct the External Data Source Definition

  • If missing, create it using the appropriate syntax, for example:
  CREATE EXTERNAL DATA SOURCE MyExternalSource
  WITH (
      LOCATION = 'sqlserver://RemoteServerName',
      CREDENTIAL = MyDatabaseCredential
  );
  • Double-check the spelling of the data source name in your query matches exactly (case sensitivity may apply depending on collation).
  • Ensure the associated DATABASE SCOPED CREDENTIAL still exists and has not been dropped or corrupted.

Step 3: Confirm PolyBase or Elastic Query Services Are Running

  • Open Services.msc on Windows Server 2025 and verify that “SQL Server PolyBase Engine” and “SQL Server PolyBase Data Movement” services are running.
  • If stopped, right-click and select Start, then set Startup Type to Automatic.
  • Restart the SQL Server instance via SQL Server Configuration Manager to force the engine to reload external resource metadata.

Step 4: Check Database and Scope Context in Scripts/Applications

  • Verify that any stored procedures, views, or applications referencing the external data source explicitly use USE [YourDatabaseName]; before executing the query.
  • If using elastic query sharding, confirm the external table and data source reside in the same database as the calling query.

Alternative or Verification Steps

  • Run the original failing query again after recreating the data source to confirm the error no longer appears, and check sys.dm_exec_external_work for successful execution status.
  • If the issue persists, drop and recreate the associated EXTERNAL TABLE objects as well, since they can retain stale references to the old data source GUID even after the data source is restored.

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

Troubleshooting Guide: DBCC CLONEDATABASE Error 12631 with Ledger Tables

Why This Error Happens

Error 12631 occurs because DBCC CLONEDATABASE does not support databases containing ledger tables, whether they are updatable ledger tables, append-only ledger tables, or system-versioned ledger tables. This restriction exists because the cloning process cannot reliably replicate the cryptographic hash chains, ledger view mappings, and append-only enforcement metadata that maintain the tamper-evidence guarantees of ledger tables. SQL Server 2025 blocks the operation outright at the schema-validation stage rather than risk producing a clone with broken or inconsistent ledger integrity verification.

Step-by-Step Resolution Guide

Step 1: Identify Ledger Tables in the Source Database

  • Run the following query against the source database to list all ledger-enabled objects:
  • SELECT name, ledger_type, ledger_type_desc FROM sys.tables WHERE ledger_type <> 0;
  • Note whether the tables are updatable ledger tables or append-only ledger tables, since this affects the alternative export method you choose later.
  • Check sys.database_ledger_transactions and sys.database_ledger_blocks to confirm ledger history scope before proceeding.

Step 2: Choose a Supported Schema/Statistics Export Method

  • Since CLONEDATABASE is blocked, use Generate Scripts in SQL Server Management Studio (SSMS) 21 to export schema-only DDL for non-ledger objects.
  • For statistics-only needs, manually script statistics using sp_helpstats or DBCC SHOW_STATISTICS combined with sys.dm_db_stats_properties.
  • Alternatively, create a new database and manually re-create ledger tables using CREATE TABLE ... WITH (LEDGER = ON), then use INSERT INTO ... SELECT to populate data without historical hash chain copying.

Step 3: Remove or Isolate Ledger Tables Before Cloning (If Clone Is Required)

  • If a lightweight clone of non-ledger objects is still required for query troubleshooting, move ledger tables into a separate schema or database first.
  • Run DBCC CLONEDATABASE (SourceDB, CloneDB) WITH NO_STATISTICS, NO_QUERYSTORE; only after confirming the source database contains zero ledger tables.
  • Validate ledger status again using SELECT COUNT(*) FROM sys.tables WHERE ledger_type <> 0; — this must return 0 before DBCC CLONEDATABASE will succeed.

Step 4: Apply Windows Server 2025 / Windows 11 Environment Checks

  • Confirm SQL Server 2025 Cumulative Update level via SELECT @@VERSION; since early builds enforce this restriction differently.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for corroborating entries tied to Error 12631.
  • Ensure the SQL Server service account has appropriate NTFS permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA in case the error is compounded by file-access issues during clone creation.

Alternative or Verification Steps

  • Verify the fix by re-running DBCC CLONEDATABASE after confirming sys.tables returns zero ledger-enabled rows; a successful run will create the clone database without raising Error 12631.
  • As an alternative, use native backup/restore (BACKUP DATABASE / RESTORE DATABASE) or sp_detach_db/sp_attach_db workflows, which fully support ledger tables and preserve their cryptographic integrity, unlike CLONEDATABASE.

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

Troubleshooting Guide: SQL Server Error 12701 – Failed to Lock External Data Source Object

Why This Error Happens

Error 12701 typically occurs when SQL Server 2025 cannot acquire the required lock on an External Data Source (EDS) object because another session or background process is already holding a conflicting lock (such as a schema or exclusive lock) during a PolyBase or Data Virtualization operation. This is often triggered by concurrent DDL operations, a stalled external table refresh, or a long-running query that has not released its lock within the timeout window. In some cases, orphaned metadata from an improperly terminated external data source connection can also cause lock contention to persist indefinitely.

Step-by-Step Resolution Guide

Step 1: Identify Blocking Sessions

  • Open SQL Server Management Studio (SSMS) connected to the instance reporting the error.
  • Run sp_who2 or query sys.dm_tran_locks filtered by resource_type = 'EXTERNAL_DATA_SOURCE' to identify the session ID (SPID) holding the conflicting lock.
  • Cross-reference the SPID with sys.dm_exec_requests to check the query text and status (e.g., SUSPENDED, RUNNABLE).

Step 2: Terminate or Wait Out the Conflicting Session

  • If the blocking session is a legitimate long-running job, allow it to complete or reschedule the conflicting operation to a non-peak window.
  • If the session is orphaned or hung, terminate it safely using KILL <SPID>; in a new query window.
  • Avoid killing system session IDs (below 50) as this can destabilize the instance.

Step 3: Validate External Data Source Configuration

  • Navigate to the SQL Server Configuration Manager (available via Start > Microsoft SQL Server 2025 > SQL Server Configuration Manager on Windows Server 2025/Windows 11).
  • Confirm the PolyBase or Data Virtualization service is running without restart loops, as repeated service crashes can leave stale EDS locks.
  • Re-run DROP EXTERNAL DATA SOURCE and recreate the object using CREATE EXTERNAL DATA SOURCE with the correct LOCATION and CREDENTIAL parameters to clear any corrupted metadata.

Step 4: Adjust Lock Timeout Settings

  • If timeouts are caused by high concurrency, increase the LOCK_TIMEOUT setting at the session level using SET LOCK_TIMEOUT 5000; (value in milliseconds) before executing the EDS-dependent query.
  • For persistent environment-wide issues, review the max worker threads and locks configuration under sp_configure to ensure the instance has sufficient resources.

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

  • As a last resort, restart the SQL Server service via services.msc on Windows Server 2025 to clear any in-memory lock table corruption.
  • Ensure no critical transactions are pending before restarting the service.

Alternative or Verification Steps

  • Verify the fix by re-running the original query or ETL job that referenced the EDS object; the operation should now complete without throwing Error 12701.
  • If the error persists after killing sessions and recreating the external data source, check the SQL Server error log (ERRORLOG file located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for underlying I/O or network timeout issues related to the external data connection.

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

Troubleshooting Guide: SQL Server Error 12629 — “Database is a Cloned Database”

Why This Error Happens

This error occurs because the database was created using the DBCC CLONEDATABASE command, which generates a schema-only, metadata-consistent copy of a database for diagnostic or support purposes. SQL Server intentionally marks cloned databases as read-only and unsupported for production workloads by setting the IsClone database property to true. Any attempt to run DML operations, attach the clone as a production database, or query it under normal application contexts triggers this protective error to prevent accidental reliance on non-live data.

Step-by-Step Resolution Guide

Step 1: Confirm the Database Is Actually a Clone

  • Run the following query to check the clone status:
  SELECT name, DATABASEPROPERTYEX(name, 'IsClone') AS IsCloneStatus
  FROM sys.databases
  WHERE name = 'YourDatabaseName';
  • A return value of 1 confirms this is a cloned database and not a corrupted production database.
  • Check SQL Server Error Log (via SSMS > Management > SQL Server Logs) for the original DBCC CLONEDATABASE execution entry to identify when and why it was created.

Step 2: Determine Intended Use and Redirect Workload

  • If the clone was created for Microsoft Support diagnostics (e.g., troubleshooting statistics or query plans), do not attempt to write to it — instead, point your application connection string back to the original production database.
  • Verify the correct production database name in SQL Server Configuration Manager or your application’s web.config / appsettings.json connection strings.
  • If you intended to restore a usable copy (not a diagnostic clone), drop the clone and instead perform a proper backup/restore:
  BACKUP DATABASE [ProductionDB] TO DISK = 'C:\SQLBackups\ProductionDB.bak';
  RESTORE DATABASE [ProductionDB_Copy] FROM DISK = 'C:\SQLBackups\ProductionDB.bak'
  WITH MOVE 'ProductionDB' TO 'C:\SQLData\ProductionDB_Copy.mdf',
  MOVE 'ProductionDB_log' TO 'C:\SQLData\ProductionDB_Copy.ldf';

Step 3: Remove the Cloned Database if No Longer Needed

  • Once diagnostics are complete, clean up the clone to avoid confusion or accidental reattachment:
  USE master;
  ALTER DATABASE [YourClonedDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  DROP DATABASE [YourClonedDB];
  • On Windows Server 2025 / Windows 11, also manually delete leftover .mdf / .ldf files from C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ if DROP DATABASE does not remove them automatically.

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

  • If the error persists due to a cached metadata state, restart the SQL Server service via PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • Confirm the service restarts cleanly by checking Event Viewer under Windows Logs > Application for SQL Server startup entries.

Alternative or Verification Steps

  • Re-run the DATABASEPROPERTYEX query from Step 1 after remediation — a NULL or 0 result confirms the database is no longer flagged as a clone.
  • If you need a writable copy of production data for testing, always use native BACKUP/RESTORE or database snapshots rather than DBCC CLONEDATABASE, since clones are permanently restricted to read-only, single-user diagnostic access by design.

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

Troubleshooting Guide: Error 12630 – VERIFY_CLONE Option Conflict with SERVICEBROKER in SQL Server 2025

Why This Error Happens

This error occurs because the CREATE DATABASE ... FOR ATTACH or database cloning command was issued with both the VERIFY_CLONE and SERVICEBROKER options specified simultaneously, which SQL Server 2025 explicitly disallows due to internal conflicts in how Service Broker GUIDs are validated during a clone verification pass. The VERIFY_CLONE option is designed to validate database clone integrity without altering identifiers, while SERVICEBROKER options (such as NEW_BROKER or ENABLE_BROKER) require modifying or resetting the Service Broker identifier — these two operations are mutually exclusive at the engine level. This is almost always caused by a scripting error, a leftover automation template, or a misconfigured database restore/attach script rather than a server misconfiguration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Locate and Review the Offending T-SQL Script

  • Open the script or automation job (SSMS query, PowerShell Invoke-Sqlcmd, or SSIS package) that triggered the CREATE DATABASE or ATTACH statement.
  • Search specifically for the keywords VERIFY_CLONE and SERVICEBROKER appearing in the same statement, for example:
  CREATE DATABASE [MyDB] ON (FILENAME = 'D:\Data\MyDB.mdf')
  FOR ATTACH WITH VERIFY_CLONE, SERVICEBROKER;
  • Identify which option is actually required for your use case (verification-only vs. broker re-identification).

Step 2: Remove the Conflicting Option

  • If your goal is to verify a database clone (common after using DBCC CLONEDATABASE), remove the SERVICEBROKER keyword entirely:
  CREATE DATABASE [MyDB] ON (FILENAME = 'D:\Data\MyDB.mdf')
  FOR ATTACH WITH VERIFY_CLONE;
  • If your goal is to reset the Service Broker GUID after attaching a copied/restored database, remove VERIFY_CLONE instead and run the broker command separately:
  CREATE DATABASE [MyDB] ON (FILENAME = 'D:\Data\MyDB.mdf')
  FOR ATTACH;
  GO
  ALTER DATABASE [MyDB] SET NEW_BROKER;
  • Save the corrected script and re-run it from SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.

Step 3: Update Any Automation or Deployment Templates

  • Check DevOps pipelines, DACPAC/BACPAC post-deployment scripts, and PowerShell modules (e.g., dbatools cmdlets like Restore-DbaDatabase) for hardcoded combinations of these flags.
  • Edit the pipeline YAML or PowerShell parameters so VERIFY_CLONE and -SetBroker (or equivalent) are never passed together in the same call.
  • Re-deploy the pipeline in a test/staging environment on Windows Server 2025 before pushing to production.

Step 4: Restart the Operation in the Correct Sequence

  • If both clone verification and broker reset are genuinely required, perform them as two sequential operations instead of one combined statement:
  • First, attach and verify the clone.
  • Then, in a separate batch, alter the database to reset the Service Broker identifier.
  • Confirm no open transactions or locks are blocking the second ALTER DATABASE call using sp_who2 or Activity Monitor.

Alternative or Verification Steps

  • Verify the fix by re-running the corrected script and confirming the database attaches successfully with no Error 12630 in the SQL Server Error Log (Management > SQL Server Logs in SSMS) or Windows Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, use DBCC CLONEDATABASE followed by a standalone ALTER DATABASE SET NEW_BROKER statement rather than combining verification and broker options in a single CREATE DATABASE FOR ATTACH command.

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

Troubleshooting Guide: SQL Server Error 12628 — NOSTATISTICS and NOQUERYSTORE Options Enabled During VERIFY_CLONE

Why This Error Happens

Error 12628 occurs when the DBCC CLONEDATABASE operation is executed with the VERIFY_CLONE option, and SQL Server 2025 detects that statistics blobs or Query Store data could not be fully copied into the cloned database. This typically happens because the source database has corrupted or inaccessible statistics metadata, insufficient permissions on system catalog views, or the Query Store was in an ERROR / READ_ONLY state at the time of cloning. As a safeguard, SQL Server automatically disables these features on the clone rather than risk shipping an inconsistent diagnostic copy.

Step-by-Step Resolution Guide

Step 1: Validate Source Database Health Before Cloning

  • Run DBCC CHECKDB ('SourceDBName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out corruption in system statistics pages.
  • Check Query Store state using:
  SELECT actual_state_desc, readonly_reason 
  FROM sys.database_query_store_options;
  • If readonly_reason is non-zero, resolve the underlying storage or size-quota issue first.

Step 2: Confirm Permissions for the Cloning Login

  • Ensure the executing login has VIEW SERVER STATE and db_owner (or at minimum, CONTROL permission) on the source database.
  • Verify the login is a member of the sysadmin fixed server role, since DBCC CLONEDATABASE requires elevated rights to read internal statistics BLOBs.
  • Run the command from a query window authenticated under this validated login:
  DBCC CLONEDATABASE ('SourceDB', 'ClonedDB') WITH VERIFY_CLONE, NO_INDEXES;

Step 3: Rebuild Statistics and Re-enable Query Store Manually

  • If cloning completes with NOSTATISTICS/NOQUERYSTORE flags, connect to ClonedDB and run:
  EXEC sp_updatestats;
  • Re-enable Query Store manually on the clone:
  ALTER DATABASE ClonedDB SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);
  • Restart the SQL Server instance service via services.msc on Windows Server 2025 if Query Store fails to initialize after the ALTER DATABASE command.

Step 4: Check SQL Server Error Log for Underlying I/O Failures

  • Open SQL Server Management Studio (SSMS) → Management → SQL Server Logs.
  • Look for related Msg 12628 context lines mentioning Statistics skipped or Query Store initialization failed.
  • Cross-reference with Windows Event Viewer → Applications and Services Logs → MSSQLSERVER for disk or permission-related errors (Event ID 824 or 17204).

Alternative or Verification Steps

  • Verify the fix by querying sys.dm_db_stats_properties and sys.database_query_store_options on the cloned database to confirm statistics and Query Store are now populated/active.
  • If the issue persists, drop the clone and re-run DBCC CLONEDATABASE with the NO_INDEXES option removed, ensuring the source database is in a quiesced (no active transactions) state during the operation.

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

Troubleshooting Guide: SQL Server Error 12626 – “Clone Database Verification Has Passed”

Why This Error Happens

Error 12626 is actually an informational message, not a true failure, that appears when the DBCC CLONEDATABASE command completes its internal consistency checks successfully on SQL Server 2025. This message is logged when the clone operation finishes validating schema and statistics integrity between the source and the cloned (target) database. However, users often “encounter” this unexpectedly when the message is misread as an error in automation scripts, or when downstream permission issues on the newly created clone database prevent further access despite the clone itself being valid.

Step-by-Step Resolution Guide

Step 1: Confirm the Message Context in SQL Server Logs

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the exact log entry:
  EXEC sp_readerrorlog 0, 1, 'CLONEDATABASE';
  • Verify the message reads: “Database cloning for ‘[DBName]’ has finished. Please note this is a clone and not a backup and is not supported for use in a production environment. For more information about the use of database cloning, see http://go.microsoft.com/fwlink/?LinkId=824751” alongside the 12626 reference, confirming it is informational.

Step 2: Check Permissions on the Cloned Database

  • Since clone databases are set to READ_ONLY or restricted access by default, validate permissions using:
  SELECT name, state_desc, is_read_only FROM sys.databases WHERE name = 'YourClonedDB';
  • If access is denied for reporting tools, grant explicit db_datareader rights or adjust the database state:
  ALTER DATABASE YourClonedDB SET READ_WRITE;
  • On Windows Server 2025, ensure the SQL Server Service Account has NTFS permissions on the file path (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).

Step 3: Adjust Automation Scripts to Ignore Severity Level 10

  • If this message is halting a PowerShell or SSIS automation pipeline because it is being caught as an exception, update your error handling logic.
  • In PowerShell scripts using Invoke-Sqlcmd, add the -ErrorLevel parameter or wrap the command in a Try/Catch block that specifically filters for severity 10 messages:
  Invoke-Sqlcmd -Query $query -ServerInstance $server -ErrorAction SilentlyContinue
  • Update SQL Agent Job steps to select “Go to next step” instead of “Quit with failure” when the output contains the text “has passed.”

Step 4: Validate Statistics and Schema Integrity

  • Run DBCC CHECKDB on the newly cloned database to ensure the internal metadata matches the schema-only copy exactly.
  DBCC CHECKDB ('YourClonedDB') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Compare the sys.stats and sys.indexes views between the source and the clone to ensure the optimizer statistics copied correctly, which is the primary intent of the clone database feature.

Alternative or Verification Steps

  • Verification: Query sys.databases to confirm the source_database_id is NULL (indicating a successful detachment from the parent) and that the state is ONLINE.
  • Alternative: If the clone is still inaccessible or corrupted despite the “passed” message, drop the clone (DROP DATABASE YourClonedDB;) and re-run DBCC CLONEDATABASE with the NO_STATISTICS or NO_QUERYSTORE flags to rule out metadata corruption during the initial copy.

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

Troubleshooting Guide: SQL Server Error 12627 – Clone Database Verification Failed

Why This Error Happens

Error 12627 occurs when the DBCC CLONEDATABASE process fails its internal consistency verification step after creating the schema-only clone. This typically happens due to insufficient permissions on the source or destination database, a corrupted or inconsistent system metadata state in the source database, or because the source database was not set to READ_ONLY (or placed in a stable state) during the clone operation, causing a mismatch in the snapshot used for verification. Insufficient disk space on the target volume during the verification copy phase can also trigger this failure.

Step-by-Step Resolution Guide

Step 1: Verify Permissions and Server Role Membership

  • Ensure the executing login has VIEW SERVER STATE and ALTER ANY DATABASE permissions at minimum.
  • For SQL Server 2025, confirm the account is a member of the db_owner role on the source database, or has sysadmin rights for cross-database metadata access.
  • Run the following to check current permissions:
  SELECT IS_SRVROLEMEMBER('sysadmin');

Step 2: Run DBCC CHECKDB on the Source Database

  • Before cloning, validate the source database is free of corruption:
  DBCC CHECKDB ('YourSourceDB') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is found, repair it using REPAIR_REBUILD (avoid REPAIR_ALLOW_DATA_LOSS unless necessary).
  • Re-run the clone operation only after confirming zero allocation or consistency errors.

Step 3: Set the Source Database to READ_ONLY Before Cloning

  • Place the source database in a read-only state to prevent schema drift during the clone snapshot:
  ALTER DATABASE YourSourceDB SET READ_ONLY;
  • Execute the clone command:
  DBCC CLONEDATABASE ('YourSourceDB', 'YourClonedDB');
  • Revert the source database back to READ_WRITE once cloning completes:
  ALTER DATABASE YourSourceDB SET READ_WRITE;

Step 4: Check Disk Space and File Path Permissions

  • Confirm the destination data/log file path (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) has at least 2x the source database size in free space.
  • Verify the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control NTFS permissions on this directory via Windows Security > Properties > Security tab.

Step 5: Review SQL Server Error Log for Underlying Cause

  • Open the error log via SSMS: Management > SQL Server Logs > Current.
  • Search for entries immediately preceding Error 12627 to identify if it’s a metadata lock, I/O timeout, or statistics mismatch triggering the verification failure.

Alternative or Verification Steps

  • To verify the fix, re-run DBCC CLONEDATABASE and confirm the cloned database appears in Object Explorer with status “Normal” (not “Restoring” or “Suspect”), then run DBCC CHECKDB on the new clone to confirm zero errors.
  • If the issue persists, use DBCC CLONEDATABASE with the NO_STATISTICS, NO_QUERYSTORE options to bypass non-essential verification components as a temporary workaround while investigating root metadata corruption.

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

Troubleshooting Guide: Error 12625 – RESTORE VERIFY Failed on Clone Backup

Why This Error Happens

Error 12625 occurs when SQL Server 2025’s RESTORE VERIFYONLY operation detects that the backup file’s internal checksums or header structure do not match the expected values for the cloned backup set. This is typically caused by the backup file being truncated, corrupted during a copy/transfer operation, or modified by antivirus/backup software after creation. It can also occur if the clone operation (such as a storage-level snapshot or file-copy clone) completed before SQL Server released its file lock, resulting in an incomplete or inconsistent backup image.

Step-by-Step Resolution Guide

Step 1: Validate the Integrity of the Source Backup File

  • Run RESTORE VERIFYONLY FROM DISK = 'C:\SQLBackups\YourBackup.bak' against the original (non-cloned) backup file to confirm it is valid.
  • Check file size consistency between the source and cloned copy using Get-Item in PowerShell:
  • Get-Item "C:\SQLBackups\YourBackup.bak" | Select-Object Length
  • If the source file itself fails verification, the issue originates at backup time, not during cloning.

Step 2: Re-Clone the Backup File Using a Clean Copy Method

  • Ensure no process (antivirus, backup agent, or snapshot tool) is locking the file during the clone operation.
  • Use robocopy with checksum validation instead of a basic file copy:
  • robocopy C:\SQLBackups\ D:\ClonedBackups\ YourBackup.bak /J /V /NP
  • Confirm the destination volume (D:\ClonedBackups) has sufficient free space and is not using compression/deduplication that could alter file blocks.

Step 3: Exclude SQL Server Backup Paths from Antivirus/EDR Scanning

  • On Windows Server 2025, open Windows Security > Virus & threat protection > Manage settings > Exclusions.
  • Add exclusions for:
  • C:\SQLBackups\
  • D:\ClonedBackups\
  • The SQL Server Data/Log directories (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\)
  • Restart the SQL Server service and re-run the clone operation.

Step 4: Re-run RESTORE VERIFYONLY with CHECKSUM Validation

  • Execute the following T-SQL command against the cloned file:
  • RESTORE VERIFYONLY FROM DISK = 'D:\ClonedBackups\YourBackup.bak' WITH CHECKSUM;
  • If Error 12625 persists, regenerate the backup using WITH CHECKSUM enabled at backup time:
  • BACKUP DATABASE [YourDB] TO DISK = 'C:\SQLBackups\YourBackup.bak' WITH CHECKSUM, COMPRESSION;

Step 5: Check Storage-Level Snapshot or VSS Clone Timing

  • If using Volume Shadow Copy Service (VSS) or SAN-based snapshot cloning, verify the SQL Server VSS Writer completed successfully before the snapshot was taken.
  • Run vssadmin list writers in an elevated PowerShell session and confirm “SqlServerWriter” shows a state of [1] Stable with no errors.
  • If the writer shows a failed state, restart the SQL Server VSS Writer service and re-trigger the clone job.

Alternative or Verification Steps

  • Verify the fix by successfully running RESTORE VERIFYONLY FROM DISK = 'D:\ClonedBackups\YourBackup.bak' WITH CHECKSUM; and confirming the output returns “The backup set on file 1 is valid” with no errors.
  • As an alternative, skip file-level cloning entirely and use BACKUP DATABASE ... TO URL (Azure Blob Storage) or a native SQL Server backup replication tool to generate the clone directly from the source database, bypassing file-copy corruption risks altogether.

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

Troubleshooting Guide: SQL Server Error 12623 — “Clone backup succeeded and is stored in %ls”

Why This Error Happens

This message is actually an informational success notification raised by the Database Snapshot/Clone (DBCC CLONEDATABASE) feature in SQL Server 2025, which is logged with Severity Level 10, causing monitoring tools and scripts to misinterpret it as a critical failure. It typically surfaces when a scheduled clone-backup job finishes writing the schema-only clone to the path specified in %ls, but alerting systems (like SQL Agent or SCOM) are configured to flag any message containing “Error” in the SQL Server Error Log. In rare cases, this can also appear alongside a genuine issue if the clone path has restrictive NTFS permissions or insufficient disk space, causing a partial write that still triggers the log entry.

Step-by-Step Resolution Guide

Step 1: Verify the Clone File Actually Completed Successfully

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Navigate to Management > SQL Server Logs and locate the exact entry for Error 12623.
  • Note the full file path shown in place of %ls (e.g., C:\SQLClones\CloneDB_20250615.bak).
  • Run dir "C:\SQLClones\" in PowerShell or Command Prompt to confirm the file exists and has a non-zero size.

Step 2: Adjust Alerting Rules to Suppress False Positives

  • Open SQL Server Agent > Alerts in SSMS.
  • If an alert exists for “Error Number 12623,” edit it and set the Severity filter to only trigger on Severity ≥ 16 (true errors), since 12623 is Severity 10.
  • For SCOM or third-party monitoring, update the log-parsing rule (usually found in Monitoring Templates > SQL Server Error Log) to exclude Message ID 12623 from critical alert classifications.
  • Restart the SQL Server Agent service to apply changes:
  net stop SQLSERVERAGENT
  net start SQLSERVERAGENT

Step 3: Validate File System Permissions and Disk Space

  • Right-click the target clone folder (e.g., C:\SQLClones\) and go to Properties > Security.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Write and Modify permissions.
  • Check available disk space using:
  Get-PSDrive C | Select-Object Used,Free
  • If space is low, either clear old clone files or redirect the clone destination using the DBCC CLONEDATABASE syntax with a new path parameter.

Step 4: Re-Run the Clone Operation Manually to Confirm Stability

  • Execute the clone command manually in a new query window:
  DBCC CLONEDATABASE ('SourceDB', 'ClonedDB_Test');
  • Observe the Messages tab in SSMS — confirm it returns the success message with Error 12623 and a valid file path, with no accompanying Severity 16+ errors.

Alternative or Verification Steps

  • Verify the Fix: Check the SQL Server Error Log after the next scheduled job run — the 12623 entry should no longer trigger an email/SMS alert if Step 2 was applied correctly, while the clone file should still be present in the target directory.
  • Alternative Approach: If alerts continue to misfire due to third-party monitoring software, create a custom SQL Agent job step using sp_altermessage to lower the severity visibility of Message ID 12623, preventing it from being scraped by external log readers entirely.

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

Troubleshooting Guide: SQL Server Error 12624 – Clone Backup Failed

Why This Error Happens

Error 12624 in SQL Server 2025 typically occurs when the Database Snapshot/Clone feature cannot acquire a consistent point-in-time copy of the database due to insufficient disk space on the volume hosting the sparse file, or because the SQL Server service account lacks the necessary CREATE DATABASE and file system permissions on the target directory. This can also be triggered by an active, conflicting I/O lock from another backup or maintenance process (such as antivirus scanning or a concurrent DBCC CHECKDB operation) that prevents the clone operation from reading the source data pages. In some cases, the underlying NTFS volume does not support sparse files, which is a mandatory requirement for the DBCC CLONEDATABASE operation.

Step-by-Step Resolution Guide

Step 1: Verify Disk Space and Volume Compatibility

  • Navigate to the target drive (e.g., D:\SQLClones\) in File Explorer and confirm at least 2x the source database size is free.
  • Open PowerShell as Administrator and run fsutil fsinfo volumeinfo D: to confirm the volume reports “Supports Sparse Files” as True.
  • If the volume is ReFS or FAT32, reformat the target drive to NTFS, as sparse files are required for cloning.

Step 2: Check SQL Server Service Account Permissions

  • Open Computer Management > Services and identify the account running the SQL Server (MSSQLSERVER) service.
  • Right-click the target clone folder (e.g., C:\CloneBackups\), select Properties > Security, and ensure the service account has Full Control.
  • Run the following T-SQL command to verify the account context:
  • EXEC xp_cmdshell 'whoami';

Step 3: Terminate Conflicting Processes and Locks

  • Open SQL Server Management Studio (SSMS) and run sp_who2 to check for blocking sessions (SPIDs) on the source database.
  • Temporarily disable real-time scanning for the SQL data directory in Windows Defender via Windows Security > Virus & threat protection > Manage settings > Add Exclusion.
  • Retry the clone command: DBCC CLONEDATABASE ('SourceDB', 'ClonedDB');

Step 4: Validate TempDB and System Catalog Integrity

  • Run DBCC CHECKDB (tempdb) WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out system catalog corruption.
  • If corruption is found, restart the SQL Server service to rebuild tempdb from the model database.
  • Ensure tempdb has sufficient autogrowth space configured (minimum 10% autogrowth recommended).

Alternative or Verification Steps

  • Verification: Query the new database using SELECT DATABASEPROPERTYEX('ClonedDB', 'Status');—a result of ONLINE confirms the clone was successful and error 12624 is resolved.
  • Alternative: If DBCC CLONEDATABASE continues to fail, use the native Backup/Restore method instead by running a WITH COPY_ONLY backup and restoring it to a new database name to bypass the sparse file snapshot mechanism entirely.

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

Troubleshooting Guide: Error 12621 – Cloned Database Detected in SQL Server 2025

Why This Error Happens

This error occurs because the database was created using the DBCC CLONEDATABASE command, which generates a schema-and-statistics-only copy of a source database for diagnostic or troubleshooting purposes. SQL Server intentionally marks the resulting database with the IsClone property set to true in its metadata, and this flag triggers Error 12621 any time the database is accessed in a way that implies production use. The underlying data files are not transactionally consistent with live data and lack actual row-level content in user tables, making the database unsuitable and unsupported for production workloads.

Step-by-Step Resolution Guide

Step 1: Confirm the Database Is a Clone and Identify Its Origin

  • Run the following query to check the clone status:
  SELECT name, DATABASEPROPERTYEX(name, 'IsClone') AS IsCloneFlag
  FROM sys.databases
  WHERE name = 'YourDatabaseName';
  • If IsCloneFlag returns 1, this confirms the database was generated via DBCC CLONEDATABASE and is not intended for production.
  • Check SQL Server Error Logs (%ProgramFiles%\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to see when and how the clone was created.

Step 2: Remove the Clone Flag If Diagnostics Are Complete (Not Recommended for Production)

  • If you fully understand the risks and only need temporary access for read-only diagnostics, you can suppress the restriction using trace flag 3658 at the session level:
  DBCC TRACEON(3658, -1);
  • Alternatively, update the database property directly (unsupported and for lab/test environments only):
  ALTER DATABASE YourDatabaseName SET READ_ONLY;
  • Never apply this workaround to databases intended for live application connections.

Step 3: Restore or Rebuild a Proper Production Copy

  • Instead of bypassing the restriction, perform a proper BACKUP and RESTORE operation from the original source database to generate a fully functional, non-cloned copy:
  BACKUP DATABASE SourceDB TO DISK = 'C:\Backups\SourceDB.bak';
  RESTORE DATABASE NewProdDB FROM DISK = 'C:\Backups\SourceDB.bak'
  WITH MOVE 'SourceDB_Data' TO 'C:\SQLData\NewProdDB.mdf',
  MOVE 'SourceDB_Log' TO 'C:\SQLData\NewProdDB.ldf';
  • Point your application connection strings to this newly restored database instead of the cloned one.

Step 4: Clean Up the Cloned Database

  • Once diagnostics are complete, drop the cloned database to avoid accidental production use:
  DROP DATABASE YourClonedDatabaseName;
  • Verify no scheduled jobs, linked servers, or applications reference the clone before removal.

Alternative or Verification Steps

  • Verify the fix by querying DATABASEPROPERTYEX(name, 'IsClone') again on the new production database — it should return 0 or NULL.
  • If diagnostics require ongoing use of a clone, isolate it in a non-production instance and restrict access using SQL Server Logins/Roles so application traffic cannot accidentally connect to it.

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

Troubleshooting Guide: Error 12622 – Database Cloning Informational Message in SQL Server 2025

Why This Error Happens

Error 12622 is actually an informational message, not a true failure condition — it is logged by SQL Server whenever the DBCC CLONEDATABASE command completes successfully, confirming that a schema-only clone of the source database has been created. However, users often misinterpret this message as an error because it appears in the SQL Server Error Log or Event Viewer with a non-zero severity marker, especially when automated monitoring tools or scripts flag any entry containing “Error” as critical. In some cases, this message surfaces alongside actual underlying issues, such as insufficient disk space on the target volume, read-only filegroup conflicts, or permission restrictions on the db_owner role, which can cause the clone operation to partially complete or behave unexpectedly on Windows Server 2025 environments.

Step-by-Step Resolution Guide

Step 1: Confirm Whether This Is a True Error or Informational Log Entry

  • Open SQL Server Management Studio (SSMS) and check SQL Server Logs under Management > SQL Server Logs.
  • Search for Event ID 12622 and verify the accompanying text reads “Database cloning for ‘%.ls’ has finished. Cloned database is ‘%.ls’.” — this confirms a successful clone, not a failure.
  • Cross-reference the timestamp with your DBCC CLONEDATABASE execution to validate it aligns with your maintenance window or script run.

Step 2: Validate Permissions and Server Role Requirements

  • Ensure the executing login has sysadmin fixed server role membership, as DBCC CLONEDATABASE requires elevated privileges in SQL Server 2025.
  • Run the following to confirm role membership:
SELECT IS_SRVROLEMEMBER('sysadmin');
  • If the result returns 0, grant the role via:
ALTER SERVER ROLE sysadmin ADD MEMBER [DOMAIN\Username];

Step 3: Check Disk Space and File Path Configuration

  • Navigate to the default data directory, typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ on Windows Server 2025.
  • Confirm there is sufficient free disk space (at least 1.5x the size of the source database) to accommodate the cloned .mdf and .ldf files.
  • If space is low, redirect the clone output using the NO_STATISTICS or NO_QUERYSTORE parameters to reduce clone size, or move the clone to a secondary volume with adequate capacity.

Step 4: Suppress False-Positive Alerts in Monitoring Tools

  • Open your monitoring software (e.g., SCOM, Nagios, or custom PowerShell alert scripts) and locate the rule filtering SQL Server Error Log entries.
  • Add an exclusion filter for Event ID 12622 specifically matching the string “has finished” to prevent future false escalations.
  • Save and restart the monitoring service to apply the updated filter rule.

Alternative or Verification Steps

  • Verify the cloned database exists and is accessible by running SELECT name FROM sys.databases WHERE name = 'YourClonedDBName'; in SSMS — if it returns a row, the clone completed successfully despite the logged message.
  • If problems persist (e.g., clone appears incomplete), re-run DBCC CLONEDATABASE ('SourceDB', 'ClonedDB') WITH VERIFY_CLONEDB; to force an integrity check and confirm schema consistency against the source.

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

Troubleshooting Guide: Error 12619 – Database Clone Creation Fails Due to Long File Path

Why This Error Happens

Error 12619 occurs when the fully qualified file path for the database clone (data/log files) exceeds the maximum path length limit recognized by SQL Server’s DBCC CLONEDATABASE operation. This typically happens when the source database is nested deep within directory structures, or when auto-generated clone file names combined with timestamps push the total character count past the 260-character (MAX_PATH) threshold. It can also occur if the default data directory configured in SQL Server points to a long UNC path rather than a shorter local or mapped path.

Step-by-Step Resolution Guide

Step 1: Verify the Current File Path Length

  • Open SQL Server Management Studio (SSMS) and run the following query to check default data/log paths:
  • EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData';
  • Count the total character length including the database name, clone suffix, and .mdf/.ldf extensions — anything over 260 characters will trigger Error 12619.

Step 2: Relocate the Default Data and Log Directories

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services → right-click your instance → Properties → Startup Parameters.
  • Change the default data path to a shorter root-level directory, such as D:\SQLData\ instead of a deeply nested path like D:\Departments\Finance\Databases\2025\Archive\SQLData\.
  • Restart the SQL Server service for changes to take effect:
  • net stop MSSQLSERVER && net start MSSQLSERVER

Step 3: Enable Long Path Support in Windows

  • Open Group Policy Editor (gpedit.msc) on Windows Server 2025 or Windows 11.
  • Navigate to Computer Configuration → Administrative Templates → System → Filesystem.
  • Enable “Enable Win32 long paths” and apply the policy.
  • Alternatively, set the registry key directly:
  • reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1
  • Restart the server to apply filesystem-level changes.

Step 4: Manually Specify Shorter Clone File Paths

  • When running DBCC CLONEDATABASE, explicitly define shorter output paths instead of relying on SQL Server’s default naming convention:
  • DBCC CLONEDATABASE ('SourceDB', 'ClonedDB') WITH BACKUP_FILES, NO_STATISTICS;
  • Pre-create a short-path directory (e.g., C:\Clones\) dedicated solely to clone operations to avoid path inheritance issues from nested source folders.

Alternative or Verification Steps

  • Re-run DBCC CLONEDATABASE after applying the above changes and confirm the clone completes without Error 12619; check sys.databases to verify the cloned database is listed and accessible.
  • If the error persists, use PowerShell to symlink a shortened path (New-Item -ItemType SymbolicLink) pointing to the deep directory structure, effectively reducing the character count SQL Server evaluates during path validation.

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

Why This Error Happens

Error 12620 is not actually a failure condition but an informational message logged when the DBCC CLONEDATABASE command is executed; it simply confirms that the schema-and-statistics-only clone operation has begun. The message is often misinterpreted as a blocking error because the cloning process appears to “hang” in the SQL Server Error Log without a corresponding completion message. In most cases, this is tied to insufficient disk space on the target drive, restrictive filesystem permissions for the SQL Server service account, or the source database being in an inconsistent state (e.g., suspect or in single-user mode) that prevents the clone from finalizing.

Step-by-Step Resolution Guide

Step 1: Verify Source Database Health and Permissions

  • Run DBCC CHECKDB against the source database to confirm it is not in a SUSPECT, EMERGENCY, or RESTORING state.
  • Confirm the login executing the command has sysadmin or db_owner rights on the source database, since DBCC CLONEDATABASE requires elevated privileges.
  • Check that the SQL Server service account has write access to the target data directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).

Step 2: Check Disk Space and File System Constraints

  • Open File Explorer or run Get-PSDrive in PowerShell on Windows Server 2025 to confirm there is at least 2x the source database size free on the target volume.
  • Validate that Windows Defender or any third-party antivirus is not actively scanning/locking the .mdf/.ndf files during the clone operation, which can stall the process indefinitely.
  • Temporarily exclude the SQL Server DATA and LOG folders from real-time antivirus scanning via Windows Security settings.

Step 3: Re-run the Clone Operation with Explicit Logging

  • Execute the command manually with verbose output enabled:
  DBCC CLONEDATABASE ('SourceDB', 'SourceDB_Clone') WITH VERIFY_CLONEDB;
  • Monitor the SQL Server Error Log (via EXEC sp_readerrorlog or SQL Server Management Studio’s Log File Viewer) for the follow-up completion message indicating success or a specific failure reason (e.g., “Database cloning for ‘…’ has finished”).
  • If the operation stalls past expected duration (based on source DB size), check sys.dm_exec_requests for blocking sessions using the clone’s SPID.

Step 4: Restart SQL Server Service if Clone Remains Stuck

  • Open Services.msc on Windows Server 2025, locate SQL Server (MSSQLSERVER), and restart it during a maintenance window.
  • After restart, drop any incomplete clone database using DROP DATABASE SourceDB_Clone and retry Step 3.

Alternative or Verification Steps

  • Confirm success by querying sys.databases for the new clone database and verifying its state_desc equals ONLINE.
  • If the clone consistently fails, use DBCC CLONEDATABASE with the NO_STATISTICS or NO_QUERYSTORE options to isolate whether statistics or Query Store data corruption is causing the stall.

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

Troubleshooting Guide: SQL Server Error 12617 – “File Path of the Database Is Not Supported”

Why This Error Happens

Error 12617 typically occurs when SQL Server 2025 attempts to create, attach, or restore a database to a file path that resides on an unsupported storage medium, such as a network share (UNC path) without proper configuration, a removable drive, or a path referencing a non-NTFS/ReFS file system. This error can also surface when the path includes unsupported characters, exceeds Windows’ maximum path length, or points to a location where the SQL Server service account lacks the necessary file system permissions. Additionally, newer security hardening in Windows Server 2025 and Windows 11 restricts certain local and network path types by default, which can trigger this validation failure during database file operations.

Step-by-Step Resolution Guide

Step 1: Verify the File Path Format and Location

  • Confirm the path does not use a mapped network drive letter (e.g., Z:\Databases\MyDB.mdf); SQL Server does not support mapped drives for database files.
  • If using a network location, convert it to a proper UNC path (e.g., \\FileServer\SQLData\MyDB.mdf) and ensure the SQL Server service account has access.
  • Check that the path length does not exceed 260 characters unless long path support is explicitly enabled in Windows Server 2025.

Step 2: Enable Long Path Support (If Applicable)

  • Open Group Policy Editor (gpedit.msc) and navigate to:
    Computer Configuration > Administrative Templates > System > Filesystem
  • Enable the policy “Enable Win32 long paths.”
  • Alternatively, apply the following registry change and restart the server:
 reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1

Step 3: Grant Proper NTFS Permissions to the SQL Server Service Account

  • Open File Explorer, right-click the target database folder (e.g., D:\SQLData\), and select Properties > Security.
  • Add the SQL Server service account (e.g., NT SERVICE\MSSQLSERVER) with Full Control permissions.
  • Apply changes and restart the SQL Server service via SQL Server Configuration Manager.

Step 4: Validate Storage Compatibility

  • Ensure the target drive is formatted as NTFS or ReFS; FAT32 and exFAT are not supported for SQL Server data files.
  • If using Storage Spaces Direct or a SAN, confirm the volume is properly mounted and recognized by Windows Server 2025 before retrying the operation.

Step 5: Retry the Database Operation Using a Local Validated Path

  • Test by creating or restoring the database to a known-good local path, such as C:\SQLData\TestDB.mdf, to isolate whether the issue is path-specific or environment-wide.
  • If successful, gradually reintroduce the original network or custom path configuration.

Alternative or Verification Steps

  • Run sp_helpdb or check SQL Server Management Studio (SSMS) > Database Properties > Files to confirm the new path registers correctly without triggering Error 12617.
  • If the issue persists, use the DBCC CHECKDB command alongside Windows Event Viewer logs (Applications and Services Logs > MSSQLSERVER) to rule out underlying storage or permission conflicts.

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

Why This Error Happens

Error 12618 occurs when a database approaches or exceeds the internal object limit enforced by the SQL Server metadata engine, which caps combined schema entities (tables, views, procedures, indexes, and constraints) at a fixed threshold per database. This is typically triggered by automated schema generation processes, ORM frameworks creating excessive temporary objects, or replication/CDC jobs that fail to clean up shadow tables. In rare cases, corrupted system catalog views (sys.objects) can also miscount entries and falsely trigger this limit.

Step-by-Step Resolution Guide

Step 1: Identify the Object Count and Source

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check current object counts:
SELECT type_desc, COUNT(*) AS ObjectCount 
FROM sys.objects 
GROUP BY type_desc 
ORDER BY ObjectCount DESC;
  • Look for abnormal spikes in USER_TABLE, INTERNAL_TABLE, or SYSTEM_TABLE categories, which often indicate runaway object creation.

Step 2: Clean Up Orphaned or Temporary Objects

  • Check for leftover temporary tables or CDC/replication artifacts using:
SELECT name, create_date 
FROM sys.tables 
WHERE name LIKE '#%' OR name LIKE 'CDC_%';
  • Drop unused objects in batches to avoid transaction log bloat:
DROP TABLE IF EXISTS [schema].[object_name];
  • If using an ORM (Entity Framework, Hibernate), review migration scripts for duplicate or auto-incrementing table creation logic.

Step 3: Rebuild the System Catalog Views

  • If object counts appear inconsistent with actual database content, run a consistency check:
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORS;
  • If corruption is detected in metadata, restore from the last known good backup rather than attempting a repair, as REPAIR_ALLOW_DATA_LOSS can worsen object count discrepancies.

Step 4: Adjust Application-Level Object Management

  • On Windows Server 2025 / Windows 11, open Task Scheduler and review any automated jobs (e.g., nightly ETL or schema-sync scripts) that may be creating objects without a corresponding cleanup step.
  • Update connection strings or ORM configuration files to disable auto-migration features in production environments.

Alternative or Verification Steps

  • After cleanup, re-run the sys.objects count query from Step 1 and confirm the total is well below the per-database object ceiling (typically under 2 billion, but issues often arise much earlier due to index/constraint multiplication).
  • If Error 12618 persists after cleanup, consider splitting the database using horizontal partitioning or migrating historical data to an archive database to permanently reduce object density.

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

Troubleshooting Guide: Error 12616 – Failed to Drop Partially Created Cloned Database

Why This Error Happens

Error 12616 typically occurs when the DBCC CLONEDATABASE operation is interrupted mid-process, leaving behind a database in an inconsistent state (neither fully online nor fully recognized as a clone). This usually happens because SQL Server 2025 still holds an active file lock or metadata reference to the cloned database files, preventing a clean DROP DATABASE command from executing. In most cases, this is caused by lingering sessions, insufficient permissions on the file system path, or the database being incorrectly flagged as read-only during the failed cloning transaction.

Step-by-Step Resolution Guide

Step 1: Identify and Terminate Active Sessions

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a new query window.
  • Run sp_who2 or query sys.dm_exec_sessions to check for active connections to the partially cloned database.
  • Execute ALTER DATABASE [ClonedDB_Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; to forcibly disconnect lingering sessions.

Step 2: Verify Database State and Permissions

  • Check the state of the database using: SELECT name, state_desc FROM sys.databases WHERE name = 'ClonedDB_Name';
  • If the state shows RECOVERY_PENDING or SUSPECT, ensure the SQL Server service account has Full Control permissions on the default data path (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Ensure no external backup software (like VSS writers) is holding a handle to the .mdf or .ldf files in Windows Server 2025.

Step 3: Force Drop the Database

  • Attempt the standard drop command again now that the DB is in single-user mode: DROP DATABASE [ClonedDB_Name];
  • If Error 12616 persists, detach the database instead of dropping it: EXEC sp_detach_db 'ClonedDB_Name', 'true';
  • Manually delete the orphaned .mdf and .ldf files from the file explorer or via PowerShell (Remove-Item -Path "C:\...\ClonedDB_Name.mdf" -Force).

Step 4: Re-attach and Clean Metadata (If Files Remain Locked)

  • If the files are still locked by the OS, restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER to release file handles.
  • Re-run the DROP DATABASE command immediately after the service restart before any other process can lock the files again.
  • Check Windows Event Viewer (System logs) for any “Disk” or “Ntfs” errors that might indicate the file system is preventing deletion due to corruption.

Alternative or Verification Steps

  • Verification: Run SELECT name FROM sys.databases; to confirm the cloned database name no longer appears in the list, and check the physical DATA directory to ensure the .mdf/.ldf files have been removed.
  • Alternative: If the drop still fails due to file corruption, put the database in EMERGENCY mode (ALTER DATABASE [ClonedDB_Name] SET EMERGENCY;) before attempting the SINGLE_USER and DROP sequence again.

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

Troubleshooting Guide: SQL Server Error 12614 – “Failed to Get Collation Name”

Why This Error Happens

This error typically occurs when SQL Server 2025 cannot properly resolve or read collation metadata from the sys.collations catalog view, often due to a corrupted system database (especially master or tempdb) or an incomplete service pack/cumulative update installation. It can also surface when a database is restored or attached from an incompatible or deprecated collation version that Windows Server 2025 / Windows 11’s underlying NLS (National Language Support) libraries no longer recognize. In some cases, missing or mismatched .nls language files after an OS upgrade prevent SQL Server from mapping the collation ID to its corresponding name.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Apply Latest Updates

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; to confirm the current build number.
  • Compare against the latest Cumulative Update (CU) for SQL Server 2025 on the Microsoft Update Catalog.
  • Download and install the latest CU, as collation-handling bugs are frequently patched in early-release cycles.

Step 2: Check and Repair System Database Integrity

  • Open Command Prompt as Administrator and stop the SQL Server service: net stop MSSQLSERVER.
  • Restart SQL Server in single-user mode: sqlservr.exe -m -T3608 (this prevents auto-recovery of all databases except master).
  • Run DBCC CHECKDB('master') WITH NO_INFOMSGS, ALL_ERRORMSGS; to detect corruption.
  • If errors are found, restore master from a known-good backup or rebuild system databases using setup.exe /ACTION=REBUILDDATABASE.

Step 3: Validate Windows NLS and Regional Language Files

  • Navigate to C:\Windows\Globalization\Sorting\ and confirm the required .nls files (e.g., sortdefault.nls) are present and not corrupted.
  • Run sfc /scannow in an elevated PowerShell window to repair missing or damaged OS system files.
  • Reboot the server and confirm the regional/language pack matches the collation originally used when the database was created (Settings > Time & Language > Language & Region).

Step 4: Recreate or Alter the Affected Database Collation

  • Identify the problematic database using SELECT name, collation_name FROM sys.databases;.
  • If a specific database shows a NULL or unrecognized collation, run:
    ALTER DATABASE [YourDB] COLLATE SQL_Latin1_General_CP1_CI_AS;
  • Export and re-import any inconsistent tables if the ALTER DATABASE command fails due to column-level collation conflicts.

Alternative or Verification Steps

  • To verify the fix, run SELECT SERVERPROPERTY('Collation'); and SELECT name, collation_name FROM sys.databases; — both should return valid, non-null collation names without triggering Error 12614.
  • If the issue persists after patching and system database repair, perform a full uninstall/reinstall of the SQL Server instance, ensuring the Windows Server 2025 language pack is installed before SQL Server setup begins.

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

Troubleshooting Guide: Error 12615 — “Failed to Get Database Properties” in SQL Server 2025

Why This Error Happens

Error 12615 typically occurs when the SQL Server service account or the currently logged-in user lacks sufficient permissions (such as VIEW DATABASE STATE or ALTER ANY DATABASE) to query system catalog views needed to render database properties. This can also happen due to a corrupted SSMS (SQL Server Management Studio) cache, an outdated version of SSMS incompatible with SQL Server 2025, or network/authentication timeouts when communicating with the SQL instance on Windows Server 2025 / Windows 11. In some cases, orphaned system metadata or a damaged model database can prevent the properties dialog from retrieving accurate configuration data.

Step-by-Step Resolution Guide

Step 1: Verify User and Login Permissions

  • Open SQL Server Management Studio (SSMS) and connect using an account with sysadmin privileges.
  • Run the following query to check role membership:
  SELECT IS_SRVROLEMEMBER('sysadmin');
  • If the result is 0, grant appropriate permissions:
  ALTER SERVER ROLE sysadmin ADD MEMBER [YourDomain\YourUser];

Step 2: Clear SSMS Cache and Update to Latest Version

  • Close SSMS completely.
  • Delete the cached settings folder located at:
    %AppData%\Microsoft\SQL Server Management Studio\<version>\
  • Download and install the latest SSMS build compatible with SQL Server 2025 from the official Microsoft Download Center.
  • Reopen SSMS and reconnect to the instance.

Step 3: Check SQL Server Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Ensure the service account has Log on as a service rights via:
    Local Security Policy > Local Policies > User Rights Assignment
  • Restart the SQL Server service after any changes.

Step 4: Validate System Database Integrity

  • Run a consistency check on the model and master databases:
  DBCC CHECKDB('model') WITH NO_INFOMSGS;
  DBCC CHECKDB('master') WITH NO_INFOMSGS;
  • If corruption is detected, restore from a recent backup or rebuild system databases using the SQL Server Installation Center repair option.

Step 5: Review Firewall and Network Configuration

  • Confirm TCP port 1433 (or custom port) is open in Windows Defender Firewall with Advanced Security.
  • Verify the SQL Server Browser service is running if using named instances.
  • Test connectivity using:
  Test-NetConnection -ComputerName <ServerName> -Port 1433

Alternative or Verification Steps

  • After applying the fixes, right-click the affected database in SSMS Object Explorer and select Properties again to confirm the dialog loads without error.
  • As an alternative, query the properties directly via T-SQL to bypass the GUI:
  SELECT * FROM sys.databases WHERE name = 'YourDatabaseName';

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

Troubleshooting Guide: Error 12612 — Failed to Sync Boot Page with Database Registration

Why This Error Happens

Error 12612 typically occurs when SQL Server 2025 is unable to write or synchronize the boot page metadata with the database’s registration record in the master database, often due to a mismatch between the database’s internal registration GUID and the boot page header. This can result from an abrupt shutdown, storage-level file corruption (particularly on the primary .mdf file), or insufficient disk-level permissions preventing the SQL Server service account from updating the boot page during startup or failover. In clustered or Always On Availability Group configurations, this error can also surface when replica metadata falls out of sync with the primary node’s registration table.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Confirm the SQL Server service account has full read/write access to the database files directory (default: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA).
  • Open Services.msc, right-click the SQL Server (MSSQLSERVER) service, and verify the “Log On As” account matches the account granted NTFS permissions on the DATA folder.
  • Run icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA" in an elevated Command Prompt to confirm Modify and Write rights are present.

Step 2: Take the Database Offline and Run Consistency Checks

  • Open SQL Server Management Studio (SSMS) and execute:
  ALTER DATABASE [YourDatabaseName] SET OFFLINE WITH ROLLBACK IMMEDIATE;
  • Bring it back online and immediately run:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review output for boot page corruption flags (look for Msg 8909 or Msg 8992 alongside 12612).

Step 3: Rebuild the Boot Page Registration Entry

  • Stop the SQL Server service via net stop MSSQLSERVER.
  • Use a known-good backup of the master database if corruption is confirmed on the registration table.
  • Restore master using single-user mode:
  sqlservr.exe -m -T3608
  • Restart the instance normally and re-attach the affected user database using CREATE DATABASE ... FOR ATTACH.

Step 4: Apply the Latest Cumulative Update

  • Navigate to Windows Update or the Microsoft Download Center and confirm SQL Server 2025 is patched to the latest Cumulative Update (CU), as early builds have a known boot page sync race condition during fast failover.
  • Reboot the Windows Server 2025 / Windows 11 host after patching to clear any cached registration locks.

Alternative or Verification Steps

  • After completing the steps, run sp_helpdb to confirm the database status reads ONLINE with no pending recovery flags, and re-check the Windows Event Viewer (Application Log) for Event ID 12612 recurrence over a 24-hour monitoring window.
  • If the error persists, restore the entire database from the last known-good full backup rather than attempting further in-place repairs, as repeated boot page desync often indicates underlying disk corruption requiring a storage-level chkdsk /f scan.

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

Why This Error Happens

Error 12613 occurs when the DBCC CLONEDATABASE command attempts to copy schema and statistics from a source database that exceeds the internal threshold for file or filegroup objects. SQL Server 2025 imposes a hard limit on the number of file metadata entries that can be processed in a single cloning transaction to prevent excessive log generation and memory pressure. This typically happens with large enterprise databases that have been partitioned extensively across multiple filegroups over time.

Step-by-Step Resolution Guide

Step 1: Verify the Current File and Filegroup Count

  • Open SQL Server Management Studio (SSMS) and connect to the instance on Windows Server 2025.
  • Run the following query to check the total count:
  SELECT COUNT(*) FROM sys.database_files;
  SELECT COUNT(*) FROM sys.filegroups;
  • Confirm whether the combined total exceeds the supported threshold (typically 1,000 objects in SQL Server 2025 cloning operations).

Step 2: Consolidate Unnecessary Filegroups

  • Identify empty or legacy filegroups using sys.filegroups and sys.database_files.
  • Use ALTER DATABASE [YourDB] REMOVE FILE [logical_file_name]; to drop unused secondary files.
  • Migrate data from redundant filegroups into a primary consolidated filegroup using ALTER TABLE ... MOVE (for partitioned tables) where applicable.

Step 3: Use Filtered Cloning via Manual Scripting

  • Instead of DBCC CLONEDATABASE, generate a schema-only script using the “Generate Scripts” wizard in SSMS.
  • Right-click the database > Tasks > Generate Scripts > select “Schema Only” and exclude non-essential filegroup definitions.
  • Execute the generated .sql file against a new empty database to replicate the schema without triggering the file-count limit.

Step 4: Apply the Latest Cumulative Update

  • Navigate to the Microsoft Update Catalog and verify your build number via:
  SELECT @@VERSION;
  • Install the latest Cumulative Update (CU) for SQL Server 2025, as early builds had a lower internal cap for DBCC CLONEDATABASE that was increased in subsequent patches.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after patching.

Alternative or Verification Steps

  • Verify the Fix: Re-run DBCC CLONEDATABASE ('SourceDB', 'ClonedDB'); after consolidation; if successful, check sys.filegroups on the ClonedDB to confirm structural integrity matches expectations.
  • Alternative Solution: If consolidation isn’t feasible due to business constraints, use the Database Experimentation Assistant (DEA) or manually export statistics via sp_helpstats combined with a schema-only backup/restore to a new database file structure.

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

Troubleshooting Guide: Error 12610 – Failed to Update Database Registration

Why This Error Happens

Error 12610 typically occurs when SQL Server 2025 cannot write updated registration metadata to the msdb system database or local registration cache due to insufficient permissions on the SQL Server service account. This can also happen if the registered servers XML file (stored in the user profile) becomes corrupted or locked by another process. Additionally, a mismatch between the SQL Server Management Studio (SSMS) version and the SQL Server 2025 engine can cause schema validation failures during the registration update handshake.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11 and confirm the SQL Server service is running under a valid domain or managed service account.
  • Ensure the account has db_owner rights on the msdb database.
  • Run the following query in SSMS to check permissions:
USE msdb;
EXEC sp_helprotect NULL, 'ServiceAccountName';

Step 2: Clear the Corrupted Registered Servers Cache

  • Close all instances of SSMS.
  • Navigate to the local cache path:
    C:\Users\<YourUsername>\AppData\Roaming\Microsoft\SQL Server Management Studio\<Version>\RegSrvr.xml
  • Rename the file to RegSrvr_old.xml to force SSMS to regenerate a clean registration file on next launch.

Step 3: Validate SSMS and Engine Version Compatibility

  • Confirm you are running the latest build of SSMS compatible with SQL Server 2025 (Build 17.x or higher).
  • Check for pending Windows Updates via Settings > Windows Update that may include critical SQL client library patches.
  • Restart the SQL Server (MSSQLSERVER) service after updates are applied:
Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Repair the msdb System Database

  • If the error persists, check the integrity of the msdb database using:
DBCC CHECKDB ('msdb') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Address any reported allocation or consistency errors before retrying the registration update.

Alternative or Verification Steps

  • To verify the fix, right-click the server node in Object Explorer, select Register, and attempt to update properties again—it should save without triggering Error 12610.
  • If the issue persists, create a new local Server Group in SSMS and re-register the database server from scratch to bypass the corrupted registration entry entirely.

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

Troubleshooting Guide: Error 12611 — “Failed to Get Database Registration Attributes”

Why This Error Happens

Error 12611 typically occurs when SQL Server 2025 cannot read or validate the metadata associated with a database’s registration in the system catalog, often due to corrupted registration attribute entries or an inconsistent state between the database engine and the Windows Server 2025 / Windows 11 registry hive used for service registration. This can also stem from insufficient permissions on the SQL Server service account, preventing it from accessing the registration keys stored under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server. In some cases, a failed or interrupted database attach/restore operation leaves orphaned registration attributes that the engine cannot reconcile on subsequent access.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Open Services.msc and confirm the account running the SQL Server (MSSQLSERVER or named instance) service.
  • Ensure this account has Full Control on the registry path HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\<InstanceID>.
  • Also verify NTFS permissions on the database file directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA) grant the service account Modify rights.

Step 2: Check and Repair Database Registration Metadata

  • Open SQL Server Management Studio (SSMS) and run the following to inspect registration consistency:
  DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is detected in system metadata, run:
  ALTER DATABASE YourDatabaseName SET EMERGENCY;
  DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);
  ALTER DATABASE YourDatabaseName SET MULTI_USER;
  • Take a full backup before running repair commands with data loss options.

Step 3: Re-register the Database Instance

  • Detach the affected database:
  EXEC sp_detach_db 'YourDatabaseName';
  • Re-attach it using the primary .mdf file to force SQL Server to rebuild registration attributes:
  CREATE DATABASE YourDatabaseName ON (FILENAME = 'C:\Path\To\YourDatabase.mdf') FOR ATTACH;
  • Restart the SQL Server service via SQL Server Configuration Manager to flush cached registration data.

Step 4: Validate Windows Server Registry Hive Integrity

  • Run regedit and navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server.
  • Export the key as a backup, then use sfc /scannow and DISM /Online /Cleanup-Image /RestoreHealth from an elevated Command Prompt to repair underlying OS-level corruption affecting the registry.

Alternative or Verification Steps

  • Confirm resolution by querying sys.databases and sys.master_files to ensure the database state reads ONLINE with no pending metadata warnings, and recheck the SQL Server Error Log for recurrence of Event ID 12611.
  • If the issue persists, restore the database from the most recent known-good backup to a new instance name, which bypasses corrupted registration attributes entirely.

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

Troubleshooting Guide: Error 12608 – “Specified clone database name already exists”

Why This Error Happens

This error occurs when the DBCC CLONEDATABASE command is executed with a target clone name that already exists as a database on the SQL Server instance. SQL Server 2025 enforces a strict uniqueness check on clone database names to prevent accidental overwriting of existing data or schema-only databases. This typically happens when a previous clone operation failed midway without cleanup, or when a script is re-run without altering the output database name.

Step-by-Step Resolution Guide

Step 1: Verify Existing Database Names

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check for naming conflicts:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourCloneDBName';
  • Confirm whether the existing database is a leftover “ghost” clone from a previous failed attempt.

Step 2: Remove or Rename the Conflicting Database

  • If the existing database is an orphaned clone (usually read-only and schema-only), drop it using the following command:
  DROP DATABASE YourCloneDBName;
  • If the database contains critical data that must be preserved, rename it instead to free up the naming slot:
  ALTER DATABASE YourCloneDBName MODIFY NAME = YourCloneDBName_Archive;
  • Ensure no active connections are using the database by setting it to SINGLE_USER mode before dropping if the DROP command fails.

Step 3: Re-run the Clone Command with a Unique Identifier

  • Modify your DBCC CLONEDATABASE script to include a timestamp or incremental suffix to avoid future collisions.
  • Example command structure:
  DBCC CLONEDATABASE ('SourceDB', 'SourceDB_Clone_20250615');
  • Verify that the SQL Server service account has the necessary db_owner permissions on the model database to facilitate the creation of the new clone.

Step 4: Check File System for Orphaned MDF/LDF Files

  • Navigate to the default data directory, typically located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\.
  • Look for .mdf or .ldf files matching the clone name that might be locked by the OS even if the database entry was removed from sys.databases.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc if files appear locked by a zombie process.

Alternative or Verification Steps

  • Verification: Re-run the DBCC CLONEDATABASE command with the new unique name and confirm the output returns a success message without the 12608 error code.
  • Alternative: If the error persists due to a sync issue between the OS file system and SQL metadata, restart the SQL Server instance to clear cached database state information before attempting the clone again.

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

Troubleshooting Guide: SQL Server Error 12609 – “Failed to Get File Attributes”

Why This Error Happens

This error typically occurs when SQL Server 2025 attempts to access a database file (MDF/LDF/NDF) or backup file on disk but is blocked due to insufficient NTFS permissions for the SQL Server service account. It can also arise from file system corruption, a locked file held by another process (such as an antivirus scanner or backup utility), or the target path residing on a volume that has been disconnected or become inaccessible (e.g., a dismounted network share or offline storage pool). Additionally, this can surface during Instant File Initialization checks if the service account lacks the SeManageVolumePrivilege right on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify File and Folder Permissions

  • Navigate to the data directory (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA) and right-click the affected file to check Properties > Security.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER or a custom domain account) has Read, Write, and Modify permissions.
  • Use PowerShell to quickly audit permissions: Get-Acl "D:\SQLData\YourDB.mdf" | Format-List.

Step 2: Check for File Locks or Antivirus Interference

  • Use Process Explorer or Handle.exe from Sysinternals to identify if another process (backup agent, antivirus, or indexing service) has an open handle on the file.
  • Add SQL Server data/log directories to your antivirus exclusion list to prevent real-time scanning conflicts.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after releasing the lock.

Step 3: Confirm Storage Volume Availability

  • Open Disk Management (diskmgmt.msc) to verify the drive hosting the database files is online and not in a “Reconnecting” or “Offline” state.
  • For network-attached storage, confirm the share path is reachable using Test-Path "\\StorageServer\SQLShare\" in PowerShell.
  • If using Storage Spaces Direct on Windows Server 2025, run Get-VirtualDisk to ensure the virtual disk health status is Healthy.

Step 4: Grant Instant File Initialization Rights

  • Open Local Security Policy (secpol.msc) and navigate to Local Policies > User Rights Assignment.
  • Add the SQL Server service account to the Perform Volume Maintenance Tasks policy.
  • Restart the SQL Server service for the privilege to take effect, which resolves file attribute read failures during database creation or restore operations.

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDatabaseName') to confirm the database is accessible and free of corruption after applying the fixes.
  • If the error persists, detach the database (sp_detach_db) and re-attach it manually via SSMS, specifying the correct file path to force SQL Server to re-validate file attributes.

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

Troubleshooting Guide: SQL Server Error 12607 – “Specified clone database name is too long”

Why This Error Happens

This error occurs when using the DBCC CLONEDATABASE command with a target database name that exceeds the maximum allowed length of 128 characters for a SQL Server identifier. It typically happens when scripts auto-generate clone names by appending timestamps, GUIDs, or descriptive suffixes (e.g., _clone_diagnostic_backup_20250101) to an already long source database name. Since SQL Server validates the identifier length before creating the clone, the operation fails immediately without creating any files.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Length of the Proposed Clone Name

  • Review the DBCC CLONEDATABASE T-SQL statement that triggered the error.
  • Count the characters in the name specified after the AS keyword in your query.
  • Run the following query in SQL Server Management Studio (SSMS) to confirm the limit:
  SELECT LEN(N'YourProposedCloneNameHere') AS NameLength;
  • Confirm if the result exceeds 128 characters, as this is the strict limit for sysname data types in SQL Server 2025.

Step 2: Shorten the Clone Database Name

  • Edit your T-SQL script or PowerShell automation job to use a shorter, concise naming convention.
  • Avoid appending full datetime stamps (e.g., YYYYMMDD_HHMMSS) and instead use shorter Julian dates or sequential IDs.
  • Example of a corrected command:
  DBCC CLONEDATABASE ('ProductionDB_LongName', 'ProdDB_Clone_01');
  GO
  • Ensure the total character count, including the database owner prefix if applicable, stays under the 128-character threshold.

Step 3: Check for Hidden Whitespace or Unicode Characters

  • Inspect the string in your automation tool (such as Azure Data Studio or a PowerShell variable) for trailing spaces or hidden Unicode characters that might inflate the string length unexpectedly.
  • If using PowerShell to generate the name dynamically, utilize the .Trim() method to remove excess whitespace:
  $CloneName = $CloneName.Trim()
  • Re-run the DBCC CLONEDATABASE command with the sanitized variable.

Step 4: Verify Instance Collation Settings

  • Check if the SQL Server instance on Windows Server 2025 is using a double-byte character set (DBCS) collation, as this can sometimes affect how character limits are interpreted by legacy tools.
  • Run sp_helpsort to view the current server collation.
  • Adjust the naming convention to use standard ASCII characters only to avoid parsing discrepancies in the Database Engine.

Alternative or Verification Steps

  • Verification: Re-execute the DBCC CLONEDATABASE command with the shortened name and confirm the new database appears in the Object Explorer under SSMS without throwing Error 12607.
  • Alternative: If the application logic absolutely requires a long descriptive name, use a standard BACKUP and RESTORE WITH MOVE sequence instead of DBCC CLONEDATABASE, as the standard restore process allows for the renaming of physical files independently of the logical database name constraints.

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

Troubleshooting Guide: SQL Server Error 12605 — Failed to Create Snapshot Database

Why This Error Happens

Error 12605 typically occurs when SQL Server cannot create or access the sparse file(s) required for a database snapshot, often due to insufficient NTFS permissions on the snapshot directory or the underlying volume not supporting sparse files (e.g., FAT32 or ReFS misconfiguration). It can also occur if the source database path is unreachable, the disk has insufficient free space, or the SQL Server service account lacks write access to the target folder. Additionally, antivirus or endpoint protection software on Windows Server 2025 may lock the file handle during snapshot creation, triggering this failure.

Step-by-Step Resolution Guide

Step 1: Verify NTFS Permissions on the Target Directory

  • Navigate to the folder where the snapshot .ss file is being created (e.g., D:\SQLData\Snapshots\).
  • Right-click the folder → Properties → Security tab.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control permissions.
  • Apply changes and restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 2: Confirm the File System Supports Sparse Files

  • Open Command Prompt as Administrator and run fsutil fsinfo volumeinfo D: to check the file system type.
  • Confirm the volume is formatted as NTFS (ReFS and FAT32 do not support the sparse file operations required for snapshots).
  • If the volume is not NTFS, reformat or choose a different NTFS-formatted volume for the snapshot path.

Step 3: Check Disk Space and Path Validity

  • Run Get-PSDrive -PSProvider FileSystem in PowerShell to confirm sufficient free space on the target drive.
  • Validate that the source database .mdf file path referenced in the CREATE DATABASE ... AS SNAPSHOT OF statement is correct and accessible.
  • Re-run the snapshot creation query:
  CREATE DATABASE SnapshotDB_Test ON
  (NAME = SourceDB, FILENAME = 'D:\SQLData\Snapshots\SourceDB_Snap.ss')
  AS SNAPSHOT OF SourceDB;

Step 4: Temporarily Disable Antivirus/Real-Time Protection

  • Exclude the SQL Server data and snapshot directories from Windows Defender or third-party antivirus real-time scanning.
  • Use PowerShell: Add-MpPreference -ExclusionPath "D:\SQLData\Snapshots\".
  • Retry the snapshot creation command to confirm whether the AV software was blocking file creation.

Alternative or Verification Steps

  • Verify the fix by querying sys.databases to confirm the snapshot database appears with source_database_id populated correctly.
  • If the issue persists, create the snapshot on a local NTFS volume (not a network share or mapped drive) since SQL Server snapshots do not support remote UNC paths.

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

Troubleshooting Guide: SQL Server Error 12606 – “Failed to Set Snapshot Database Name”

Why This Error Happens

Error 12606 typically occurs when SQL Server 2025 cannot generate or assign a unique name for a database snapshot, often because the source database name is invalid, inaccessible, or the snapshot name collides with an existing database object. This can also result from insufficient permissions on the data directory where the snapshot’s sparse file is being created, or from corrupted metadata in the source database that prevents proper name resolution. Additionally, running this operation on a database that is not in a state that supports snapshots (such as one involved in certain replication or mirroring configurations) can trigger this error.

Step-by-Step Resolution Guide

Step 1: Verify Source Database State and Name

  • Confirm the source database is online and not in RESTORING, SUSPECT, or EMERGENCY mode using SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';.
  • Ensure the snapshot name you are specifying does not already exist as a database name on the instance.
  • Check for invalid characters or reserved keywords in the snapshot name being passed in the CREATE DATABASE ... AS SNAPSHOT OF statement.

Step 2: Validate File System Permissions and Paths

  • Navigate to the directory where the snapshot sparse file will be created, typically alongside the source .mdf file (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).
  • Right-click the folder, select Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • Run the following command in an elevated PowerShell session to reset permissions if needed:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)F"

Step 3: Check for Snapshot Naming Conflicts in System Catalogs

  • Query sys.databases to check if a stale or orphaned snapshot entry is holding the name you are trying to reuse.
  • Run SELECT name, source_database_id FROM sys.databases WHERE source_database_id IS NOT NULL; to list all existing snapshots.
  • Drop any conflicting orphaned snapshot using DROP DATABASE [SnapshotName]; if it is no longer needed.

Step 4: Rebuild the Snapshot with an Explicit, Unique Name

  • Reissue the CREATE DATABASE command using a fully qualified and unique snapshot name, avoiding spaces or special characters.
  • Example syntax:
  CREATE DATABASE SalesDB_Snapshot_0530 ON
  ( NAME = SalesDB, FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\SalesDB_0530.ss' )
  AS SNAPSHOT OF SalesDB;
  • Ensure the NAME parameter matches the logical file name of the source database exactly (case-sensitive in some collations).

Alternative or Verification Steps

  • Verify the fix: After creation, run SELECT * FROM sys.databases WHERE name = 'SnapshotName'; to confirm the snapshot is listed and in ONLINE state.
  • Alternative solution: If the error persists, restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell to clear any cached metadata locks, then retry the snapshot creation command.

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

Troubleshooting Guide: DBCC CLONEDATABASE Error 12603

Why This Error Happens

Error 12603 occurs because DBCC CLONEDATABASE is explicitly restricted by SQL Server’s engine to user databases only, as system databases (master, model, msdb, tempdb) contain internal server-level metadata that cannot be safely duplicated through this command. The restriction is hardcoded into the command’s validation logic, not a permissions or configuration issue. Attempting to target a system database triggers an immediate validation failure before any cloning operation begins, regardless of the account’s privilege level.

Step-by-Step Resolution Guide

Step 1: Confirm the Target Database Type

  • Run SELECT name, database_id FROM sys.databases; to identify whether the target is a system database (database_id 1-4 typically indicates master, tempdb, model, msdb).
  • If the target is indeed a system database, understand that DBCC CLONEDATABASE cannot be used — proceed to an alternative method below.

Step 2: Use the Correct Command Syntax for User Databases

  • Verify you are targeting a user database with correct syntax:
  • DBCC CLONEDATABASE ('UserDB_Source', 'UserDB_Clone');
  • Ensure the source database is not master, model, msdb, or tempdb.
  • Confirm you have VIEW SERVER STATE and VIEW DATABASE STATE/CREATE DATABASE permissions on the instance.

Step 3: Script Out System Database Objects Manually (If System DB Data Is Needed)

  • Open SQL Server Management Studio (SSMS) on Windows Server 2025 or Windows 11.
  • Right-click the system database (e.g., msdb) → Tasks → Generate Scripts.
  • Select the specific objects (jobs, schemas, logins) you need to replicate rather than the entire database.
  • Execute the generated .sql script against the target instance manually.

Step 4: For Full System Database Migration, Use Native Backup/Restore

  • Open a new query window in SSMS and run:
  • BACKUP DATABASE msdb TO DISK = 'C:\Backup\msdb_backup.bak';
  • On the target server, restore using:
  • RESTORE DATABASE msdb FROM DISK = 'C:\Backup\msdb_backup.bak' WITH REPLACE;
  • Note: Restoring over master requires starting SQL Server in single-user mode (-m startup parameter) via SQL Server Configuration Manager.

Step 5: Validate SQL Server Service Account Permissions

  • Open Services.msc on Windows Server 2025/Windows 11.
  • Confirm the SQL Server service account has read/write access to the backup directory path used above.
  • Restart the SQL Server (MSSQLSERVER) service if permissions were modified.

Alternative or Verification Steps

  • Run SELECT * FROM sys.dm_exec_requests WHERE command = 'DBCC'; to confirm no cloning operation is hung or erroring silently.
  • If system-level replication is the actual goal, consider using Log Shipping, Always On Availability Groups, or a full Database Mirroring setup instead of attempting to clone system databases directly.

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

Why This Error Happens

Error 12604 typically occurs when SQL Server 2025 marks a database as Suspect or Offline due to corruption in the transaction log, an unexpected shutdown during an active transaction, or storage-level I/O failures. This can also happen if the underlying MDF/LDF files were moved, renamed, or became inaccessible due to permission changes on Windows Server 2025. In some cases, insufficient disk space during a checkpoint operation triggers this state to prevent further data corruption.

Step-by-Step Resolution Guide

Step 1: Verify the Current Database State

  • Open SQL Server Management Studio (SSMS) and run the following query to check the database status:
  SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the state_desc returns SUSPECT or OFFLINE, proceed to the next step.
  • Check the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for related I/O or corruption messages.

Step 2: Attempt to Bring the Database Back Online

  • Try setting the database back online directly:
  ALTER DATABASE YourDatabaseName SET ONLINE;
  • If this fails, place the database into EMERGENCY mode to allow read-only access for data recovery:
  ALTER DATABASE YourDatabaseName SET EMERGENCY;
  • Run DBCC CHECKDB to assess the extent of corruption:
  DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS;

Step 3: Repair the Database (If Checkdb Finds Errors)

  • Set the database to SINGLE_USER mode to perform repairs:
  ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  • Run the repair command (note: this may result in data loss for corrupted pages):
  DBCC CHECKDB (YourDatabaseName, REPAIR_ALLOW_DATA_LOSS);
  • Revert the database back to multi-user mode once repairs are complete:
  ALTER DATABASE YourDatabaseName SET MULTI_USER;

Step 4: Validate File System Permissions

  • Navigate to the data file directory (e.g., D:\SQLData\) and ensure the SQL Server Service Account has Full Control permissions on the .mdf and .ldf files.
  • In Windows Server 2025, check File Properties > Security tab to confirm NT SERVICE\MSSQLSERVER is listed with the correct access rights.

Alternative or Verification Steps

  • Verification: Re-run SELECT name, state_desc FROM sys.databases; to confirm the status now reads ONLINE. Attempt a test query against a critical table to ensure data integrity.
  • Alternative: If REPAIR_ALLOW_DATA_LOSS does not resolve the issue or data loss is unacceptable, restore the database from the most recent clean backup using RESTORE DATABASE YourDatabaseName FROM DISK = 'BackupPath' WITH RECOVERY;.

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

Troubleshooting Guide: Error 12601 — DBCC CLONEDATABASE Not Allowed Within a Transaction

Why This Error Happens

This error occurs because DBCC CLONEDATABASE is designed to run as an atomic, standalone operation and cannot be executed while an explicit transaction is open on the connection. SQL Server 2025 enforces this restriction because the command performs internal schema-only snapshot operations that require full control over the session state. If a prior BEGIN TRANSACTION statement was left uncommitted, was wrapped around the command inadvertently, or if the client driver/ORM auto-wraps commands in a transaction, SQL Server will reject the clone operation with Error 12601.

Step-by-Step Resolution Guide

Step 1: Check for Open or Implicit Transactions

  • Run SELECT @@TRANCOUNT; in the same session before executing DBCC CLONEDATABASE to confirm the transaction count is 0.
  • If the count is greater than 0, issue COMMIT TRANSACTION; or ROLLBACK TRANSACTION; as many times as needed to clear it.
  • Verify SET IMPLICIT_TRANSACTIONS OFF; is set for the session, since some client tools and ORMs (e.g., certain .NET or JDBC configurations) enable implicit transactions by default.

Step 2: Isolate the Command in Its Own Session

  • Open a brand-new query window in SQL Server Management Studio (SSMS) or Azure Data Studio dedicated solely to the clone operation.
  • Do not place DBCC CLONEDATABASE inside any BEGIN TRAN ... COMMIT block, stored procedure called within a transaction, or application-level transaction scope (such as TransactionScope in C#).
  • Example of correct syntax:
  DBCC CLONEDATABASE ('SourceDB', 'ClonedDB');
  GO

Step 3: Review Application and Connection Pooling Settings

  • On Windows Server 2025 / Windows 11, check connection strings in web.config, appsettings.json, or ODBC/DSN settings under Control Panel > Administrative Tools > ODBC Data Sources for Enlist=true or ambient transaction settings that auto-enlist connections into distributed transactions (MSDTC).
  • Disable MSDTC enlistment for the specific connection used to run the DBCC command, or explicitly open a new, non-enlisted connection for this operation.
  • If using PowerShell or sqlcmd, ensure no surrounding transaction script block wraps the DBCC call.

Step 4: Restart the Session and Re-run the Command

  • Close and reopen the query window/connection entirely to guarantee a clean session state with @@TRANCOUNT = 0.
  • Re-execute DBCC CLONEDATABASE ('SourceDB', 'ClonedDB'); as the only statement in the batch.
  • Confirm no triggers or session-level settings (like SET XACT_ABORT ON combined with an open transaction) are interfering.

Alternative or Verification Steps

  • Verify the fix by checking SELECT @@TRANCOUNT; returns 0 immediately before running the command, then confirm the cloned database appears successfully under Databases in SSMS Object Explorer with schema-only objects (no data).
  • If the error persists despite a clean transaction state, use sp_who2 or sys.dm_exec_sessions to confirm no other process or linked server call is implicitly enlisting your session into a distributed transaction via MSDTC.

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

Troubleshooting Guide: Error 12602 — DBCC CLONEDATABASE Fails Through MARS Connection

Why This Error Happens

Error 12602 occurs because DBCC CLONEDATABASE requires a dedicated, single-result-set connection to execute its internal consistency checks and metadata copy operations correctly. Multiple Active Result Sets (MARS) alters the way batches and transactions are interleaved on a single connection, which conflicts with the internal session state that DBCC CLONEDATABASE depends on. SQL Server 2025 explicitly blocks this command when it detects the connection was opened with MultipleActiveResultSets=True, raising Error 12602 instead of allowing undefined behavior.

Step-by-Step Resolution Guide

Step 1: Identify the Connection String Causing the Issue

  • Check the client application or tool (SSMS, custom app, ETL job) that issued the DBCC CLONEDATABASE command.
  • Look for MultipleActiveResultSets=True or MARS=True in the connection string or ODBC/OLE DB DSN configuration.
  • In SSMS, this is normally not enabled by default, so this step is more critical for custom .NET, Python (pyodbc), or PowerShell scripts.

Step 2: Create or Use a Non-MARS Connection

  • Open a new connection explicitly without MARS enabled by setting MultipleActiveResultSets=False (or simply omitting the parameter, since it defaults to false).
  • Example for a .NET connection string:
  • Server=YourServer;Database=master;Integrated Security=True;MultipleActiveResultSets=False;
  • For SSMS users, open a fresh Query Window (Ctrl+N) rather than reusing a tab that may share a MARS-enabled session pool.

Step 3: Re-run DBCC CLONEDATABASE from the Clean Session

  • Execute the command from the newly opened non-MARS connection:
  • DBCC CLONEDATABASE ('SourceDB', 'ClonedDB');
  • Ensure you are connected to the master database context before running the command.
  • Confirm the login has CREATE DATABASE permission and is either sysadmin or has been granted the ALTER ANY DATABASE and VIEW SERVER STATE permissions required for cloning in SQL Server 2025.

Step 4: Update Application-Level Connection Pooling Settings

  • If the error originates from an application server (IIS, Azure App Service, or a Windows Service on Windows Server 2025), locate the web.config, app.config, or environment variable storing the SQL connection string.
  • Remove or set MultipleActiveResultSets=false permanently for any connection pool used to run maintenance/DBCC commands.
  • Restart the application pool or service so the updated connection string takes effect.

Step 5: Validate SQL Server Configuration Manager Settings (Optional)

  • Open SQL Server Configuration Manager on Windows Server 2025.
  • Navigate to SQL Server Network Configuration > Protocols for [Your Instance].
  • Confirm no legacy MARS-forcing client aliases are configured under SQL Native Client Configuration > Client Protocols.

Alternative or Verification Steps

  • Verify the fix by running DBCC CLONEDATABASE again from a known clean, non-MARS session (e.g., sqlcmd -S YourServer -E -Q "DBCC CLONEDATABASE ('SourceDB','ClonedDB')") and confirm it completes without Error 12602.
  • If MARS cannot be disabled application-wide due to other dependencies, isolate database maintenance tasks into a separate connection pool or use a dedicated SQL Agent Job/PowerShell script with Invoke-Sqlcmd, which does not use MARS by default.

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

Troubleshooting Guide: DBCC CLONEDATABASE Error 12600 on SQL Server 2025

Why This Error Happens

Error 12600 occurs because DBCC CLONEDATABASE is disabled by default on SQL Server instances and requires an explicit trace flag or server configuration to be enabled before execution. This is a deliberate safety mechanism, since cloning a database (which copies schema and statistics without data) can be misused to bypass licensing restrictions or expose metadata unintentionally. Additionally, the login executing the command may lack the required ALTER ANY DATABASE or VIEW SERVER STATE permissions, or the target instance may be running under a service account with restricted sysadmin privileges.

Step-by-Step Resolution Guide

Step 1: Enable Trace Flag 3604 and 2588 for the Session

  • Open a new query window in SQL Server Management Studio (SSMS) connected via sysadmin credentials.
  • Run the following commands before executing the clone operation:
  DBCC TRACEON (3604, 2588, -1);
  • Note that Trace Flag 2588 is the specific flag required to unlock DBCC CLONEDATABASE functionality in SQL Server 2025.

Step 2: Verify and Elevate Login Permissions

  • Confirm the executing login is a member of the sysadmin fixed server role, or has been explicitly granted ALTER ANY DATABASE and VIEW SERVER STATE permissions.
  • Use this query to check current permissions:
  SELECT IS_SRVROLEMEMBER('sysadmin');
  • If the result returns 0, escalate the account via SQL Server Configuration Manager or ask a Database Administrator to grant temporary sysadmin rights.

Step 3: Check Source Database State and Compatibility

  • Ensure the source database is not in SINGLE_USER mode or marked as SUSPECT, as this will block the clone operation even with trace flags enabled.
  • Run sp_helpdb 'YourSourceDatabaseName' to verify the status column shows ONLINE.
  • Confirm the database compatibility level is set to 100 or higher (ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 160; for SQL Server 2025 alignment).

Step 4: Execute the DBCC CLONEDATABASE Command

  • With trace flags active and permissions confirmed, run the actual clone syntax:
  DBCC CLONEDATABASE ('SourceDB', 'ClonedDB');
  • Monitor the SQL Server Error Log (located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG on Windows Server 2025) for any secondary blocking messages during execution.

Alternative or Verification Steps

  • Verify the Fix: After cloning, query sys.databases to confirm the new ClonedDB appears with a status of ONLINE, and check that sys.stats objects were successfully copied over.
  • Alternative Method: If trace flags fail to resolve the issue due to Group Policy restrictions on Windows Server 2025, use the -T2588 startup parameter in SQL Server Configuration Manager under SQL Server Services > Properties > Startup Parameters to persist the flag across service restarts.

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

Why This Error Happens

Error 12525 occurs when SQL Server’s internal catalog cache becomes desynchronized from the actual physical storage metadata on disk, often due to an abrupt termination during a schema change, DDL operation, or online index rebuild. This can also result from corrupted system catalog pages, filesystem-level corruption on the data volume, or a failed in-place upgrade that left partition/table metadata pointers inconsistent. In clustered or Always On Availability Group configurations, replication lag combined with a failover during a metadata operation can also trigger this inconsistency.

Step-by-Step Resolution Guide

Step 1: Verify the Scope of the Corruption

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to identify whether the corruption is isolated to one table or spans multiple objects.
  • Check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for accompanying messages referencing object IDs or page numbers.
  • Note the specific table name and object_id referenced in the error, as this determines whether you need table-level or database-level repair.

Step 2: Clear the Plan Cache and Metadata Cache

  • Execute DBCC FREEPROCCACHE; followed by DBCC FREESYSTEMCACHE('ALL'); to force SQL Server to rebuild its internal metadata references.
  • Restart the SQL Server service via Services.msc or PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force.
  • Retry the original operation that triggered the error immediately after the restart.

Step 3: Rebuild Indexes and Update Statistics

  • Run ALTER INDEX ALL ON dbo.YourTableName REBUILD WITH (ONLINE = OFF); to force SQL Server to regenerate physical page pointers for the table.
  • Follow with UPDATE STATISTICS dbo.YourTableName WITH FULLSCAN; to ensure the query optimizer’s metadata aligns with the rebuilt structure.
  • If the table resides in a partitioned scheme, rebuild each partition individually to isolate which partition held the stale metadata.

Step 4: Restore from a Known-Good Backup (If Corruption Persists)

  • If DBCC CHECKDB reports allocation errors tied to this table, perform a page-level restore using RESTORE DATABASE YourDatabaseName PAGE = 'FileID:PageID' FROM DISK = 'BackupPath.bak';.
  • Alternatively, restore the full database to a secondary instance on Windows Server 2025 and use sp_help to export clean metadata, then re-import the table via BCP or SELECT INTO.

Step 5: Validate Underlying Storage Health

  • Check the Windows Event Viewer (Application and System logs) for Disk or NTFS warnings on the volume hosting the .mdf/.ndf files.
  • Run chkdsk D: /f /r (replace D: with your data drive) during a maintenance window to rule out filesystem-level sector corruption.

Alternative or Verification Steps

  • Confirm resolution by re-running DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS; and verifying zero allocation or consistency errors are returned.
  • If the error persists after all steps, export the problematic table’s data to a new table (SELECT * INTO dbo.NewTable FROM dbo.OldTable), drop and recreate the original table, then rename the new table to match—this bypasses corrupted metadata entirely without requiring a full database restore.

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

Troubleshooting Guide: SQL Server Error 12526 – Internal Error While Cloning Warehouse

Why This Error Happens

Error 12526 typically occurs when SQL Server 2025’s warehouse cloning engine encounters a mismatch between metadata and the underlying storage snapshot, often due to an in-progress transaction on the source warehouse at the time of cloning. This can also stem from insufficient permissions on the service account accessing the storage container, or from a corrupted metadata cache left behind by an interrupted previous clone operation. Additionally, conflicts can arise if the target warehouse name already exists in a soft-deleted state within the same resource pool.

Step-by-Step Resolution Guide

Step 1: Verify Source Warehouse State and Halt Active Transactions

  • Open SQL Server Management Studio (SSMS) and connect to the instance hosting the source warehouse.
  • Run DBCC OPENTRAN against the source warehouse to check for uncommitted transactions.
  • If active transactions exist, commit or roll them back using KILL <session_id> before retrying the clone.
  • Ensure no scheduled maintenance plans or backup jobs are running concurrently on the source warehouse.

Step 2: Check and Repair Service Account Permissions

  • Navigate to Services.msc on Windows Server 2025 and confirm the SQL Server service account has read/write access to the warehouse storage path (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\Warehouses\).
  • Grant the account db_owner role on both source and target databases via SSMS under Security > Logins.
  • If using Azure-integrated storage, validate the Managed Identity has Storage Blob Data Contributor rights on the associated storage account.

Step 3: Clear Corrupted Metadata Cache

  • Stop the SQL Server service using net stop MSSQLSERVER in an elevated PowerShell/Command Prompt window.
  • Delete temporary clone metadata files located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\LOG\CloneCache\.
  • Restart the service with net start MSSQLSERVER and clear the plan cache using DBCC FREEPROCCACHE.

Step 4: Remove Soft-Deleted Target Warehouse Conflicts

  • Query sys.databases to check if a warehouse with the same target name exists in a soft-deleted or suspect state.
  • Run DROP DATABASE [TargetWarehouseName] if a stale instance is found, ensuring you have confirmed it is not needed.
  • Re-attempt the clone operation using the T-SQL command CREATE DATABASE [NewWarehouse] AS CLONE OF [SourceWarehouse].

Step 5: Reattempt Clone with Elevated Logging

  • Enable trace flag 3614 to capture verbose clone diagnostics: DBCC TRACEON (3614, -1).
  • Re-run the clone operation and monitor the SQL Server Error Log for detailed failure context before it fails again.

Alternative or Verification Steps

  • Verify the fix: Run SELECT name, state_desc FROM sys.databases WHERE name = 'NewWarehouse' to confirm the cloned warehouse shows an ONLINE state, then validate row counts against the source using a quick COUNT(*) comparison on key tables.
  • Alternative solution: If cloning continues to fail, perform a manual export/import using BACKUP DATABASE and RESTORE DATABASE WITH MOVE as a workaround instead of the native clone feature.

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

Troubleshooting Guide: Error 12524 — “The specified point-in-time is invalid”

Why This Error Happens

This error occurs when SQL Server 2025’s point-in-time restore engine cannot locate physical metadata snapshots corresponding to the requested timestamp, typically because the transaction log chain has gaps or the log backups covering that window were truncated, deleted, or never captured. It can also happen when the accelerated database recovery (ADR) persistent version store (PVS) has already cleaned up historical row versions older than the requested recovery point. Additionally, specifying a timestamp that falls before the earliest available full backup or outside the retention window configured for the database will trigger this error.

Step-by-Step Resolution Guide

Step 1: Verify the Backup and Log Chain Timeline

  • Run RESTORE HEADERONLY FROM DISK = 'path_to_backup.bak' to confirm the BackupStartDate and BackupFinishDate values bracket your target timestamp.
  • Check msdb.dbo.backupset for continuous LSN chains using SELECT backup_start_date, backup_finish_date, type FROM msdb.dbo.backupset WHERE database_name = 'YourDB' ORDER BY backup_start_date;.
  • Confirm no log backups are missing between the last full/differential backup and your desired point-in-time.

Step 2: Check Accelerated Database Recovery (ADR) Retention Settings

  • Query current PVS retention using SELECT name, is_accelerated_database_recovery_on FROM sys.databases WHERE name = 'YourDB';.
  • Inspect SELECT * FROM sys.dm_tran_persistent_version_store_stats WHERE database_id = DB_ID('YourDB'); to see the oldest available version timestamp.
  • If the requested time predates the PVS retention window, increase retention temporarily via ALTER DATABASE YourDB SET PERSISTENT_VERSION_STORE_FILEGROUP = [FILEGROUP_NAME]; and adjust cleanup frequency before attempting the restore again.

Step 3: Validate File Paths and Recovery Settings in SQL Server Configuration Manager

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm the SQL Server service account has read/write access to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\.
  • Ensure no antivirus or Windows Defender exclusion is blocking access to .trn log backup files during the restore scan.
  • Re-run the restore command using an adjusted, earlier timestamp that falls strictly within the validated backup window from Step 1.

Step 4: Rebuild the Restore Sequence Manually

  • Use RESTORE DATABASE YourDB FROM DISK = 'Full.bak' WITH NORECOVERY; followed by sequential RESTORE LOG statements up to (but not exceeding) the last confirmed valid LSN.
  • Finish with RESTORE DATABASE YourDB WITH RECOVERY, STOPAT = 'YYYY-MM-DD HH:MM:SS'; using a timestamp confirmed valid in Step 1.

Alternative or Verification Steps

  • After completing the restore, run DBCC CHECKDB('YourDB') WITH NO_INFOMSGS; to confirm database consistency and that the point-in-time recovery completed cleanly.
  • If Error 12524 persists, fall back to restoring to the nearest valid full backup timestamp (identified in Step 1) rather than the original target time, then manually replay transactions from application-level logs if finer granularity is required.

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

Troubleshooting Guide: Error 12522 – Point-in-Time Outside Data Retention Period

Why This Error Happens

This error occurs when using System-Versioned Temporal Tables in SQL Server 2025, and a query attempts to retrieve historical data using a FOR SYSTEM_TIME clause with a timestamp that falls outside the configured retention window. The database engine enforces retention policies to automatically clean up aging historical records via the background cleanup task, and once that data has been purged, it is permanently unrecoverable through standard temporal queries. This typically happens when retention policies were recently shortened, when the cleanup job ran more aggressively than expected, or when an application or reporting tool is requesting data older than the business-defined retention window.

Step-by-Step Resolution Guide

Step 1: Verify the Current Retention Policy Settings

  • Open SQL Server Management Studio (SSMS) and connect to the target instance.
  • Run the following query to check retention settings on the affected table:
  SELECT name, temporal_type_desc, history_retention_period, history_retention_period_unit_desc
  FROM sys.tables
  WHERE name = 'YourTableName';
  • Confirm whether the retention period matches what the application expects (e.g., 90 days vs. 30 days).

Step 2: Adjust the Query or Timestamp Being Requested

  • Review the application code or report generator issuing the FOR SYSTEM_TIME AS OF or BETWEEN clause.
  • Ensure the requested datetime falls within the valid window:
  SELECT * FROM dbo.YourTable
  FOR SYSTEM_TIME AS OF '2025-01-15T00:00:00'
  • If the business requirement demands older data, this indicates a policy mismatch rather than a bug—proceed to Step 3.

Step 3: Modify the Retention Period (If Business Requirements Changed)

  • Alter the table definition to extend the retention window:
  ALTER TABLE dbo.YourTable
  SET (SYSTEM_VERSIONING = ON (HISTORY_RETENTION_PERIOD = 180 DAYS));
  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log on Windows Server 2025 to review the Temporal History Retention cleanup job logs and confirm when the last purge cycle executed.
  • Restart the SQL Server Agent service if the policy change does not take effect immediately:
  Restart-Service -Name "SQLSERVERAGENT"

Step 4: Restore From Backup If Data Is Required Beyond Retention

  • If the needed historical data has already been purged and cannot be queried, restore a full or differential backup to a secondary database using SSMS or the RESTORE DATABASE T-SQL command.
  • Query the restored copy directly for the specific time range needed, then export results to the production environment if required.

Alternative or Verification Steps

  • Re-run the original temporal query with a timestamp within the newly extended retention window to confirm Error 12522 no longer appears.
  • If data is frequently needed beyond the retention period, consider disabling automatic history cleanup (HISTORY_RETENTION_PERIOD = INFINITE) and instead manage archival manually via a custom ETL job into a separate archive table.

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

Troubleshooting Guide: Error 12523 – Invalid Point-in-Time Specification in SQL Server 2025

Why This Error Happens

Error 12523 occurs when a point-in-time restore, temporal query, or Accelerated Database Recovery (ADR) operation references a timestamp that falls after the most recent valid snapshot or transaction log backup in SQL Server 2025. This typically happens due to clock drift between the client and server, an outdated or truncated transaction log chain, or a user manually specifying a future or out-of-range timestamp. It can also surface when the persisted version store (PVS) used by ADR has been cleaned up before the requested time window, invalidating the reference point.

Step-by-Step Resolution Guide

Step 1: Verify System Time Synchronization

  • Confirm that the SQL Server host (Windows Server 2025) and the client machine issuing the query have synchronized clocks via Windows Time Service (W32Time).
  • Run w32tm /query /status in an elevated PowerShell/Command Prompt to check sync status.
  • Correct drift with w32tm /resync /force if the server is out of sync with the domain controller or NTP source.

Step 2: Validate the Timestamp Against Available Backup/Snapshot History

  • Query msdb.dbo.backupset to confirm the exact range of valid backup timestamps:
  SELECT database_name, backup_start_date, backup_finish_date
  FROM msdb.dbo.backupset
  ORDER BY backup_finish_date DESC;
  • Ensure the requested STOPAT time in your RESTORE DATABASE ... WITH STOPAT command falls strictly before the latest backup_finish_date, not after.
  • For ADR-based temporal queries, confirm the PVS retention window using sys.dm_tran_persistent_version_store_stats.

Step 3: Check and Repair the Transaction Log Chain

  • Verify there are no gaps in the log backup chain using RESTORE HEADERONLY against each .trn file.
  • If a break exists (e.g., due to a log truncation or a full backup taken outside the chain), take a fresh full backup to re-establish a valid recovery baseline.
  • Re-attempt the point-in-time restore using a timestamp within the newly established chain.

Step 4: Adjust the Requested Timestamp or Recovery Model

  • If using a GUI tool (SSMS 21 or Azure Data Studio), re-enter the timestamp manually in YYYY-MM-DD HH:MI:SS.mmm format rather than relying on a picker that may round incorrectly.
  • Ensure the database is in FULL or BULK_LOGGED recovery model — SIMPLE recovery model does not support point-in-time restores.
  • Re-run the restore command with the corrected, validated timestamp.

Alternative or Verification Steps

  • After applying the fix, re-run the RESTORE DATABASE or temporal SELECT ... FOR SYSTEM_TIME AS OF query with the corrected timestamp and confirm it completes without Error 12523.
  • If the issue persists, restore to the most recent valid backup finish time first (using RESTORE ... WITH RECOVERY), then manually validate downstream timestamps against sys.databases.replica_update_sequence_number or ADR diagnostic DMVs before retrying finer-grained point-in-time operations.

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

Troubleshooting Guide: SQL Server Error 12520 — Non-Versionable Data Source in Time Travel Query

Why This Error Happens

Error 12520 occurs when a temporal query (FOR SYSTEM_TIME AS OF, BETWEEN, FROM...TO, etc.) is executed against a table or view that does not have system-versioning enabled. This typically happens when the target object is a standard table, a non-temporal view, or an external data source that lacks the PERIOD FOR SYSTEM_TIME columns and history table binding required for time travel queries. It can also occur if the temporal table’s history table link was broken during a migration, restore, or schema change.

Step-by-Step Resolution Guide

Step 1: Identify the Non-Versionable Object

  • Run sys.tables query: SELECT name, temporal_type, temporal_type_desc FROM sys.tables WHERE name = 'YourTableName';
  • Confirm temporal_type_desc returns NON_TEMPORAL_TABLE instead of SYSTEM_VERSIONED_TEMPORAL_TABLE.
  • Check if the query is targeting a view, synonym, or linked server object instead of the base temporal table.

Step 2: Enable System-Versioning on the Table

  • Add required period columns if missing:
    ALTER TABLE dbo.YourTableName ADD ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL DEFAULT SYSUTCDATETIME(), ValidTo DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'), PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
  • Enable versioning and bind a history table:
    ALTER TABLE dbo.YourTableName SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.YourTableName_History));
  • Verify the history table was created in SQL Server Management Studio (SSMS) under Databases > YourDB > Tables > System-Versioned.

Step 3: Repair Broken Temporal Links (If Previously Versioned)

  • If the table was previously temporal but lost its link (common after a restore or DROP/CREATE cycle), set versioning to OFF first:
    ALTER TABLE dbo.YourTableName SET (SYSTEM_VERSIONING = OFF);
  • Re-establish the link to the existing history table:
    ALTER TABLE dbo.YourTableName SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.YourTableName_History, DATA_CONSISTENCY_CHECK = ON));
  • On Windows Server 2025, confirm the SQL Server service account has read/write NTFS permissions on the data file path (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) in case file-level corruption is blocking the history table write.

Step 4: Redirect the Query to the Correct Object

  • If the object is intentionally non-temporal (e.g., a reporting view), rewrite the T-SQL query to remove the FOR SYSTEM_TIME clause.
  • Alternatively, point the query to the correctly versioned base table instead of the view/synonym causing the conflict.

Alternative or Verification Steps

  • Verify the fix by re-running the original time travel query (e.g., SELECT * FROM dbo.YourTableName FOR SYSTEM_TIME AS OF '2025-01-01';) and confirming it returns historical rows without Error 12520.
  • If the error persists, use sp_helptext or query sys.periods to confirm the PERIOD FOR SYSTEM_TIME definition exists and matches the columns referenced in the query.

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

Troubleshooting Guide: Error 12521 — FOR TIMESTAMP AS OF Query Hint Restriction

Why This Error Happens

This error occurs because the FOR TIMESTAMP AS OF temporal query hint is designed exclusively for point-in-time historical data retrieval and cannot be combined with Data Manipulation Language (DML) operations such as INSERT, UPDATE, or DELETE. SQL Server 2025 enforces this restriction because temporal queries reconstruct data from both the current and history tables, making write operations logically inconsistent against a reconstructed, non-deterministic snapshot. This typically happens when a developer mistakenly embeds the temporal clause inside a stored procedure or ORM-generated statement that performs an underlying write operation rather than a pure SELECT.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Capture the exact T-SQL statement from the application log or SQL Server error log that triggered Error 12521.
  • Use SQL Server Profiler or Extended Events (xEvents) filtered on error_reported with Error Code 12521 to pinpoint the exact query text in real time.
  • Check if the statement is wrapped inside a stored procedure using sp_helptext '[SchemaName].[ProcedureName]' in SSMS.

Step 2: Separate Read and Write Logic

  • Refactor the query so the FOR TIMESTAMP AS OF clause exists only within a standalone SELECT statement.
  • If you need to use the historical data to update current records, first SELECT the data into a temporary table or table variable, then perform the UPDATE/INSERT/DELETE as a separate transaction against the standard (non-temporal) table name.
  • Example corrected syntax:
  -- Step A: Read historical data
  SELECT * INTO #TempHistory 
  FROM dbo.YourTable 
  FOR TIMESTAMP AS OF '2025-01-01T00:00:00';

  -- Step B: Perform write operation separately
  UPDATE dbo.YourTable
  SET Column1 = t.Column1
  FROM #TempHistory t
  WHERE dbo.YourTable.ID = t.ID;

Step 3: Audit Application and ORM Configuration

  • If using Entity Framework Core, Dapper, or another ORM, check the connection string or query builder configuration for AsOf() or temporal extension methods.
  • Ensure these temporal methods are only chained to read queries (.ToListAsync(), .FirstOrDefault()) and never combined with .SaveChanges() or ExecuteUpdate() calls in the same context scope.
  • Look specifically in appsettings.json or the Data Access Layer (DAL) classes where temporal table queries are constructed dynamically.

Step 4: Validate Server and Compatibility Level Settings

  • Navigate to SQL Server Management Studio (SSMS) and verify the database compatibility level supports system-versioned temporal tables correctly.
  • Run the following command to check the compatibility level:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure it is set to 170 or higher (required for SQL Server 2025 temporal feature enhancements) using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verify the fix: Re-run the isolated SELECT ... FOR TIMESTAMP AS OF query independently in SSMS to confirm it returns historical data without triggering Error 12521, then run the write operation separately to confirm it executes successfully.
  • Alternative approach: If the application architecture makes separation difficult, consider using a MERGE statement that sources data from a pre-fetched temporal snapshot (via a CTE defined before the merge) rather than inline within the USING clause referencing FOR TIMESTAMP AS OF directly.

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

Troubleshooting Guide: Error 12519 – “FOR TIMESTAMP AS OF” Query Hint Specified Multiple Times

Why This Error Happens

This error occurs because the T-SQL parser in SQL Server 2025 only permits a single FOR TIMESTAMP AS OF temporal clause per statement, and the query being executed contains duplicate references—often introduced by nested views, joined temporal tables with inherited clauses, or ORM-generated SQL that appends the hint redundantly. It can also surface when a stored procedure dynamically concatenates temporal query logic without checking for existing clauses in the base query string. Essentially, the engine detects a conflicting or repeated instruction on how to resolve the historical data snapshot and refuses to execute ambiguous logic.

Step-by-Step Resolution Guide

Step 1: Isolate the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Run the query in isolation using SET SHOWPLAN_TEXT ON to identify exactly which sub-select or joined table is injecting the duplicate clause.
  • Check if the error originates from a View definition by running sp_helptext [ViewName].

Step 2: Audit Nested Views and CTEs

  • Search the query body for multiple instances of the string FOR SYSTEM_TIME AS OF or FOR TIMESTAMP AS OF.
  • If using Common Table Expressions (CTEs), ensure the temporal hint is applied only at the outermost SELECT statement and removed from the inner CTE logic.
  • Specifically look in the path C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Views\ if views are stored as linked server objects or exported scripts for reference.

Step 3: Correct Dynamic SQL Generation

  • If the query is generated by an application or middleware, inspect the source code for string concatenation logic that appends temporal clauses.
  • Modify the application logic to use a regex check or a boolean flag (hasTemporalClauseApplied) to prevent the hint from being appended twice during query building.
  • Rebuild the query string ensuring only one AS OF '2025-01-01T00:00:00' declaration exists in the final executable string.

Step 4: Apply Server Configuration Patch (If Applicable)

  • Ensure your Windows Server 2025 instance has the latest Cumulative Update (CU) for SQL Server 2025 installed, as early builds had a parsing bug with linked temporal tables.
  • Navigate to Control Panel > Programs > Programs and Features to verify the current SQL Server build version matches the latest release from the Microsoft Update Catalog.
  • Restart the SQL Server service via services.msc after patching to ensure the new query optimizer engine is loaded.

Alternative or Verification Steps

  • Verification: Re-run the specific query via SSMS; if the execution plan generates successfully without a syntax error, the duplicate hint has been successfully removed.
  • Alternative: If the error persists in a complex JOIN scenario, bypass the issue by selecting data into a temporary table using the AS OF clause first, then perform the JOIN logic on the static temporary table without further temporal hints.

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

Troubleshooting Guide: Error 12517 – Point-in-Time Outside Data Retention Period

Why This Error Happens

This error occurs when a query against a System-Versioned Temporal Table attempts to retrieve historical data for a point in time that falls outside the configured HISTORY_RETENTION_PERIOD for that table. SQL Server 2025 actively enforces retention policies via the background cleanup task (temporal history retention cleanup job), which automatically purges historical rows older than the defined threshold. Consequently, if the requested FOR SYSTEM_TIME AS OF timestamp predates the oldest surviving record in the history table, the engine rejects the query rather than returning incomplete or misleading results.

Step-by-Step Resolution Guide

Step 1: Verify the Current Retention Policy Configuration

  • Run the following query to inspect the retention settings on the affected table:
  • SELECT name, temporal_type_desc, history_retention_period, history_retention_period_unit_desc FROM sys.tables WHERE name = 'YourTableName';
  • Confirm whether the retention period (e.g., 90 days, 1 year) is shorter than the point-in-time value used in your SYSTEM_TIME AS OF clause.

Step 2: Adjust the Retention Period If Business Requirements Demand Longer History

  • Use ALTER TABLE to extend the retention window if older data is still required:
  • ALTER TABLE YourTableName SET (SYSTEM_VERSIONING = ON (HISTORY_RETENTION_PERIOD = 5 YEARS));
  • Ensure the SQL Server Agent service account has sufficient permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data since retention changes trigger metadata updates that require write access to the data files.
  • Restart the SQL Server Agent service via services.msc on Windows Server 2025 to ensure the cleanup job picks up the new policy immediately.

Step 3: Check the Temporal History Retention Cleanup Job Logs

  • Open SQL Server Management Studio (SSMS) and navigate to SQL Server Agent > Jobs > “Temporal History Cleanup”.
  • Review the job history to confirm whether old rows were already purged before the retention period was extended (if so, the data is unrecoverable via live queries).
  • If rows were purged, you will need to restore the data from a backup rather than querying the live temporal table.

Step 4: Restore From Backup If Data Was Already Purged

  • Locate the most recent .bak file containing the required historical range, typically stored in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup.
  • Restore the backup to a secondary database using RESTORE DATABASE YourDB_Recovery FROM DISK = 'C:\Backup\YourDB.bak' WITH NORECOVERY;
  • Query the restored copy directly for the historical point-in-time data needed.

Alternative or Verification Steps

  • Re-run the original SELECT * FROM YourTableName FOR SYSTEM_TIME AS OF '2024-01-01' query after adjusting the retention period to confirm Error 12517 no longer appears.
  • If immediate access to purged data is required and no backup exists, check if Azure SQL Database long-term retention (LTR) or a linked archival table was configured as a secondary safeguard, as native temporal history cannot be recovered once hard-deleted by the cleanup job.

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

Why This Error Happens

Error 12518 occurs when querying a system-versioned temporal table using the FOR SYSTEM_TIME clause with a timestamp value that is later than or equal to the start time of the current transaction. SQL Server 2025 enforces strict temporal consistency, meaning any point-in-time query must reference a moment strictly before @@TRAN_START_TIME or the equivalent transaction begin marker to prevent reading uncommitted or “future” data relative to the transaction snapshot. This typically happens due to client-server clock drift, incorrect UTC conversions in application code, or a hardcoded timestamp that was generated after the transaction was initiated.

Step-by-Step Resolution Guide

Step 1: Verify System Clock Synchronization

  • Check for time drift between the application server and the SQL Server 2025 instance, as mismatched clocks are the most common cause.
  • On Windows Server 2025, open PowerShell as Administrator and run w32tm /query /status to confirm the time source is accurate.
  • Force a resync if drift is detected using w32tm /resync /force.

Step 2: Audit the Query’s Point-in-Time Value

  • Review the T-SQL statement using FOR SYSTEM_TIME AS OF and confirm the datetime variable passed is not using GETDATE() or SYSDATETIME() captured after the transaction began.
  • Example of a safe pattern:
BEGIN TRANSACTION;
DECLARE @PointInTime DATETIME2 = DATEADD(SECOND, -5, SYSUTCDATETIME());
SELECT * FROM dbo.YourTemporalTable
FOR SYSTEM_TIME AS OF @PointInTime;
COMMIT TRANSACTION;
  • Ensure the application layer is not passing local server time when the database column is stored in UTC.

Step 3: Inspect Transaction Isolation Level and Scope

  • Run DBCC USEROPTIONS; within the same session to confirm the isolation level isn’t causing an unexpected transaction start time offset.
  • If the query runs inside a larger explicit transaction block (e.g., nested in an ORM like Entity Framework Core targeting .NET 9), verify the transaction wasn’t opened significantly earlier than the point-in-time value being passed.
  • Isolate the query outside of any ambient transaction scope to test if the error persists in autocommit mode.

Step 4: Rebuild the Temporal History Table Statistics

  • Corrupted or stale statistics on the history table can sometimes cause the query optimizer to miscalculate valid time ranges.
  • Run the following to refresh statistics on both the current and history tables:
UPDATE STATISTICS dbo.YourTemporalTable;
UPDATE STATISTICS dbo.YourTemporalTable_History;
  • Restart the SQL Server Database Engine service via services.msc on Windows Server 2025 if statistics issues persist after the update.

Alternative or Verification Steps

  • Re-run the original query with a point-in-time value set several minutes in the past (e.g., DATEADD(MINUTE, -10, SYSUTCDATETIME())) to confirm the query executes successfully once clock and transaction timing are corrected.
  • If the error persists across all queries, use SQL Server Management Studio (SSMS) 21 to manually inspect the sys.time_zone_info and server collation settings, as locale mismatches between the OS and SQL Server can occasionally cause temporal boundary miscalculations.

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

Troubleshooting Guide: SQL Server Error 12516 – “Specified Point-in-Time is Invalid”

Why This Error Happens

This error occurs when a temporal query (using FOR SYSTEM_TIME AS OF) specifies a timestamp that predates the most recent schema alteration (ALTER TABLE) on the temporal table or its associated history table. SQL Server’s temporal consistency engine blocks queries referencing a point-in-time before the current schema version to prevent column mismatch errors between the current and historical table structures. This commonly happens after adding/dropping columns, changing data types, or modifying the history table retention settings without accounting for the schema version boundary.

Step-by-Step Resolution Guide

Step 1: Identify the Last Schema Alteration Timestamp

  • Open SQL Server Management Studio (SSMS) and connect to the target instance.
  • Run the following query to check the modify_date on the table in sys.tables:
  SELECT name, modify_date FROM sys.tables WHERE name = 'YourTemporalTableName';
  • Compare this timestamp against the point-in-time value used in your AS OF clause.

Step 2: Adjust the Query’s Point-in-Time Value

  • Modify your temporal query to use a timestamp equal to or later than the modify_date retrieved in Step 1.
  • Example corrected syntax:
  SELECT * FROM YourTable 
  FOR SYSTEM_TIME AS OF '2025-06-15T10:00:00.0000000';
  • Ensure the timestamp format matches datetime2 precision (7 decimal places) to avoid implicit conversion errors.

Step 3: Audit the History Table for Consistency

  • Navigate to the history table (usually named dbo.YourTable_History or similar) via SSMS Object Explorer under Databases > [YourDB] > Tables > System-Versioned.
  • Verify the history table schema matches the current table schema using:
  EXEC sp_help 'dbo.YourTable_History';
  • If mismatched columns are found, this confirms the ALTER operation caused a schema version break requiring the query date adjustment.

Step 4: Recreate Temporal Versioning (If Data Loss is Suspected)

  • If historical data prior to the alteration is required but inaccessible, export existing history data before making further changes.
  • Disable system versioning temporarily via:
  ALTER TABLE YourTable SET (SYSTEM_VERSIONING = OFF);
  • Re-enable versioning and merge the archived history table back using SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.YourHistoryTable).

Alternative or Verification Steps

  • Verify the fix: Re-run the original FOR SYSTEM_TIME AS OF query with the updated timestamp from Step 2; a successful return of row data (rather than Error 12516) confirms resolution.
  • Alternative check: If the error persists, query sys.periods to ensure the SYSTEM_TIME period definition on the table hasn’t been corrupted or redefined with a conflicting start/end column.

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

Troubleshooting Guide: Error 12514 – Invalid Point-in-Time Restore

Why This Error Happens

Error 12514 occurs when SQL Server 2025 rejects a point-in-time restore operation because the specified STOPAT timestamp is later than the current system clock time on the SQL Server instance. This often happens due to time zone mismatches between the client application and the server, clock drift between the backup source and restore target, or a user manually entering an incorrect future date when calculating recovery points. It can also surface when Windows Server 2025’s time synchronization service has desynced from the domain controller, causing the server to report an inaccurate “current time” during the restore validation check.

Step-by-Step Resolution Guide

Step 1: Verify the System Clock and Time Zone Settings

  • Open PowerShell as Administrator and run Get-Date to check the current system time on the SQL Server host.
  • Compare this output against the timestamp you are passing in the STOPAT clause of your RESTORE DATABASE command.
  • Check Windows time zone settings via Settings > Time & Language > Date & Time and ensure “Set time zone automatically” is toggled correctly for your environment.

Step 2: Resynchronize Windows Time Service

  • Open an elevated Command Prompt and force a resync with the domain controller or NTP source using w32tm /resync /force.
  • Verify the time service status with w32tm /query /status to confirm the server is not experiencing clock drift.
  • If the server is a VM, check hypervisor time synchronization settings (e.g., Hyper-V Integration Services) as these can override Windows Time Service and cause conflicts.

Step 3: Correct the STOPAT Timestamp in Your Restore Script

  • Recalculate the correct point-in-time value using UTC to avoid time zone ambiguity, for example: RESTORE LOG [YourDB] FROM DISK = 'D:\Backups\YourDB.trn' WITH STOPAT = '2025-01-15T14:30:00', NORECOVERY;
  • Ensure the timestamp does not exceed the last transaction log backup’s completion time, which you can check via RESTORE HEADERONLY FROM DISK = 'D:\Backups\YourDB.trn'.
  • Remove any hardcoded or copy-pasted timestamps from scripts that may reference a future date relative to the server’s actual current time.

Step 4: Validate Backup Chain Integrity

  • Run RESTORE VERIFYONLY FROM DISK = 'D:\Backups\YourDB.trn' to confirm the log backup file itself is not corrupted and contains valid timestamp metadata.
  • Check that no backup files in the restore sequence have mismatched or illogical timestamps caused by file corruption or improper file transfers between servers.

Alternative or Verification Steps

  • Re-run the RESTORE DATABASE ... WITH STOPAT command using a timestamp several minutes earlier than Get-Date output to confirm the error no longer triggers, then incrementally adjust closer to your target recovery point.
  • If the issue persists despite correct timestamps, check for virtualization-layer time sync overrides (common in Hyper-V or VMware environments) that may be silently resetting the SQL Server host’s clock after each w32tm resync attempt.

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

Troubleshooting Guide: SQL Server Error 12515

Why This Error Happens

Error 12515 occurs when querying Temporal Tables (System-Versioned Tables) using the FOR SYSTEM_TIME AS OF clause with a timestamp that predates the creation of the table or its history table. This commonly happens due to incorrect timezone conversions (UTC vs. Local Server Time) in the application layer, or when a table has been recently recreated/migrated, resetting its “creation” metadata while the application still attempts to query historical dates from before the migration.

Step-by-Step Resolution Guide

Step 1: Verify the Table Creation Timestamp

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the exact creation date of the specific temporal table in question:
SELECT name, create_date FROM sys.tables WHERE name = 'YourTableName';
  • Compare this create_date value against the specific point-in-time timestamp used in your FOR SYSTEM_TIME AS OF query.

Step 2: Audit and Correct Timezone Discrepancies

  • Check the application code (C#, Python, or PowerShell scripts) generating the query to ensure it is not accidentally converting local time to UTC, which could push the requested timestamp earlier than the table’s actual creation date.
  • Standardize the format to ISO 8601 (e.g., '2025-01-01T00:00:00.0000000') to avoid regional parsing errors specific to Windows Server 2025 locale settings.
  • Ensure the timestamp variable is not defaulting to 0001-01-01 due to a null or uninitialized DateTime object in the calling application.

Step 3: Inspect the History Table for Data Retention Gaps

  • Navigate to Object Explorer > Databases > [Your DB] > Tables in SSMS and expand the “System-Versioned” table to locate the linked History Table.
  • Verify that data retention policies (if enabled via HISTORY_RETENTION_PERIOD) have not purged older records, which might make a previously valid timestamp invalid if the table itself was rebuilt.
  • If the table was dropped and recreated during a recent migration to Windows Server 2025, update your application’s “oldest valid query date” logic to reflect the new creation timestamp rather than the original historical data.

Step 4: Adjust the Query Logic with a Dynamic Floor Value

  • Modify the Transact-SQL query to use a GREATEST logic check (or a CASE statement in SQL Server 2025) to ensure the input timestamp is never less than the table’s creation date.
  • Example implementation:
DECLARE @SafeTime DATETIME2 = 
    CASE WHEN @UserInputTime < (SELECT create_date FROM sys.tables WHERE name = 'YourTableName') 
    THEN (SELECT create_date FROM sys.tables WHERE name = 'YourTableName') 
    ELSE @UserInputTime END;

SELECT * FROM YourTableName FOR SYSTEM_TIME AS OF @SafeTime;

Alternative or Verification Steps

  • Verification: Re-run the original query using the exact create_date retrieved in Step 1 as the point-in-time value; if the query executes successfully, the timestamp logic in the application is confirmed as the root cause.
  • Alternative: If historical data integrity is critical and was lost due to a table rebuild, restore the specific database to a point-in-time backup prior to the migration to recover the original history table schema and data.

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

Troubleshooting Guide: SQL Server Error 12512 – Internal Error While Cloning Trident DW Database

Why This Error Happens

Error 12512 typically occurs when SQL Server 2025’s Trident data warehouse cloning operation encounters an internal state mismatch, often caused by insufficient permissions on the storage layer or an interrupted metadata transaction. This can also result from corrupted transaction log entries in the source database or a stale lock held by a previous failed clone attempt. Additionally, resource governor throttling or insufficient disk space on the target volume can trigger this error mid-clone.

Step-by-Step Resolution Guide

Step 1: Verify Database and Service Account Permissions

  • Confirm the SQL Server service account has db_owner rights on both source and target Trident DW databases.
  • Check that the account also has CREATE DATABASE and ALTER ANY DATABASE server-level permissions.
  • Run SELECT * FROM sys.fn_my_permissions(NULL, 'SERVER'); to audit current permission scope.

Step 2: Clear Stale Locks and Orphaned Clone Metadata

  • Query sys.dm_tran_locks to identify any lingering locks tied to the failed clone session.
  • Execute DBCC OPENTRAN('TridentDW'); to check for uncommitted long-running transactions.
  • If a stale session is found, terminate it using KILL <session_id>; and retry the clone operation.

Step 3: Validate Storage Path and Disk Space

  • Ensure the target clone directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) has at least 20% free space relative to the source database size.
  • Check NTFS permissions on the folder to confirm the SQL Server service account has full control.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell to clear any cached file handles.

Step 4: Rebuild Trident Metadata Cache

  • Open SQL Server Management Studio (SSMS) and run EXEC sp_trident_refresh_metadata 'TridentDW'; to force a metadata resync.
  • If this stored procedure is unavailable, manually drop and recreate the Trident warehouse linked service connection from the Fabric/Trident workspace settings.
  • Re-attempt the clone operation after the cache rebuild completes.

Step 5: Review SQL Server Error Logs for Root Cause

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Search for entries immediately preceding Error 12512 to identify whether it’s a timeout, permission denial, or I/O failure.
  • Cross-reference the timestamp with Windows Event Viewer (Application log) for correlating system-level warnings.

Alternative or Verification Steps

  • To verify the fix, re-run the clone operation and monitor sys.dm_exec_requests in real time to confirm the clone completes without rollback.
  • As an alternative, use the BACKUP DATABASE and RESTORE DATABASE WITH MOVE approach to manually recreate the Trident DW database if automated cloning continues to fail after the above steps.

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

Troubleshooting Guide: Error 12513 – Internal Error While Cloning Table in SQL Server 2025

Why This Error Happens

Error 12513 typically occurs when SQL Server’s internal table cloning operation (used for schema-only copy operations via sp_clone_database or similar DDL cloning utilities) encounters a mismatch between metadata and the underlying data files. This is often caused by insufficient permissions on the target directory, a corrupted or locked source table file, or an interrupted previous clone operation that left temporary system objects in an inconsistent state. In some cases, this also surfaces when the SQL Server service account lacks write access to the destination path specified during the clone request.

Step-by-Step Resolution Guide

Step 1: Verify Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11 and locate the SQL Server (MSSQLSERVER) service.
  • Confirm the “Log On As” account has Full Control on both the source database directory and the target clone directory (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\).
  • Run the following command in an elevated PowerShell window to grant permissions if missing:
  icacls "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)F

Step 2: Clear Orphaned Clone Metadata

  • Open SQL Server Management Studio (SSMS) and connect to the instance via a query window.
  • Run the following to check for incomplete clone sessions:
  SELECT * FROM sys.dm_exec_requests WHERE command LIKE '%CLONE%';
  • If a stuck session is found, terminate it using KILL <session_id>; and retry the clone operation.

Step 3: Validate Table Consistency

  • Run DBCC CHECKTABLE('YourTableName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out underlying corruption.
  • If corruption is detected, restore the table from the most recent clean backup before attempting the clone again.

Step 4: Restart SQL Server Service and Clear TempDB Cache

  • In an elevated PowerShell prompt, restart the instance:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This clears any residual locks in tempdb that may be blocking the internal clone engine from allocating new metadata structures.

Alternative or Verification Steps

  • After applying the fixes, re-run the original CLONE DATABASE or sp_clone_database command and confirm Error 12513 no longer appears in the SQL Server Error Log (ERRORLOG file located in the MSSQL\LOG folder).
  • As an alternative, if cloning still fails, perform a manual schema-only export using SQL Server Generate Scripts Wizard and import it into a new empty database to bypass the internal cloning engine entirely.

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

Why This Error Happens

Error 12511 occurs because the DBCC CLONEDATABASE feature is disabled by default at the instance level via a server-level configuration flag (Trace Flag 3608 dependency and the 'allow database cloning' configuration option). This typically happens on fresh installations of SQL Server 2025 where the sp_configure option for database cloning has not been explicitly enabled, or where the executing login lacks the necessary ALTER permissions combined with VIEW SERVER STATE and CREATE DATABASE permissions. Additionally, this can occur if the instance is running in a restricted Azure Arc-enabled or Contained Availability Group mode where cloning operations are blocked by policy.

Step-by-Step Resolution Guide

Step 1: Verify Current Configuration State

  • Open SQL Server Management Studio (SSMS) and connect to the target instance.
  • Run the following query to check the current value:
  EXEC sp_configure 'allow database cloning';
  • If the run_value returns 0, this confirms the feature is disabled and causing the 12511 error.

Step 2: Enable the Database Cloning Feature

  • Execute the following T-SQL script to enable the advanced option and the specific feature flag:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  GO
  EXEC sp_configure 'allow database cloning', 1;
  RECONFIGURE;
  GO
  • Ensure you run this using a login with sysadmin server role privileges, as a standard db_owner role is insufficient to change server-level configurations.

Step 3: Restart the SQL Server Service

  • Navigate to the Services management console on Windows Server 2025 (services.msc).
  • Locate SQL Server (MSSQLSERVER) or the specific named instance.
  • Right-click and select Restart to ensure the configuration change is fully loaded into the Service Control Manager (SCM) context.
  • Alternatively, use PowerShell to restart the service:
  Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Re-attempt the DBCC CLONEDATABASE Command

  • Open a new query window in SSMS.
  • Execute the clone command again, specifying the source and destination database names:
  DBCC CLONEDATABASE ('SourceDB', 'ClonedDB');
  • Confirm that the command completes with a “Command(s) completed successfully” message rather than throwing the 12511 error.

Alternative or Verification Steps

  • Verification: Query the sys.databases view to confirm the new cloned database exists and check the is_cleanly_shutdown status to ensure data integrity was maintained during the clone operation.
  • Alternative: If sp_configure changes do not persist due to Group Policy restrictions on Windows Server 2025, manually edit the registry key under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLServer to ensure no local security policy is overriding the AllowDatabaseCloning DWORD value.

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

Troubleshooting Guide: SQL Server Error 12509 – Insufficient Database Permissions

Why This Error Happens

Error 12509 occurs when the executing login does not hold the necessary database-level roles (such as db_owner or db_datawriter) on either the source or target database involved in a data transfer operation, such as Database Mail, replication, or a cross-database query. This is common after a database restore or migration, as orphaned users may retain Windows/SQL logins but lose their internal Security Identifier (SID) mapping to the database user. Additionally, if the operation relies on a Linked Server, the configured security context (“Be made using the login’s current security context”) may not have equivalent permissions on the remote target.

Step-by-Step Resolution Guide

Step 1: Verify and Repair Orphaned User Mappings

  • Open SQL Server Management Studio (SSMS) and connect to the instance via Windows 11 or Windows Server 2025.
  • Run the following query to check for orphaned users on both source and target databases:
  EXEC sp_change_users_login 'Report';
  • If orphaned users are found, remap the SID using:
  EXEC sp_change_users_login 'Update_One', 'UserName', 'LoginName';

Step 2: Grant Explicit Database Roles

  • Navigate to Object Explorer > Databases > [Target DB] > Security > Users.
  • Right-click the specific user account causing the 12509 error and select Properties.
  • Under “Membership,” manually check the boxes for db_datareader and db_datawriter (or db_owner if administrative rights are required for schema changes).
  • Apply the changes and restart the specific SQL Agent Job or ETL process to test immediately.

Step 3: Audit Linked Server Security Context

  • If the error occurs during a cross-server query, navigate to Server Objects > Linked Servers in SSMS.
  • Right-click the specific Linked Server and select Properties > Security.
  • Ensure the mapping is set to “Be made using this security context” with a login that has explicit sysadmin or db_owner rights on the remote target, rather than relying on “Login’s current security context” if the local login doesn’t exist remotely.

Step 4: Check Windows Server 2025 Firewall and UAC Permissions

  • If running on Windows Server 2025 Core, ensure that User Account Control (UAC) is not blocking the SQL Service account from accessing local resources.
  • Verify the SQL Server Service Account (visible in SQL Server Configuration Manager) has “Log on as a service” rights via secpol.msc > Local Policies > User Rights Assignment.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM fn_my_permissions(NULL, 'DATABASE'); while impersonating the specific user to confirm the required CONNECT, SELECT, and INSERT permissions are now present.
  • Alternative: If role assignment fails to resolve the issue, drop the specific database user entirely using DROP USER [UserName] and recreate them using CREATE USER [UserName] FOR LOGIN [LoginName] to force a clean permission mapping.