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

Troubleshooting Guide: SQL Server Error 10530 – Plan Guide Statement Mismatch

Why This Error Happens

Error 10530 occurs when the @statement_start_offset value supplied to sp_create_plan_guide does not correspond to the exact character position of a statement in the target module, batch, or query text. This typically happens because the T-SQL text was modified (extra whitespace, comments, or line breaks added/removed) after the offset was originally calculated. It can also occur if the plan guide was generated against a cached execution plan that no longer matches the current definition of the stored procedure, trigger, or function due to a schema update or recompilation.

Step-by-Step Resolution Guide

Step 1: Recalculate the Statement Offset

  • Query sys.dm_exec_sql_text and sys.dm_exec_query_stats to retrieve the exact current text of the batch or module.
  • Use the following query to find the precise offsets for statements in a cached plan:
  SELECT st.text, qs.statement_start_offset, qs.statement_end_offset
  FROM sys.dm_exec_query_stats AS qs
  CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
  WHERE st.text LIKE '%YourProcedureName%';
  • Confirm the offset is measured in bytes (double-byte for nvarchar text), not character count, as this is a common miscalculation.

Step 2: Regenerate the Plan Guide Using spgetquery_template or Plan Cache

  • Drop the invalid plan guide using sys.sp_control_plan_guide 'DROP', 'GuideName'; to clear the broken definition.
  • Re-run sp_create_plan_guide using the freshly extracted @stmt text and the newly calculated @statement_start_offset from Step 1.
  • If targeting a stored procedure, ensure the @module_or_batch parameter exactly matches the procedure name, including schema (e.g., dbo.MyProc).

Step 3: Validate Module Text Consistency

  • Check if the underlying object was altered via sys.objects.modify_date after the plan guide was created.
  • If the procedure was recently altered, the old offset is now stale; re-extract the text via OBJECT_DEFINITION(OBJECT_ID('dbo.MyProc')) to ensure whitespace and line endings match exactly.
  • On Windows Server 2025 environments, verify that SSMS or deployment scripts are not converting line endings (CRLF vs LF) during file transfer, as this shifts offset calculations.

Step 4: Use Plan Guide Matching via spcreateplanguidefrom_handle

  • Instead of manually calculating offsets, use sp_create_plan_guide_from_handle with a valid @plan_handle and @statement_start_offset pulled directly from sys.dm_exec_query_stats.
  • This bypasses manual text-matching errors entirely by binding directly to the cached execution plan reference.

Alternative or Verification Steps

  • Verify the fix by running SELECT * FROM sys.plan_guides WHERE name = 'YourGuideName'; and confirming the is_disabled column equals 0 and no error is thrown on creation.
  • If manual offset calculation continues to fail, use the Query Store Force Plan feature in SQL Server Management Studio as an alternative to classic plan guides, as it automatically handles statement matching internally.

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

Troubleshooting Guide: SQL Server Error 10529 – Plan Guide Conflict

Why This Error Happens

This error occurs because SQL Server already has an existing plan guide with @type = 'TEMPLATE' bound to the exact same @stmt text you are trying to target with a new plan guide. SQL Server enforces a uniqueness constraint that prevents multiple template-type plan guides from matching the identical statement, since this would create ambiguity in how the query optimizer should parameterize and execute that specific query. This typically happens when automation scripts, forced parameterization routines, or DBA teams attempt to re-apply a plan guide without first checking sys.plan_guides for existing entries.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Plan Guide

  • Open SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Run the following query to locate the existing template guide:
  SELECT name, scope_type_desc, is_disabled, statement 
  FROM sys.plan_guides 
  WHERE type_desc = 'TEMPLATE';
  • Note the name of the plan guide returned, as you will need it for the next step.

Step 2: Drop the Existing Plan Guide

  • Use sp_control_plan_guide to remove the conflicting template guide before creating a new one.
  • Execute the drop command using the exact name identified in Step 1:
  EXEC sp_control_plan_guide N'DROP', N'Guide_Name_Here';
  • If the name contains special characters or spaces, ensure it is properly bracketed or quoted using N'[Guide Name]'.

Step 3: Validate Statement Text Formatting

  • Check that the @stmt parameter in your new CREATE script matches the formatting (including whitespace, casing, and line breaks) of the query you intend to target.
  • Use sp_get_query_template to regenerate a clean, normalized version of the statement text and parameters list to avoid future mismatches.
  • Re-run your original EXEC sp_create_plan_guide command now that the path is clear.

Step 4: Restart SQL Server Service (If Cache is Stale)

  • If the error persists despite dropping the guide, the plan cache may be holding a stale reference.
  • Open Services.msc on your Windows Server 2025 machine.
  • Locate SQL Server (MSSQLSERVER) or your named instance, right-click, and select Restart.

Alternative or Verification Steps

  • Verify the Fix: Re-query sys.plan_guides to confirm only one entry exists for that specific @stmt value, and check is_disabled is set to 0 to ensure the new guide is active.
  • Alternative Approach: If dropping the old guide isn’t feasible due to active production dependencies, use sp_control_plan_guide N'DISABLE' on the old guide instead of dropping it, which effectively frees up the conflict without permanently deleting the configuration data.

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

Troubleshooting Guide: Error 10528 – Invalid Plan Guide Name

Why This Error Happens

Error 10528 occurs when the sp_create_plan_guide stored procedure is executed with a plan guide name that begins with a pound/hash (#) character. SQL Server reserves names beginning with # and ## to denote local and global temporary objects respectively, and this naming convention is strictly enforced even for logical objects like plan guides that are not physically temporary tables. The SQL Server 2025 Query Optimizer rejects the object creation at the parsing stage before any metadata is written to the sys.plan_guides catalog view, as it cannot distinguish the intent between a temporary object reference and a standard identifier.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Script

  • Locate the specific script or application module calling sp_create_plan_guide.
  • Search for the @name parameter within the EXEC sp_create_plan_guide block.
  • Use SQL Server Management Studio (SSMS) 21 or Azure Data Studio to open the deployment script in question.

Step 2: Rename the Plan Guide Identifier

  • Remove the leading # or ## characters from the @name string value.
  • Replace the hash symbol with an underscore (_) or a descriptive prefix (e.g., change #MyGuide to PG_MyGuide).
  • Ensure the new name still adheres to standard SQL Server identifier rules (max 128 characters, no reserved keywords).

Step 3: Validate Object Naming Conventions

  • Cross-reference the new name against existing objects in sys.plan_guides to prevent duplicate name conflicts (which would trigger a different error, 10529).
  • If the name must contain special characters, enclose it strictly in square brackets [ ], though this is generally discouraged for Plan Guides.

Step 4: Re-execute the Creation Script

  • Run the corrected sp_create_plan_guide command against the target database using an account with ALTER ANY DATABASE DDL TRIGGER or appropriate sysadmin/db_owner permissions.
  • Open the specific session (SPID) in Activity Monitor to confirm the command completes without a timeout or blocking issue.

Alternative or Verification Steps

  • Verify the Fix: Query the system view using SELECT name, scope_type_desc FROM sys.plan_guides WHERE name = 'YourNewName'; to confirm the object now exists in the database metadata.
  • Alternative Approach: If dynamic SQL is generating this name programmatically, inspect the application’s string concatenation logic (e.g., in a .NET or Python script) to ensure a variable isn’t accidentally prepending a # symbol intended for a different temporary table creation step elsewhere in the code.

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

Troubleshooting Guide: SQL Server Error 10527 – Cannot Create Plan Guide on Temporary Object

Why This Error Happens

This error occurs because SQL Server plan guides are designed to attach to persistent, schema-bound database objects, and they explicitly cannot reference temporary tables (#temp or ##temp) or temporary stored procedures. The error is triggered when the @module_or_batch or target object parameter in sp_create_plan_guide points to an object name prefixed with # or ##, which SQL Server identifies as a session-scoped or global temporary object. Since plan guides must persist in sys.plan_guides independently of a session’s lifecycle, binding them to a temporary object—which is destroyed when the session ends or the batch completes—is architecturally invalid.

Step-by-Step Resolution Guide

Step 1: Identify the Object Referenced in the Plan Guide Creation Script

  • Open the T-SQL script or stored procedure call that invoked sp_create_plan_guide.
  • Check the @module_or_batch parameter value for a leading # (local temp) or ## (global temp) prefix.
  • Run the following diagnostic query to confirm the object type:
SELECT name, type_desc, create_date 
FROM tempdb.sys.objects 
WHERE name LIKE '#%';

Step 2: Convert the Temporary Object into a Permanent Object

  • If the logic resides in a temporary stored procedure (e.g., #GetSalesData), recreate it as a permanent stored procedure in the target user database rather than tempdb.
  • Use CREATE PROCEDURE dbo.GetSalesData instead of CREATE PROCEDURE #GetSalesData.
  • If the plan guide targets an ad-hoc batch referencing a temp table, replace the temp table with a permanent staging table or a table variable, depending on the workload requirements.

Step 3: Recreate the Plan Guide Against the Permanent Object

  • Re-run sp_create_plan_guide using the fully qualified, permanent object name.
  • Example syntax:
EXEC sp_create_plan_guide 
    @name = N'PlanGuide_Sales', 
    @stmt = N'SELECT * FROM dbo.Sales', 
    @type = N'OBJECT', 
    @module_or_batch = N'dbo.GetSalesData', 
    @params = NULL, 
    @hints = N'OPTION (RECOMPILE)';
  • Verify the object exists in the correct database context (not tempdb) before execution using SELECT OBJECT_ID('dbo.GetSalesData').

Step 4: Clear Cached Temporary References (If Applicable)

  • If the script was executed in a session that cached a temporary object reference, close and reopen the SQL Server Management Studio (SSMS) query window on Windows Server 2025 or Windows 11 to clear the session-scoped tempdb binding.
  • Restart the SQL Server Agent job (if the plan guide creation was part of an automated job) to ensure no stale temporary object handles remain.

Alternative or Verification Steps

  • Verify the fix by querying sys.plan_guides to confirm the new plan guide is listed with is_disabled = 0 and the correct scope_type_desc (e.g., OBJECT or SQL).
  • If permanent object conversion is not feasible for your workload, use Plan Forcing via Query Store instead (available in SQL Server 2025), as Query Store can force execution plans for ad-hoc and temporary workloads without the object-persistence restrictions that plan guides require.

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

Troubleshooting Guide: Error 10526 — Cannot Drop Trigger Referenced by Plan Guide

Why This Error Happens

This error occurs because SQL Server 2025 prevents the deletion of a DML/DDL trigger when an active plan guide has been explicitly bound to it for query optimization purposes. The Database Engine maintains a dependency link between the plan guide and the trigger object to ensure the specified execution plan (hints) remains valid and enforceable. Since dropping the trigger would orphan the plan guide and break the query optimization strategy, the engine blocks the DROP TRIGGER operation until the dependency is manually removed.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Plan Guide

  • Open SQL Server Management Studio (SSMS) and connect to the target instance running on Windows Server 2025 or Windows 11.
  • Run the following query to locate the specific plan guide name referencing the trigger:
SELECT name, scope_type, scope_type_desc, is_disabled 
FROM sys.plan_guides 
WHERE scope_type_desc = 'OBJECT';
  • Cross-reference the scope_object_id column with OBJECT_ID('YourTriggerName') to confirm the exact match mentioned in the error message.

Step 2: Record the Plan Guide Definition

  • Before deleting anything, back up the logic by querying the full definition:
SELECT name, hints, query_text 
FROM sys.plan_guides 
WHERE name = 'PlanGuideNameFromStep1';
  • Copy the hints and query_text output into a .sql script file and save it to a local directory (e.g., C:\SQLBackups\PlanGuides\) for future re-creation if needed.

Step 3: Drop the Plan Guide

  • Execute the sp_control_plan_guide system stored procedure to remove the dependency using the DROP parameter:
EXEC sp_control_plan_guide N'DROP', N'PlanGuideNameFromStep1';
  • Confirm the command returns a success status with no error messages in the “Messages” tab of SSMS.

Step 4: Execute the Original Drop Command

  • Retry the original command that triggered Error 10526:
DROP TRIGGER YourTriggerName;
  • Verify the command completes without being blocked by the previous dependency check.

Step 5: Recreate the Plan Guide (Optional)

  • If the trigger logic is being updated rather than permanently removed, recreate the trigger first.
  • Use the sp_create_plan_guide procedure with the parameters saved in Step 2 to reapply the optimization hints to the new object.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM sys.plan_guides; again after the fix to ensure the specific plan guide entry no longer appears in the result set and that the trigger ID is removed from sys.triggers.
  • Alternative: If sp_control_plan_guide fails due to permissions, ensure the executing login has ALTER ANY DATABASE DDL TRIGGER or CONTROL permission on the database, as plan guide manipulation requires elevated schema-modification rights in SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 10525 — Plan Guide Matched Statement After Automatic Parameterization

Why This Error Happens

This error occurs when a plan guide is created to match a specific SQL statement, but the database is also running under FORCED or SIMPLE parameterization, which rewrites the literal values in the query into parameters before the plan guide can evaluate it. Essentially, there is a conflict between two parameterization mechanisms acting on the same statement, causing SQL Server to detect that the text it matched no longer represents the original, non-parameterized query shape. This typically results from a misconfigured database-level setting (PARAMETERIZATION FORCED) combined with a plan guide that was authored assuming SIMPLE parameterization behavior.

Step-by-Step Resolution Guide

Step 1: Identify the Current Parameterization Mode

  • Run the following query to check the database setting: SELECT name, is_parameterization_forced FROM sys.databases WHERE name = 'YourDatabaseName';
  • A result of 1 confirms FORCED parameterization is active, which is likely conflicting with your plan guide.
  • Cross-reference this with the plan guide definitions using SELECT * FROM sys.plan_guides; to see the exact @stmt and @params values.

Step 2: Align the Plan Guide with the Parameterization Mode

  • If FORCED parameterization is required for performance reasons, update the plan guide to use the parameterized form of the query, rather than the literal-value version.
  • Use sp_get_query_template to generate the exact parameterized text and parameter list that SQL Server will produce internally.
  • Drop the old guide: EXEC sp_control_plan_guide N'DROP', N'YourPlanGuideName';
  • Recreate it using the templated text output from sp_get_query_template so it matches post-parameterization syntax.

Step 3: Switch Database Parameterization to SIMPLE (If Appropriate)

  • If FORCED parameterization is not business-critical for this specific workload, revert the database to default behavior: ALTER DATABASE YourDatabaseName SET PARAMETERIZATION SIMPLE;
  • This stops the automatic rewriting of literals, allowing literal-value plan guides to match correctly without interference.
  • Restart the SQL Server service via services.msc on Windows Server 2025 only if the change does not take effect immediately for active connections.

Step 4: Validate Plan Guide Syntax Against Live Query Text

  • Open SQL Server Management Studio (SSMS) and extract the exact text of the problematic query from sys.dm_exec_query_stats combined with sys.dm_exec_sql_text.
  • Ensure there is no mismatch in whitespace, casing, or comments between the live query and the @stmt parameter in your plan guide definition, as even minor discrepancies prevent matching.

Alternative or Verification Steps

  • Verification: After applying changes, run the query in a new session and check sys.plan_guides for the is_disabled column; ensure it reads 0, and confirm the execution plan via SET STATISTICS XML ON shows the plan guide was successfully applied in the plan properties.
  • Alternative: If matching remains unstable, drop the specific plan guide and use a Plan Guide based on OBJECT or SQL handle instead of literal text matching, as this bypasses parameterization text-matching conflicts entirely by targeting the query hash rather than the raw string.

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

Troubleshooting Guide: SQL Server Error 10524 – Cannot Parameterize @querytext

Why This Error Happens

Error 10524 occurs when SQL Server’s forced parameterization engine encounters a query construct it cannot safely convert into a parameterized plan, such as queries containing variables, certain functions, or syntax incompatible with simple/forced parameterization rules. This is commonly triggered when the database has PARAMETERIZATION FORCED enabled at the database level, but the incoming query text includes elements (like TOP, subqueries with literals, or non-deterministic functions) that violate parameterization constraints. It can also surface due to outdated cardinality estimation behavior or compatibility level mismatches after upgrading to SQL Server 2025 on Windows Server 2025/Windows 11 hosts.

Step-by-Step Resolution Guide

Step 1: Confirm the Current Parameterization Setting

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check the current mode:
  SELECT name, is_parameterization_forced 
  FROM sys.databases 
  WHERE name = 'YourDatabaseName';
  • If is_parameterization_forced returns 1, this confirms Forced Parameterization is the likely cause.

Step 2: Switch to Simple Parameterization (Temporary Fix)

  • Execute the following T-SQL command to revert the database to simple parameterization:
  ALTER DATABASE YourDatabaseName 
  SET PARAMETERIZATION SIMPLE;
  • Note: This requires exclusive access; ensure no active connections are blocking the ALTER DATABASE command by checking sys.dm_exec_sessions.

Step 3: Use Plan Guides for Specific Problematic Queries

  • If Forced Parameterization is required for performance reasons across the database, do not disable it globally. Instead, create a Plan Guide to exempt the specific @querytext causing Error 10524.
  • Use sp_create_plan_guide with the TEMPLATE type to explicitly disable parameterization for that specific query pattern:
  EXEC sp_create_plan_guide 
    @name = N'Guide_DisableParam',
    @stmt = N'SELECT * FROM Table WHERE Column = @Var',
    @type = N'TEMPLATE',
    @module_or_batch = NULL,
    @params = NULL,
    @hints = N'OPTION(PARAMETERIZATION SIMPLE)';

Step 4: Check for Windows Server 2025 Registry/Driver Conflicts

  • Ensure the ODBC Driver 18+ (or native client) installed on the Windows 11/Windows Server 2025 client machine is fully updated, as outdated drivers can malform query text before it reaches the parser.
  • Navigate to Control Panel > ODBC Data Sources > Drivers tab to verify the driver version matches SQL Server 2025 requirements.

Step 5: Restart the SQL Server Service

  • Apply the changes by restarting the relevant service via Services.msc or PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This clears the existing cached execution plans that might be stuck in a failed parameterization state.

Alternative or Verification Steps

  • Verify the Fix: Re-run the original query that triggered the error via SSMS or your application. Check the SQL Server Error Log (Management > SQL Server Logs) to confirm Error 10524 no longer appears during execution.
  • Alternative Solution: If the error persists, rewrite the application-side query to avoid dynamic SQL concatenation and use fully parameterized stored procedures instead, bypassing the need for SQL Server’s automatic parameterization engine entirely.

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

Troubleshooting Guide: Error 10523 in Microsoft SQL Server 2025

Why This Error Happens

Error 10523 occurs when the sp_create_plan_guide or sp_create_plan_guide_from_handle stored procedure receives a @querytext parameter that does not resolve to a single, valid, parseable T-SQL statement. This typically happens when the captured query text includes multiple batches separated by GO or semicolons, contains comments/whitespace that corrupts the parser’s recognition of statement boundaries, or includes syntax that is incompatible with the specified @type (OBJECT, SQL, or TEMPLATE) of the plan guide. It can also surface when query text is pulled from sys.dm_exec_sql_text and inadvertently includes trailing null characters or truncated SQL from a batch.

Step-by-Step Resolution Guide

Step 1: Isolate and Validate the Query Text

  • Extract the exact string being passed to @querytext and run it independently in a new query window to confirm it parses as a single valid statement.
  • Check for multiple statements separated by semicolons (;) — plan guides created with @type = N'TEMPLATE' require exactly one parameterizable statement.
  • Remove any GO batch separators, as these are not valid T-SQL and will cause the parser to fail with 10523.
  • Example validation query:
  SELECT @querytext AS QueryToTest;

Step 2: Clean Up Whitespace, Comments, and Hidden Characters

  • Strip leading/trailing whitespace and any embedded carriage returns that may have been introduced when copying text from sys.dm_exec_requests or sys.dm_exec_sql_text.
  • Remove inline comments (-- or /* */) immediately preceding the statement, as some SQL Server 2025 parser builds treat malformed comment blocks as invalid syntax.
  • Use the LTRIM(RTRIM()) function or REPLACE(@querytext, CHAR(13) + CHAR(10), ' ') to normalize the string before passing it to sp_create_plan_guide.

Step 3: Match the @type Parameter to the Query Structure

  • Confirm that @type = N'TEMPLATE' is only used with statements that SQL Server can safely auto-parameterize (typically simple SELECT, INSERT, UPDATE, DELETE with literal constants).
  • If the query contains complex constructs (CTEs, subqueries with variables, or multiple joins with literals in unusual positions), switch to @type = N'SQL' instead and supply an explicit @module_or_batch if needed.
  • Re-run the procedure call:
  EXEC sp_create_plan_guide
      @name = N'Guide1',
      @stmt = N'SELECT * FROM Sales.Orders WHERE OrderID = 1',
      @type = N'TEMPLATE',
      @module_or_batch = NULL,
      @params = N'@0 int',
      @hints = N'OPTION (PARAMETERIZATION FORCED)';

Step 4: Rebuild the Plan Guide from a Verified Query Handle

  • If extracting text manually is unreliable, use sp_create_plan_guide_from_handle with a known-good @plan_handle from sys.dm_exec_query_stats instead of manually copying @querytext.
  • Verify the handle maps to a single statement using sys.dm_exec_sql_text(plan_handle) and confirm the text column returns one statement only before executing the procedure.

Alternative or Verification Steps

  • After applying the fix, confirm success by querying sys.plan_guides and checking that the new guide appears with is_disabled = 0 and no error returned during creation.
  • If the error persists, bypass template matching entirely by forcing parameterization at the database level using ALTER DATABASE <DBName> SET PARAMETERIZATION FORCED;, which avoids the need for manually created template plan guides.

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

Troubleshooting Guide: SQL Server Error 10522 – Illegal @hints Value for Template Plan Guides

Why This Error Happens

This error occurs when creating a plan guide with @type = N'TEMPLATE' but the @hints parameter contains a query hint other than OPTION(PARAMETERIZATION FORCED) or OPTION(PARAMETERIZATION SIMPLE). SQL Server’s template plan guides are specifically designed to override the parameterization behavior for queries matching a specific template, so they only accept these two parameterization directives and reject any other hint syntax (such as join hints, recompile hints, or index hints). This is a validation rule enforced internally by the sp_create_plan_guide stored procedure, not a bug—it is working as designed to prevent conflicting or unsupported hint combinations for this specific plan guide type.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Statement

  • Locate the exact sp_create_plan_guide or sp_create_plan_guide_from_handle call that triggered Error 10522.
  • Check SQL Server Management Studio (SSMS) query results pane or the Windows Event Viewer under Applications and Services Logs > Microsoft > Windows > SQLServer for the full error text, including the plan guide name referenced in %.*ls.
  • Note the current value passed into the @hints parameter.

Step 2: Correct the @hints Parameter Value

  • Open the script in SSMS and inspect the @hints argument for anything other than parameterization options.
  • Replace invalid values with the only two accepted options, written exactly as:
  • N'OPTION(PARAMETERIZATION FORCED)'
  • N'OPTION(PARAMETERIZATION SIMPLE)'
  • Ensure there are no trailing hints concatenated onto the string, such as OPTION(PARAMETERIZATION FORCED, RECOMPILE), as combining hints with parameterization options in a template guide is not supported.

Step 3: Re-Evaluate the Plan Guide Type if Other Hints Are Needed

  • If your intent was to apply hints like OPTIMIZE FOR, MAXDOP, or RECOMPILE, change @type from TEMPLATE to SQL or OBJECT instead, since those types support the full range of query hints.
  • Update the @type parameter and adjust @module_or_batch / @stmt accordingly to match the new plan guide type requirements.
  • Re-run the corrected sp_create_plan_guide statement in a test environment first.

Step 4: Apply the Fix in Production

  • Once validated, execute the corrected script against the production instance using SSMS or sqlcmd.
  • Example corrected syntax:
EXEC sp_create_plan_guide
    @name = N'TemplateGuide1',
    @stmt = N'SELECT * FROM Sales.Orders WHERE OrderID = @1',
    @type = N'TEMPLATE',
    @module_or_batch = NULL,
    @params = N'@1 int',
    @hints = N'OPTION(PARAMETERIZATION FORCED)';
  • Confirm the command completes without returning Error 10522.

Alternative or Verification Steps

  • Query sys.plan_guides and check the scope_type and hints columns to confirm the new plan guide was created successfully with the correct parameterization option.
  • If template plan guides continue to fail, consider enabling forced parameterization at the database level instead via ALTER DATABASE [YourDB] SET PARAMETERIZATION FORCED;, which achieves similar query plan reuse behavior without requiring individual template guides.

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

Troubleshooting Guide: SQL Server Error 10521 – Plan Guide Creation Failure

Why This Error Happens

This error occurs when executing sp_create_plan_guide with a @type parameter value (such as OBJECT, SQL, or TEMPLATE) that has specific dependency requirements on other parameters, but one of those required parameters (like @module_or_batch, @params, or @hints) was passed as NULL. SQL Server 2025 enforces strict validation logic during plan guide creation to ensure the guide has enough contextual information to bind correctly to a query plan. Essentially, the command is structurally incomplete because the parameter combination violates the internal schema rules for that specific guide type.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Type and Missing Parameter

  • Review the error message text carefully; it explicitly names the @type value used (e.g., 'OBJECT') and the specific parameter that was left NULL (e.g., '@module_or_batch').
  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact T-SQL script that triggered the sp_create_plan_guide call.

Step 2: Correct the Parameter Values in the Script

  • If @type is set to OBJECT, ensure you provide a valid schema-qualified object name in the @module_or_batch parameter; it cannot be NULL for this type.
  • If @type is set to SQL or TEMPLATE, ensure the @stmt parameter contains the exact Transact-SQL statement text you are trying to optimize.
  • Verify that @params is set to NULL only if the query truly has no parameters; otherwise, provide the comma-separated list of data types matching the query signature.

Step 3: Validate Syntax Using Native SQL Server Tools

  • Run the query in a test environment on Windows Server 2025 using a non-production database to confirm the syntax compiles without triggering Error 10521.
  • Use the native sp_help_plan_guide stored procedure to check if a similar, correctly configured plan guide exists that you can use as a template for syntax.

Step 4: Re-execute the Corrected Script

  • Run the updated EXEC sp_create_plan_guide command with the newly populated parameters.
  • Ensure the SQL Server Agent service is running under a least-privilege Windows Server 2025 service account during execution, as insufficient permissions can sometimes cause silent parameter validation failures.

Alternative or Verification Steps

  • Verify the fix by querying the sys.plan_guides system view (SELECT * FROM sys.plan_guides WHERE name = 'YourPlanGuideName';) to confirm the is_disabled column shows 0 and the guide was successfully inserted.
  • If manual scripting continues to fail, use the Query Store “Force Plan” feature in SSMS as an alternative GUI-based method to achieve the same query optimization goal without manually defining sp_create_plan_guide parameters.

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

Troubleshooting Guide: Error 10520 – Plan Guide Parameter Mismatch

Why This Error Happens

This error occurs when creating a plan guide using sp_create_plan_guide with an @type value of OBJECT or SQL, while simultaneously passing a non-NULL value to a parameter that is only valid for the TEMPLATE type (typically @hints or @params). SQL Server 2025 strictly validates the relationship between the @type parameter and the other arguments in the stored procedure call, rejecting the request if an incompatible parameter combination is detected. Essentially, this is a syntax/logic error in the T-SQL script rather than a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Parameter

  • Open the T-SQL script or query that triggered Error 10520 in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Check the @type value defined in your EXEC sp_create_plan_guide statement (e.g., N'OBJECT', N'SQL', or N'TEMPLATE').
  • Cross-reference this with the @module_or_batch, @params, and @hints arguments to see which one contains an unexpected value.

Step 2: Correct the NULL Value Requirements

  • If @type is set to OBJECT, ensure the @params parameter is explicitly set to NULL, as object-based plan guides do not accept parameterized lists.
  • If @type is set to SQL or OBJECT, verify that @module_or_batch matches the exact text of the target query or object definition.
  • Update the script syntax: EXEC sp_create_plan_guide @name = N'Guide1', @stmt = N'SELECT...', @type = N'OBJECT', @module_or_batch = N'dbo.ProcName', @params = NULL, @hints = N'OPTION (RECOMPILE)';

Step 3: Validate Schema and Object References

  • Confirm that the specific stored procedure, function, or trigger referenced in @module_or_batch actually exists in the current database context.
  • Run sp_helptext 'dbo.ObjectName' to ensure the text matches exactly what you are passing into the @module_or_batch variable, as mismatches in whitespace or object names can trigger secondary type-validation errors in SQL Server 2025.

Step 4: Re-execute the Creation Script

  • Save the corrected script and re-run it against the target database.
  • Monitor the “Messages” tab in SSMS for a “Command(s) completed successfully” confirmation rather than the Error 10520 stack trace.

Alternative or Verification Steps

  • Verification: Query the sys.plan_guides system view (SELECT * FROM sys.plan_guides WHERE name = 'YourGuideName';) to confirm the is_disabled column is set to 0 and the guide was successfully inserted into the metadata.
  • Alternative: If manual creation continues to fail, use the Database Engine Tuning Advisor (DTA) in Windows 11/Server 2025 to generate the plan guide automatically, as it correctly handles the NULL/non-NULL parameter logic based on the workload file you provide.

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

Troubleshooting Guide: SQL Server Error 10519 – Plan Guide Hint Mismatch

Why This Error Happens

Error 10519 occurs when the @hints parameter passed to sp_create_plan_guide specifies query hints that are syntactically or semantically incompatible with the T-SQL statement defined in @stmt. This typically happens because the hint references objects, joins, or query constructs (such as OPTION (TABLE HINT...) targeting a table alias that doesn’t exist in the statement) that are not present at the exact @statement_start_offset. It can also occur if the statement text captured from the plan cache (via sp_get_query_template or extracted from sys.dm_exec_query_stats) does not character-for-character match the statement the hint engine expects, including whitespace, comments, or parameterization differences.

Step-by-Step Resolution Guide

Step 1: Validate the Exact Statement Text

  • Re-extract the statement using sp_get_query_template to ensure @stmt matches the parameterized form SQL Server expects.
  • Check for hidden characters, extra whitespace, or line breaks that may have been introduced when copying the query from SSMS or a log file.
  • Confirm the @statement_start_offset and @statement_end_offset (if using sp_create_plan_guide_from_handle) correctly bound the target statement.

Step 2: Test the Hint Independently

  • Run the original query manually in SSMS with the OPTION (...) clause appended directly to it (e.g., OPTION (RECOMPILE, OPTIMIZE FOR (@p1 = 1))).
  • If the query itself throws a syntax or binding error, the hint is invalid for that query shape — revise the hint’s table/index names or join hints to match actual object names in the FROM clause.
  • For TABLE HINT or INDEX hints, verify the referenced index still exists by running sp_helpindex 'YourTableName'.

Step 3: Simplify and Isolate the Hint Set

  • Remove hints one at a time from the @hints string and retry sp_create_plan_guide to isolate which specific hint is causing the conflict.
  • Avoid combining incompatible hints such as FORCESEEK with a table that has no usable index, or FAST n with aggregate-only queries.
  • Rebuild the @hints value using properly escaped single quotes, e.g., N'OPTION (MAXDOP 1)'.

Step 4: Recreate the Plan Guide with Corrected Parameters

  • Drop any partially created or conflicting plan guide:
  EXEC sp_control_plan_guide N'DROP', N'YourPlanGuideName';
  • Re-run sp_create_plan_guide with the corrected @stmt, @type, and @hints values, ensuring @type (OBJECT, SQL, or TEMPLATE) matches how the statement was originally captured.

Alternative or Verification Steps

  • Verify the fix by querying sys.plan_guides and checking that the is_disabled column is 0 and scope_type_desc matches your intended target.
  • If the error persists, bypass the plan guide approach and use an inline query hint directly in application code, or apply a USE PLAN guide instead, which is more tolerant of minor statement variations.

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

Troubleshooting Guide: Error 10518 – Insufficient Permissions to Control Plan Guide

Why This Error Happens

This error occurs when the user executing sp_control_plan_guide lacks the necessary ALTER permission on the underlying object (table, view, or stored procedure) that the plan guide references. SQL Server 2025 enforces strict permission validation on plan guides to prevent unauthorized users from altering query execution behavior for objects they don’t own. This typically happens after a permissions audit, role reassignment, or when a plan guide was created by a different user/service account with higher privileges than the current account attempting to manage it.

Step-by-Step Resolution Guide

Step 1: Identify the Plan Guide and Referenced Object

  • Run the following query to find the plan guide details and its associated object:
  SELECT name, scope_type_desc, [parameters], query_text 
  FROM sys.plan_guides 
  WHERE name = 'YourPlanGuideName';
  • Note the object (table/view/procedure) referenced in the query_text or OBJECT scope argument.

Step 2: Verify Current User Permissions

  • Check existing permissions on the referenced object using:
  SELECT * FROM fn_my_permissions('dbo.YourObjectName', 'OBJECT');
  • Confirm whether ALTER is missing from the returned permission set.

Step 3: Grant the Required ALTER Permission

  • Using SQL Server Management Studio (SSMS) or a sqlcmd session, run:
  GRANT ALTER ON OBJECT::dbo.YourObjectName TO [YourUserOrRole];
  • If the plan guide references multiple objects, repeat this grant for each one.
  • Alternatively, add the user to the db_ddladmin fixed database role if broader schema modification rights are appropriate for the environment.

Step 4: Re-execute spcontrolplan_guide

  • Retry the original command that failed, for example:
  EXEC sp_control_plan_guide N'DROP', N'YourPlanGuideName';
  • Confirm the command completes without returning Error 10518.

Step 5: Restart SQL Server Service (If Permissions Were Cached)

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or the named instance service.
  • Right-click and select Restart to clear any cached permission tokens.

Alternative or Verification Steps

  • Verify the fix by running sp_control_plan_guide again and confirming no error is returned; also re-check sys.plan_guides to ensure the is_disabled state changed as expected.
  • If the issue persists, log in with a sysadmin-level account temporarily to execute the plan guide command, then investigate whether permission inheritance via database roles was broken or misconfigured.

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

Troubleshooting Guide: SQL Server Error 10517 — Plan Guide Creation Permission Denied

Why This Error Happens

This error occurs because the login or user attempting to create a plan guide does not hold the ALTER permission on the target database, which is a mandatory requirement for the sp_create_plan_guide stored procedure to execute successfully. By default, only members of the dbowner or dbddladmin fixed database roles, or the sysadmin server role, possess sufficient rights to alter database-level objects like plan guides. This typically surfaces when a developer or application service account is granted limited read/write (dbdatareader/dbdatawriter) permissions but lacks the broader schema-altering privileges needed for query optimization hints.

Step-by-Step Resolution Guide

Step 1: Verify the Current User’s Permission Level

  • Open SQL Server Management Studio (SSMS) and connect to the instance using an account with sysadmin privileges.
  • Run the following query to check existing role memberships for the problematic user:
  • SELECT DP1.name AS DatabaseRoleName, DP2.name AS DatabaseUserName FROM sys.database_role_members DRM JOIN sys.database_principals DP1 ON DRM.role_principal_id = DP1.principal_id JOIN sys.database_principals DP2 ON DRM.member_principal_id = DP2.principal_id;
  • Confirm that the user attempting the CREATE PLAN GUIDE action is missing from the db_ddladmin or db_owner list.

Step 2: Grant the Required ALTER Permission

  • Navigate to Object Explorer > Databases > [Your Target Database] > Security > Users.
  • Right-click the specific user and select Properties, then navigate to the Membership page.
  • Alternatively, execute the following T-SQL command directly in a New Query window to grant the specific permission without adding the user to a broader role:
  • USE [YourDatabaseName]; GRANT ALTER TO [YourUsername];
  • For a more scalable approach, add the user to the db_ddladmin role using: ALTER ROLE db_ddladmin ADD MEMBER [YourUsername];

Step 3: Refresh the Connection and Clear Cached Credentials

  • Since Windows Server 2025 and Windows 11 clients often cache Kerberos tickets or SSMS connection tokens, permission changes may not apply to an already active session.
  • Close and restart the SQL Server Management Studio application entirely (do not just disconnect the object explorer).
  • If using an application connection pool (e.g., IIS or a .NET service), recycle the application pool or restart the relevant Windows Service to force a new connection handshake with the updated permissions.

Step 4: Re-attempt the Plan Guide Creation

  • Log back into the database using the updated credentials.
  • Re-run the specific sp_create_plan_guide command that previously failed.
  • Monitor the Messages tab in SSMS to ensure the command returns “Command(s) completed successfully” rather than Error 10517.

Alternative or Verification Steps

  • Verification: Execute SELECT * FROM sys.fn_my_permissions(NULL, 'DATABASE'); while logged in as the affected user to confirm that “ALTER” now appears in the returned permission list.
  • Alternative Fix: If granting ALTER is restricted by security policy, have a Database Administrator (DBA) with sysadmin rights run the plan guide creation script on behalf of the development team to bypass the need for elevated user permissions entirely.

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

Troubleshooting Guide: SQL Server Error 10516 – Plan Guide Compilation Failure

Why This Error Happens

Error 10516 occurs when SQL Server 2025 attempts to validate and compile the @module_or_batch parameter provided to sp_create_plan_guide, but the batch text, stored procedure, or trigger referenced contains syntax errors, unresolved object references, or deferred name resolution failures. This commonly happens when the statement text does not exactly match the original cached query plan text (including whitespace, comments, or collation differences), or when the target object was altered/dropped after the plan guide script was authored. It can also occur if the batch relies on session-specific SET options (like ANSI_NULLS or QUOTED_IDENTIFIER) that differ from those active when the plan guide is created.

Step-by-Step Resolution Guide

Step 1: Validate the Batch or Module Independently

  • Open a new query window in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Copy the exact @stmt or @module_or_batch text from your sp_create_plan_guide call and execute it standalone to confirm it compiles without errors.
  • Check for incomplete object references, missing schema prefixes (e.g., dbo.), or typos in table/column names.

Step 2: Match SET Options to the Original Plan Context

  • Run DBCC FREEPROCCACHE (in a test environment only) to clear stale plans that may conflict with validation.
  • Verify that SET ANSI_NULLS ON and SET QUOTED_IDENTIFIER ON are explicitly set before creating the plan guide, matching the settings used when the original query was cached:
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
EXEC sp_create_plan_guide
    @name = N'Guide1',
    @stmt = N'SELECT * FROM dbo.YourTable WHERE Id = @Id',
    @type = N'OBJECT',
    @module_or_batch = N'dbo.YourStoredProc',
    @params = NULL,
    @hints = N'OPTION (RECOMPILE)';

Step 3: Confirm the Referenced Object Still Exists and Is Valid

  • Query sys.objects and sys.sql_modules to ensure the stored procedure, function, or trigger named in @module_or_batch has not been dropped, renamed, or altered incompatibly:
SELECT OBJECT_ID('dbo.YourStoredProc'), definition 
FROM sys.sql_modules 
WHERE object_id = OBJECT_ID('dbo.YourStoredProc');
  • If the object was recently modified, regenerate the plan guide script using the current definition rather than a cached or archived version.

Step 4: Rebuild the Plan Guide Using spgetquery_template

  • Use sp_get_query_template to generate a parameterized version of the query text, ensuring exact syntax alignment with what SQL Server expects.
  • Re-run sp_create_plan_guide using the output from this procedure instead of a manually typed batch string.

Alternative or Verification Steps

  • Verify the fix by querying sys.plan_guides and checking that the is_disabled column is 0 and no scope_batch errors are returned: SELECT * FROM sys.plan_guides WHERE name = 'Guide1';
  • If errors persist, use sp_control_plan_guide @operation = N'DROP ALL' to clear conflicting guides, then recreate a single plan guide incrementally, testing compilation after each addition.

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

Troubleshooting Guide: SQL Server Error 10514 – Plan Guide Creation Failure

Why This Error Happens

Error 10514 occurs when the sp_create_plan_guide stored procedure is executed with the @type parameter set to OBJECT, but the @module_or_batch parameter contains a value exceeding the allowed size for this type (typically when the referenced module text is treated as a large object/LOB instead of a standard nvarchar reference). SQL Server enforces this restriction because OBJECT-type plan guides are meant to bind to a specific stored procedure, trigger, or function signature by name, not to hold the full batch text as a large character blob. This mismatch commonly happens due to incorrect parameter construction in application code, outdated T-SQL scripts carried over from legacy systems, or automated tools generating plan guides incorrectly after a migration to SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Plan Guide Script

  • Locate the exact sp_create_plan_guide call that triggered Error 10514 by checking the SQL Server Error Log or Extended Events session capturing error_reported.
  • Open SQL Server Management Studio (SSMS) and run the following to review recent plan guide attempts:
  SELECT * FROM sys.plan_guides WHERE is_disabled = 0;
  • Note the application or migration script name associated with the failed statement.

Step 2: Correct the @type and @moduleorbatch Parameters

  • Verify that when @type = 'OBJECT', the @module_or_batch parameter contains only the fully qualified object name (e.g., N'dbo.MyStoredProcedure'), not the full SQL batch text.
  • If the intention was to target an ad-hoc SQL statement or batch, change @type to SQL or TEMPLATE instead of OBJECT.
  • Example corrected syntax:
  EXEC sp_create_plan_guide
      @name = N'Guide1',
      @stmt = N'SELECT * FROM dbo.Orders WHERE OrderID = @id',
      @type = N'OBJECT',
      @module_or_batch = N'dbo.GetOrderById',
      @params = NULL,
      @hints = N'OPTION (RECOMPILE)';

Step 3: Rebuild the Plan Guide Using Correct Object References

  • Drop any existing malformed plan guide using:
  EXEC sp_control_plan_guide N'DROP', N'Guide1';
  • Recreate it with the corrected parameters validated in Step 2, ensuring the object name is under the nvarchar(4000) limit for OBJECT type bindings.
  • Deploy the corrected script through your standard change management or deployment pipeline (e.g., Azure DevOps, SSDT, or manual T-SQL execution).

Step 4: Validate Compatibility Level Settings

  • Confirm the database compatibility level supports the plan guide syntax used, since SQL Server 2025 may enforce stricter parsing rules under higher compatibility levels.
  • Check current compatibility level:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Adjust if necessary using ALTER DATABASE ... SET COMPATIBILITY_LEVEL = 160; (or the appropriate level for your environment) and retest the plan guide creation.

Alternative or Verification Steps

  • After applying the fix, re-run sp_create_plan_guide and confirm success by querying sys.plan_guides to ensure the new guide appears with is_disabled = 0 and no errors are logged.
  • If the error persists, bypass OBJECT type entirely by using @type = N'SQL' with the exact statement text and matching @params, which avoids the large object restriction altogether.

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

Troubleshooting Guide: SQL Server Error 10515 – Plan Guide Module Not Found

Why This Error Happens

This error occurs when SQL Server cannot locate the stored procedure, trigger, or user-defined function specified in the OBJECT_NAME parameter of the sp_create_plan_guide statement. The most common root causes are a misspelled or schema-qualified object name, the module being dropped or never created in the target database, or the executing login lacking the CONTROL or ALTER permission on the referenced module. Additionally, if the plan guide is created in a different database context than where the module actually resides, SQL Server will fail to resolve the reference.

Step-by-Step Resolution Guide

Step 1: Verify the Module Exists in the Target Database

  • Run the following query to confirm the object is present and spelled correctly:
  SELECT object_id, name, schema_id, type_desc 
  FROM sys.objects 
  WHERE name = 'YourModuleName';
  • Check that you are connected to the correct database context (USE YourDatabaseName;) before running sp_create_plan_guide.
  • Confirm the object type is SQL_STORED_PROCEDURE, SQL_TRIGGER, or SQL_SCALAR_FUNCTION, since plan guides only support these module types.

Step 2: Validate Schema Qualification in the Plan Guide Statement

  • Ensure the @module_or_batch parameter uses the fully qualified two-part name, e.g., dbo.usp_GetCustomerData rather than just usp_GetCustomerData.
  • Re-run the creation statement with explicit schema binding:
  EXEC sp_create_plan_guide 
      @name = N'PlanGuide1', 
      @stmt = N'SELECT * FROM dbo.Customers', 
      @type = N'OBJECT', 
      @module_or_batch = N'dbo.usp_GetCustomerData', 
      @params = NULL, 
      @hints = N'OPTION (RECOMPILE)';
  • If the schema was recently changed (e.g., via ALTER SCHEMA TRANSFER), update the reference accordingly.

Step 3: Check and Grant Required Permissions

  • Confirm the executing login has CONTROL permission on the object by running:
  SELECT * FROM fn_my_permissions('dbo.usp_GetCustomerData', 'OBJECT');
  • If permissions are missing, grant them using SQL Server Management Studio (SSMS) on Windows Server 2025 or via T-SQL:
  GRANT CONTROL ON OBJECT::dbo.usp_GetCustomerData TO [YourLoginName];
  • Restart the SQL Server Agent service if permission changes do not take effect immediately, via services.msc on Windows 11/Windows Server 2025.

Step 4: Rebuild the Module if Corrupted or Missing

  • If the object was dropped unintentionally, recreate it using the original deployment script located in your source control or C:\SQLScripts\Deployment\.
  • Validate the object compiles without errors by executing CREATE PROCEDURE or CREATE FUNCTION manually in a new query window in SSMS.
  • Re-attempt the sp_create_plan_guide execution once the module is successfully restored.

Alternative or Verification Steps

  • Verify the fix by querying sys.plan_guides to confirm the new plan guide appears with is_disabled = 0 and no associated errors.
  • If the issue persists, use sp_control_plan_guide with the DROP option to clear any orphaned plan guide references, then recreate the plan guide from scratch using the validated module name and schema.

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

Troubleshooting Guide: SQL Server Error 10512 — Plan Guide Cannot Be Created on Encrypted Object

Why This Error Happens

Error 10512 occurs because SQL Server’s Plan Guide feature relies on parsing the original T-SQL text of a stored procedure, trigger, or batch to match and apply a query plan. When a module is encrypted using WITH ENCRYPTION or protected via an Extended Protection mechanism, SQL Server cannot access the underlying object definition in sys.sql_modules, making it impossible to validate or bind the plan guide. This is a security-by-design restriction rather than a bug, corruption, or permissions failure.

Step-by-Step Resolution Guide

Step 1: Identify the Encrypted Object

  • Run the following query to confirm encryption status:
  SELECT OBJECT_NAME(object_id), definition, uses_ansi_nulls 
  FROM sys.sql_modules 
  WHERE object_id = OBJECT_ID('YourProcedureName');
  • If the definition column returns NULL, the object is confirmed encrypted.
  • Cross-check using sp_helptext 'YourProcedureName' — it will return “The object comments have been encrypted” if encryption is active.

Step 2: Decide Between Decryption or Alternative Tuning

  • If query plan tuning is critical and encryption is not a strict business requirement, script out the procedure and recreate it without the WITH ENCRYPTION clause:
  ALTER PROCEDURE YourProcedureName
  AS
  BEGIN
      -- original procedure body
  END;
  • If encryption must be retained (e.g., compliance or vendor-locked code), skip to Step 3 and use alternative tuning methods instead of Plan Guides.

Step 3: Apply Alternative Query Tuning Techniques

  • Since Plan Guides are blocked, use Query Store Hints (new in SQL Server 2022+/2025) to force a plan without needing the object unencrypted:
  EXEC sys.sp_query_store_set_hints 
      @query_id = <id>, 
      @query_hints = N'OPTION (MAXDOP 1)';
  • Alternatively, update statistics and indexes on underlying tables referenced by the encrypted module:
  UPDATE STATISTICS dbo.YourTable WITH FULLSCAN;
  • Ensure the correct non-clustered indexes exist to support the query’s predicates and joins, reducing reliance on manual plan forcing.

Step 4: Use a Temporary Unencrypted Copy for Analysis

  • In a non-production environment, restore a backup of the database and remove encryption temporarily using sp_decrypt_object (third-party tools) or re-scripting from source control.
  • Use SQL Server Profiler or Extended Events to capture the actual execution plan from the unencrypted copy, then manually implement equivalent indexing/hints in the production object via ALTER PROCEDURE.

Alternative or Verification Steps

  • Verify the fix by re-running the sp_create_plan_guide command against the modified (unencrypted) procedure — it should complete without Error 10512.
  • If encryption cannot be removed, confirm improved performance by checking sys.dm_exec_query_stats for reduced total_worker_time and total_logical_reads after applying indexing/statistics changes from Step 3.

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

Troubleshooting Guide: SQL Server Error 10513 – Object Referenced by Plan Guide

Why This Error Happens

Error 10513 occurs when an attempt is made to drop, alter, or modify a database object (such as a stored procedure, function, or trigger) that is currently bound to an existing plan guide. SQL Server enforces this dependency check to prevent orphaned plan guides from referencing objects that no longer exist in their original form. This is a referential integrity safeguard, not a corruption issue — the plan guide must be explicitly removed or redefined before the underlying object can be changed.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Plan Guide

  • Run the following query to find the plan guide name referenced in the error message:
  • SELECT name, scope_type_desc, statement, object_id FROM sys.plan_guides WHERE is_disabled = 0;
  • Cross-reference the name column with the plan guide name mentioned in the Error 10513 message text (the second %.*ls placeholder).

Step 2: Record the Plan Guide Definition

  • Before dropping anything, capture the full definition so it can be recreated later if needed:
  • SELECT name, query, scope_batch, hints FROM sys.plan_guides WHERE name = 'YourPlanGuideName';
  • Save the output (query text, scope batch, and hints) to a script file, e.g., C:\SQLBackups\PlanGuide_Backup.sql.

Step 3: Drop the Plan Guide Using spcontrolplan_guide

  • Execute the system stored procedure to remove the dependency:
  • EXEC sp_control_plan_guide N'DROP', N'YourPlanGuideName';
  • Confirm no error is returned and the plan guide no longer appears in sys.plan_guides.

Step 4: Perform the Original Object Modification

  • Retry the original ALTER, DROP, or CREATE OR ALTER statement that triggered Error 10513.
  • Example: ALTER PROCEDURE dbo.YourStoredProc AS ... or DROP PROCEDURE dbo.YourStoredProc;
  • Verify the operation completes without re-triggering the dependency error.

Step 5: Recreate the Plan Guide (If Still Required)

  • If the plan guide is still needed for query optimization, recreate it using the saved definition from Step 2.
  • EXEC sp_create_plan_guide N'YourPlanGuideName', N'YourSavedQueryText', N'OBJECT', N'dbo.YourStoredProc', NULL, N'OPTION (RECOMPILE)';
  • Adjust parameters to match the original hints and scope captured earlier.

Alternative or Verification Steps

  • Verify the fix by re-running SELECT * FROM sys.plan_guides WHERE name = 'YourPlanGuideName'; — it should either be absent (if not recreated) or show the new plan_guide_id with matching hints.
  • If the plan guide must remain in place and the object cannot be altered, consider creating a new object (e.g., a new stored procedure version) and updating the plan guide’s scope_batch to point to it instead of dropping the original.

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

Troubleshooting Guide: SQL Server Error 10510 – Duplicate Plan Guide Name

Why This Error Happens

Error 10510 occurs when a sp_create_plan_guide statement attempts to create a plan guide using a name that already exists within the same database’s sys.plan_guides catalog view. SQL Server enforces unique naming for plan guides at the database level, regardless of the scope (OBJECT, SQL, or TEMPLATE) the guide is applied to. This typically results from a deployment script being re-run without a cleanup step, multiple developers using identical naming conventions, or an automated CI/CD pipeline that does not check for existing objects before insertion.

Step-by-Step Resolution Guide

Step 1: Identify the Existing Plan Guide

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Run the following query to locate the conflicting name:
  SELECT name, scope_type, is_disabled, query_text 
  FROM sys.plan_guides 
  WHERE name = 'YourPlanGuideName';
  • Note the plan_guide_id and scope_type to determine if it is safe to remove or if it is actively being used in production.

Step 2: Drop the Conflicting Plan Guide (If Obsolete)

  • If the existing guide is outdated or part of a failed previous deployment, remove it using the system stored procedure.
  • Execute the following in the context of the target database (ensure you are not in master):
  EXEC sp_control_plan_guide N'DROP', N'YourPlanGuideName';
  • Verify Windows Server 2025 file permissions are not locking the .mdf/.ldf files if the drop command hangs, as this can indicate a separate I/O contention issue.

Step 3: Rename the New Plan Guide (If Guide Must Persist)

  • If the old plan guide must remain active, modify your creation script to use a unique identifier.
  • Update the @name parameter in your sp_create_plan_guide call:
  EXEC sp_create_plan_guide 
      @name = N'YourPlanGuideName_v2', 
      @stmt = N'SELECT * FROM dbo.YourTable', 
      @type = N'OBJECT', 
      ...
  • Ensure the new name adheres to standard SQL Server identifier rules and does not use reserved keywords.

Step 4: Clear Cached Deployment Scripts

  • If using Azure DevOps or GitHub Actions for Windows Server 2025 deployment, clear the pipeline’s artifact cache.
  • Ensure the deployment script includes a conditional check (IF EXISTS... DROP) prior to the CREATE statement to prevent future state mismatches.

Alternative or Verification Steps

  • Verification: Re-run the query from Step 1. If the result set returns the new guide name without an error, and sys.plan_guides shows is_disabled = 0, the fix was successful.
  • Alternative: If Error 10510 persists despite the name appearing unique, check for hidden whitespace or case-sensitivity collation conflicts in the database (SELECT DATABASEPROPERTYEX('YourDB', 'Collation')), as case-insensitive collations will flag “PlanGuideA” and “planguidea” as duplicates.

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

Troubleshooting Guide: SQL Server Error 10511 – Plan Guide Creation Failure

Why This Error Happens

This error occurs when calling sp_create_plan_guide with @type = 'OBJECT' while simultaneously supplying a non-NULL value for the @params parameter. The OBJECT type plan guide is designed for standalone stored procedures, triggers, or scalar functions, and SQL Server enforces a strict internal rule that parameterization data is irrelevant in this context because the object itself already defines its own parameter list. This typically happens due to a copy-paste error from a SQL or TEMPLATE type plan guide script, or a flaw in a migration script carried over from a previous SQL Server version into SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending T-SQL Script

  • Locate the specific sp_create_plan_guide call that triggered Error 10511 in the SQL Server Error Log or the client application output.
  • Check the @type argument in the script; confirm it is explicitly set to N'OBJECT'.
  • Note the value currently passed into the @params argument, as this is the variable causing the conflict.

Step 2: Correct the @params Argument

  • Edit the T-SQL script to set the @params argument strictly to NULL.
  • Ensure the syntax matches the required format: @params = NULL.
  • Example of corrected syntax:
  EXEC sp_create_plan_guide 
      @name = N'Guide1', 
      @stmt = N'SELECT * FROM dbo.Table1', 
      @type = N'OBJECT', 
      @module_or_batch = N'dbo.MyStoredProcedure', 
      @params = NULL, 
      @hints = N'OPTION (OPTIMIZE FOR UNKNOWN)';

Step 3: Validate the @moduleorbatch Context

  • Verify that the @module_or_batch parameter correctly points to the specific stored procedure or trigger name.
  • Ensure there are no trailing schema inconsistencies (e.g., missing dbo. prefix) that might cause SQL Server to misinterpret the object context during creation.

Step 4: Re-execute the Script via SSMS

  • Open SQL Server Management Studio (SSMS) 21 or later (required for full SQL Server 2025 compatibility).
  • Run the corrected script against the target database.
  • Monitor the “Messages” tab for a successful completion status rather than the 10511 error.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM sys.plan_guides WHERE name = 'Guide1'; to confirm the is_disabled column reads 0 and the plan guide now exists in the system catalog.
  • Alternative: If object-specific parameterization is actually required for your query, switch the plan guide type from OBJECT to SQL or TEMPLATE, which allows the @params argument to be populated correctly alongside the @type definition.

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

Troubleshooting Guide: SQL Server Error 10509 — Plan Guide Creation Failure

Why This Error Happens

Error 10509 occurs when the Transact-SQL statement supplied to sp_create_plan_guide (via @stmt or @module_or_batch combined with @statement_start_offset) does not match exactly, character-for-character, with the statement SQL Server expects to bind the plan guide to. This mismatch is commonly caused by extra whitespace, inconsistent line breaks, collation differences, or the use of unsupported constructs (such as certain USE statements, CTEs in the wrong context, or statements that reference objects in a way the optimizer cannot validate). It can also happen if the @statement_start_offset points to the wrong byte position within the batch, or if the plan guide type (OBJECT, SQL, or TEMPLATE) is incompatible with the statement structure provided.

Step-by-Step Resolution Guide

Step 1: Validate the Exact Text of the Target Statement

  • Extract the statement directly from sys.dm_exec_sql_text or sys.dm_exec_query_stats rather than retyping it manually.
  • Ensure there are no trailing spaces, tab characters, or mismatched line-ending styles (CRLF vs LF) between the captured text and the @stmt parameter.
  • Confirm the statement does not include a semicolon or batch terminator unless the original batch did.

Step 2: Verify Plan Guide Type and Offset Alignment

  • If using @type = 'OBJECT', confirm the @module_or_batch name matches an existing stored procedure, function, or trigger exactly, including schema prefix (e.g., dbo.usp_GetOrders).
  • If using @statement_start_offset, recalculate the byte offset using DATALENGTH() on the preceding text in Unicode, since SQL Server stores batch text as nvarchar.
  • Run the statement in isolation using SET SHOWPLAN_XML ON to confirm it compiles independently without errors.

Step 3: Check for Unsupported T-SQL Constructs

  • Remove or isolate statements containing RECEIVE, READTEXT, INSERT...EXEC, or multi-statement table-valued function calls, as these are ineligible for plan guides.
  • If the statement includes a Common Table Expression (CTE), ensure the plan guide is created against the full CTE-containing statement, not just the inner SELECT.
  • On Windows Server 2025 / Windows 11 hosts, confirm the SQL Server 2025 instance has the latest Cumulative Update applied, since several plan guide parsing fixes are delivered via CU patches (check via SELECT @@VERSION).

Step 4: Recreate the Plan Guide Using spcreateplan_guide Safely

  • Use the OBJECT type when targeting stored procedures instead of manually supplying offsets, as it eliminates offset mismatch errors entirely.
  • Example:
EXEC sp_create_plan_guide 
    @name = N'PG_FixedGuide',
    @stmt = N'SELECT * FROM dbo.Orders WHERE CustomerID = @CustomerID',
    @type = N'OBJECT',
    @module_or_batch = N'dbo.usp_GetOrders',
    @params = NULL,
    @hints = N'OPTION (RECOMPILE)';
  • Drop any failed or orphaned plan guide attempts first using sp_control_plan_guide @operation = N'DROP', @name = N'PG_FixedGuide'.

Alternative or Verification Steps

  • Query sys.plan_guides and check the is_disabled and scope_type_desc columns to confirm the guide was created successfully and is active.
  • If manual @stmt matching continues to fail, use Plan Guide from existing cached plan via sp_create_plan_guide_from_handle, which copies the exact query text and offset automatically from sys.dm_exec_query_stats, bypassing manual transcription errors entirely.

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

Troubleshooting Guide: Error 10507 – Cannot Create Plan Guide

Why This Error Happens

Error 10507 occurs when SQL Server’s query optimizer cannot match the statement text provided in @stmt against a valid, parsable T-SQL statement, or when @module_or_batch references an object that does not align with the specified statement. This typically happens due to syntax inconsistencies (extra whitespace, comments, or collation mismatches) between the plan guide definition and the actual cached query text. It can also occur if the target stored procedure, trigger, or function does not exist, has been altered since the plan guide was created, or if the statement type is unsupported for plan guide creation (such as DDL or control-of-flow statements).

Step-by-Step Resolution Guide

Step 1: Validate the Exact Statement Text

  • Extract the statement text directly from sys.dm_exec_sql_text or sys.dm_exec_query_stats rather than retyping it manually.
  • Ensure there are no trailing spaces, line-break differences, or encoding mismatches (ANSI vs. Unicode) between the captured text and @stmt.
  • Confirm the statement is a single, standalone SELECT, INSERT, UPDATE, or DELETE statement — plan guides do not support multi-statement batches unless using OBJECT or SQL type correctly.

Step 2: Verify the Target Object for @moduleorbatch

  • Run sys.sql_modules to confirm the stored procedure, function, or trigger referenced in @module_or_batch still exists and matches the expected schema name (e.g., dbo.usp_GetOrders).
  • Check that the object has not been recompiled or altered after the plan guide script was written, as this can shift internal statement offsets.
  • If using @type = 'OBJECT', ensure @module_or_batch contains only the object name, not the full statement text.

Step 3: Test Plan Guide Creation in Isolation

  • Open SQL Server Management Studio (SSMS) 21 on Windows Server 2025 and run sp_create_plan_guide manually against a simplified test case.
  • Use sp_help_plan_guide to inspect existing guides for syntax patterns that previously succeeded.
  • If the statement includes parameters, verify @params matches the exact data types and order declared in the original query.

Step 4: Rebuild the Plan Guide from Query Store

  • Navigate to Query Store (Database Properties > Query Store) and locate the problematic query_id.
  • Use the “Create Plan Guide from Query Store” feature (new in SQL Server 2025) instead of manual scripting to auto-generate accurate @stmt values.
  • Apply the generated script in a test environment before deploying to production.

Alternative or Verification Steps

  • After recreating the plan guide, run SELECT * FROM sys.plan_guides WHERE is_disabled = 0; to confirm it is active and scope_type matches your intended target.
  • If errors persist, use sp_control_plan_guide 'DROP_ALL' to clear conflicting guides, then reapply guides one at a time using Query Store–generated scripts to isolate the exact failing statement.

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

Troubleshooting Guide: SQL Server Error 10508 – Plan Guide Does Not Exist or Permission Denied

Why This Error Happens

Error 10508 occurs when SQL Server cannot locate the specified plan guide by name within the current database context, typically because the plan guide was already dropped, was never successfully created, or exists in a different database than the one currently in session scope. This can also surface when the executing login lacks the ALTER permission on the plan guide or sufficient rights on the database to view system catalog views like sys.plan_guides. Additionally, case sensitivity mismatches in the plan guide name or a failed/partial creation transaction can leave the object in an inconsistent state that triggers this error.

Step-by-Step Resolution Guide

Step 1: Verify the Plan Guide Actually Exists

  • Connect to the correct database context using USE [YourDatabaseName]; before running any plan guide commands.
  • Query the system view to confirm existence: SELECT name, scope_type, is_disabled FROM sys.plan_guides;
  • Check for exact name spelling, including case sensitivity if your instance uses a case-sensitive collation.

Step 2: Confirm You Are in the Correct Database Session

  • Run SELECT DB_NAME(); to validate the active database matches where the plan guide was originally created.
  • If the plan guide lives in a different database, switch context with USE [CorrectDatabaseName]; and retry the operation.
  • Remember that plan guides are database-scoped objects and do not carry over between databases, even on the same SQL Server 2025 instance.

Step 3: Validate User Permissions

  • Ensure the login has ALTER permission on the plan guide object or is a member of db_owner / db_ddladmin roles.
  • Run SELECT * FROM fn_my_permissions(NULL, 'DATABASE'); to inspect current session permissions.
  • If permissions are insufficient, grant access using: GRANT ALTER ON PLAN GUIDE::[YourPlanGuideName] TO [YourLoginName];

Step 4: Recreate the Plan Guide if Missing

  • If the plan guide was dropped or never fully committed, recreate it using sp_create_plan_guide with the original query text, type, and hints.
  • Double-check that the @name parameter matches exactly what your application or script references later.
  • Test the creation script in a non-production environment first to avoid syntax drift from SQL Server 2025 changes.

Step 5: Check for Replication or Mirroring Conflicts

  • On Windows Server 2025 environments using Always On Availability Groups, confirm the plan guide exists on the primary replica and has synced if using readable secondaries.
  • Plan guides are not automatically replicated in all configurations, so manual recreation may be required on each node.

Alternative or Verification Steps

  • Run sp_control_plan_guide @operation = 'DROP', @name = N'YourPlanGuideName'; in a test transaction to confirm the object is now recognized by SQL Server before attempting your original ALTER or DISABLE operation.
  • If the issue persists, use SQL Server Profiler or Extended Events to capture the exact T-SQL batch and database context at the moment of failure, which often reveals a connection string defaulting to the wrong database.

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

Troubleshooting Guide: SQL Server Error 10505 – Invalid Plan Guide Module Name

Why This Error Happens

This error occurs because the @module_or_batch parameter passed to sp_create_plan_guide requires a properly formatted two-part name consisting of schema_name.object_name when the plan guide type is set to OBJECT. SQL Server 2025 strictly validates this naming convention, and a common root cause is providing only the object name (e.g., MyProcedure) without its schema prefix, or using an incorrectly escaped/delimited string. Additionally, this can happen if the stored procedure or function referenced was created under a non-default schema, but the schema was omitted during the plan guide creation call.

Step-by-Step Resolution Guide

Step 1: Identify the Target Object and Its Schema

  • Run a query against sys.objects and sys.schemas to confirm the exact schema of the procedure or function you are targeting.
  • Use the following T-SQL command to verify: SELECT s.name AS SchemaName, o.name AS ObjectName FROM sys.objects o JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE o.name = 'YourObjectName';
  • Do not assume the object resides in dbo; in SQL Server 2025 environments, objects are frequently organized under custom schemas for security partitioning.

Step 2: Correct the Two-Part Naming Syntax

  • Modify your sp_create_plan_guide script to explicitly include the schema name followed by a period and the object name.
  • Ensure the value is properly enclosed in single quotes, formatted exactly as N'schema_name.object_name'.
  • Example of corrected syntax: EXEC sp_create_plan_guide @name = N'Guide1', @stmt = N'SELECT * FROM Table1', @type = N'OBJECT', @module_or_batch = N'Sales.GetOrderDetails', @params = NULL, @hints = N'OPTION (RECOMPILE)';

Step 3: Validate Database Context and Permissions

  • Confirm that the current database context (USE [YourDatabaseName];) matches the database where the schema and object actually reside.
  • Check that the executing user has ALTER permission on the schema in question, as insufficient permissions can sometimes trigger ambiguous parsing errors alongside naming issues.
  • Restart the query execution in SQL Server Management Studio (SSMS) after context verification to rule out cached session errors.

Step 4: Re-create the Plan Guide

  • Drop the failed plan guide attempt if a partial object was created using EXEC sp_control_plan_guide N'DROP', N'Guide1';.
  • Execute the corrected creation script with the validated two-part name from Step 1 and Step 2.

Alternative or Verification Steps

  • To verify the fix, query the sys.plan_guides catalog view (SELECT * FROM sys.plan_guides WHERE name = 'Guide1';) and ensure the is_disabled column returns 0 and the scope_type_desc matches OBJECT.
  • If the error persists despite correct syntax, use sp_help 'schema_name.object_name' to ensure there are no invisible trailing spaces or special Unicode characters in the schema or object name that are causing the two-part name parser to fail.

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

Troubleshooting Guide: SQL Server Error 10506 – Plan Guide Creation Failure

Why This Error Happens

Error 10506 occurs when the @stmt parameter passed to sp_create_plan_guide contains multiple T-SQL statements separated by semicolons or batch terminators, but the plan guide engine requires exactly one statement to bind to. This typically happens when a stored procedure, trigger, or ad-hoc batch is copied verbatim—including surrounding statements—into the @stmt argument instead of isolating the single target query. It can also occur if the @module_or_batch text was extracted incorrectly, picking up trailing or leading statements such as SET options, comments treated as separate tokens, or multi-statement CTEs that the parser interprets as distinct statements.

Step-by-Step Resolution Guide

Step 1: Isolate the Exact Statement Text

  • Open the original stored procedure, function, or batch using sp_helptext 'SchemaName.ProcedureName' in SSMS to get the precise, unmodified text.
  • Copy only the single SQL statement (e.g., one SELECT, INSERT, UPDATE, or DELETE) you intend to guide—do not include BEGIN...END, SET statements, or multiple semicolon-delimited queries.
  • Remove any trailing semicolons or stray batch separators (GO) that may have been accidentally included during copy-paste.

Step 2: Validate the Statement Independently

  • Run the isolated statement by itself in a new query window connected to the target database to confirm it executes without needing supporting context from adjacent statements.
  • Check for implicit multi-statement constructs such as common table expressions (CTEs) followed by a second query, or statements using WITH XMLNAMESPACES combined with a subsequent query—split these if necessary and guide only the primary query.
  • If the statement originally relied on local variables declared in prior lines (e.g., DECLARE @x INT), use the @params argument of sp_create_plan_guide instead of embedding the declaration in @stmt.

Step 3: Recreate the Plan Guide with Corrected Syntax

  • Execute the corrected call, for example:
  EXEC sp_create_plan_guide
      @name = N'Guide1',
      @stmt = N'SELECT * FROM dbo.Orders WHERE CustomerID = @CustomerID',
      @type = N'OBJECT',
      @module_or_batch = N'dbo.GetOrdersByCustomer',
      @params = NULL,
      @hints = N'OPTION (RECOMPILE)';
  • Ensure @type matches your scenario (OBJECT, SQL, or TEMPLATE) and that @module_or_batch references the correct fully-qualified object name when using OBJECT type.
  • If using SQL type for an ad-hoc batch, confirm the batch in @module_or_batch matches @stmt exactly, character-for-character, including whitespace.

Step 4: Check for Hidden Multi-Statement Triggers

  • Inspect whether the source text includes multiple statements separated by semicolons that aren’t visually obvious (e.g., inline comments spanning lines, or statements on the same line separated by ;).
  • Use SELECT LEN(@stmt) - LEN(REPLACE(@stmt, ';', '')) in a test script to count semicolons in your intended @stmt string—if the count exceeds what’s expected for a single statement (such as one trailing semicolon), trim accordingly.

Alternative or Verification Steps

  • Verify the fix by querying sys.plan_guides (SELECT * FROM sys.plan_guides WHERE name = 'Guide1') and confirming is_disabled = 0 with no associated errors in sys.plan_guides.query_text.
  • If manual isolation remains error-prone, use Query Store (sys.query_store_plan) to force a specific plan via sp_query_store_force_plan instead of manually crafting a plan guide, as this avoids the single-statement parsing requirement entirely.

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

Troubleshooting Guide: Error 10504 — Cannot Create Plan Guide Due to Incorrect @hints Parameter

Why This Error Happens

This error occurs when the @hints parameter supplied to sp_create_plan_guide contains a malformed or incomplete OPTION clause, causing the SQL Server parser to reject the query hint string. Common root causes include missing parentheses around the hint list, incorrect hint syntax (e.g., using a deprecated or misspelled hint name), or copying the hint string from a USE PLAN XML output without properly escaping embedded quotes. Since SQL Server 2025 validates the @hints string at creation time rather than execution time, any syntax deviation from the expected OPTION ( <query_hint> [ ,...n ] ) format immediately triggers Error 10504.

Step-by-Step Resolution Guide

Step 1: Validate the Raw @hints String Syntax

  • Extract the exact string passed to @hints in your sp_create_plan_guide call.
  • Confirm it starts with N'OPTION ( and ends with a closing )' — both parentheses must be present and balanced.
  • Check for stray single quotes inside the string; these must be escaped by doubling them ('') since the whole hint is itself a Unicode string literal.

Step 2: Test the Hint Clause Independently

  • Take the inner hint content (without the OPTION() wrapper) and run it against a sample query directly in SQL Server Management Studio (SSMS), e.g.:
  SELECT * FROM Sales.Orders OPTION (RECOMPILE, MAXDOP 1);
  • If this standalone query fails, the hint keyword itself is invalid, deprecated, or misspelled — cross-reference against the current list of supported query hints in SQL Server 2025 Books Online.
  • Pay special attention to hints that require specific formatting, such as OPTIMIZE FOR (@variable = value) or USE PLAN N'<XML_Plan>', which need correct nested quoting.

Step 3: Rebuild the Plan Guide Statement Cleanly

  • Reconstruct the full sp_create_plan_guide call from scratch rather than editing a copy-pasted version, to avoid hidden characters or truncation.
  • Use a properly formatted template:
  EXEC sp_create_plan_guide
      @name = N'MyPlanGuide',
      @stmt = N'SELECT * FROM Sales.Orders WHERE CustomerID = @id',
      @type = N'OBJECT',
      @module_or_batch = N'dbo.GetOrdersByCustomer',
      @params = NULL,
      @hints = N'OPTION (RECOMPILE)';
  • If using USE PLAN, generate the XML plan via sys.dm_exec_query_plan first, then wrap it carefully, doubling any single quotes found in the XML.

Step 4: Check Compatibility Level and Deprecated Hints

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'; to confirm the database compatibility level supports the hints used.
  • Remove or replace any hints flagged as deprecated in SQL Server 2025 (check sys.dm_exec_query_plan warnings or the Deprecated Features Extended Event).

Alternative or Verification Steps

  • After recreating the plan guide, verify it loads correctly by querying SELECT * FROM sys.plan_guides WHERE name = 'MyPlanGuide'; and confirming is_disabled = 0.
  • If the issue persists, use sp_control_plan_guide @operation = N'DROP', @name = N'MyPlanGuide' to clear any corrupted entry, then reapply the guide using the Database Engine Tuning Advisor to auto-generate a syntactically valid @hints string.

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

Troubleshooting Guide: SQL Server Error 10502 — “Cannot create plan guide” (Statement Mismatch)

Why This Error Happens

Error 10502 occurs when SQL Server cannot locate an exact, character-for-character match between the Transact-SQL text specified in @stmt and the actual statement found inside the object referenced by @module_or_batch. This mismatch is typically caused by extra whitespace, differing collation settings, comments, or formatting changes (such as line breaks or tabs) introduced during copy-pasting from Management Studio or a source control tool. It can also occur if the stored procedure, trigger, or batch was altered after the plan guide script was originally generated, leaving the @stmt parameter referencing outdated T-SQL syntax.

Step-by-Step Resolution Guide

Step 1: Extract the Exact Statement Text Programmatically

  • Do not manually retype the query from the procedure definition.
  • Run the following to pull the raw definition directly from the engine to avoid hidden character discrepancies:
  SELECT OBJECT_DEFINITION(OBJECT_ID('YourSchema.YourProcedureName'));
  • Copy the output exactly as returned, including any leading whitespace, into your @stmt parameter.

Step 2: Validate Hidden Characters and Collation Settings

  • Open the extracted text in a hex-aware editor (like VS Code) to check for non-printable Unicode characters (e.g., zero-width spaces) that often get introduced when copying from web browsers or PDFs.
  • Verify that the @stmt variable is declared as NVARCHAR(MAX) and not VARCHAR, as implicit conversion can alter character matching logic.
  • Check the database collation using SELECT DATABASE_COLLATION_NAME to ensure it matches the server default if the plan guide is being applied across linked environments.

Step 3: Use spgetquery_template to Normalize Syntax

  • Instead of manually writing the @stmt string for parameterized queries, use the system procedure sp_get_query_template to generate a normalized version of the query.
  • This system procedure automatically handles the parameterization and whitespace formatting required by the Plan Guide engine, significantly reducing the risk of a string mismatch.
  • Pass the output of this procedure directly into the @stmt parameter of sp_create_plan_guide.

Step 4: Clear Plan Cache and Re-deploy

  • Since Windows Server 2025 environments often retain stale execution plans in memory, clear the specific plan cache for the database to prevent conflicts with the old, unlinked guide attempt:
  DBCC FREEPROCCACHE;
  • Re-run the sp_create_plan_guide script with the newly validated @stmt text from Step 1.

Alternative or Verification Steps

  • Verify: Query the sys.plan_guides system view and check the is_disabled column to ensure the new guide was created successfully and is active (value 0).
  • Alternative: If manual creation continues to fail, use SQL Server Management Studio’s native “Create Plan Guide” context-menu option (right-click on a query in the Query Store reports), as this GUI tool automatically captures the exact binary string of the statement, bypassing manual transcription errors entirely.

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

Troubleshooting Guide: Error 10503 – “Operation ‘%.*ls’ is not allowed”

Why This Error Happens

Error 10503 in SQL Server 2025 typically occurs when an operation is attempted on a database object that is in an inconsistent or restricted state, such as attempting DDL changes on a table involved in an active replication topology, Change Data Capture (CDC) session, or while a database snapshot is in progress. This error is also commonly triggered when attempting schema modifications on memory-optimized tables or columnstore indexes during an unsupported transaction isolation level. Additionally, it can surface when a database is in a READ_ONLY state, is part of an Availability Group secondary replica, or has pending schema lock conflicts from concurrent sessions.

Step-by-Step Resolution Guide

Step 1: Identify the Database and Object State

  • Open SQL Server Management Studio (SSMS) and run the following query to check database state:
  • SELECT name, state_desc, is_read_only FROM sys.databases WHERE name = 'YourDatabaseName';
  • Confirm whether the database is READ_ONLY, RESTORING, or part of an Availability Group.
  • Check if the target table is enabled for CDC or Replication using sys.tables and sys.change_tracking_tables.

Step 2: Disable Conflicting Features Temporarily

  • If CDC is enabled, disable it before running the operation using:
  • EXEC sys.sp_cdc_disable_table @source_schema = 'dbo', @source_name = 'YourTable', @capture_instance = 'all';
  • If the table is part of transactional replication, pause the Log Reader Agent via SQL Server Agent in SSMS under SQL Server Agent > Jobs.
  • For Availability Groups, ensure you are executing the command on the Primary Replica only, not a read-only secondary.

Step 3: Verify Database Compatibility and Isolation Level

  • Check the database compatibility level, as SQL Server 2025 defaults to 170; legacy syntax may trigger this error.
  • Run: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If using memory-optimized tables, ensure the session isolation level is set to SNAPSHOT rather than READ COMMITTED:
  • ALTER DATABASE YourDatabaseName SET READ_COMMITTED_SNAPSHOT ON;

Step 4: Check for Active Locks or Blocking Sessions

  • Navigate to Activity Monitor in SSMS or run sp_who2 to identify blocking session IDs (SPIDs).
  • Kill the blocking process ID (PID) if it is safe to do so:
  • KILL [SPID];
  • Retry the original DDL or DML operation once the schema lock is released.

Step 5: Re-enable Previously Disabled Features

  • Once the operation completes successfully, re-enable CDC or resume the Replication Log Reader Agent to restore data synchronization.
  • EXEC sys.sp_cdc_enable_table @source_schema = 'dbo', @source_name = 'YourTable', @role_name = NULL;

Alternative or Verification Steps

  • Verification: Re-run the original query or stored procedure that triggered Error 10503; if successful, check the SQL Server Error Log (via SSMS Management > SQL Server Logs) to confirm no residual state conflicts remain.
  • Alternative: If the error persists on a specific table, create a new table with the identical schema, migrate the data using INSERT INTO ... SELECT, and rename the tables to swap them, bypassing the locked object state entirely.

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

Troubleshooting Guide: SQL Server Error 10501 – Plan Guide Type Not Allowed

Why This Error Happens

This error occurs when the sp_create_plan_guide stored procedure is called with a @type parameter value that does not match one of the three valid plan guide types: OBJECT, SQL, or TEMPLATE. In most cases, this is caused by a typo, incorrect casing sensitivity in a case-sensitive collation, or a legacy script written for an older SQL Server version that used a deprecated or malformed type string. Additionally, this can surface during database migration scripts to SQL Server 2025 where syntax validation has become stricter.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Script Causing the Error

  • Open SQL Server Management Studio (SSMS) and check the Messages tab for the full error output, noting the plan guide name and the invalid type string reported.
  • Locate the specific EXEC sp_create_plan_guide statement in your deployment script or stored procedure that triggered Error 10501.
  • Use SELECT * FROM sys.plan_guides; to check if a partial or corrupted entry was left behind from a failed execution.

Step 2: Correct the @type Parameter Value

  • Verify the @type argument is wrapped in single quotes and matches one of the three accepted values exactly: N'OBJECT', N'SQL', or N'TEMPLATE'.
  • Check for hidden whitespace or non-printable characters copied from documentation or external sources (e.g., N'SQL ' with a trailing space will fail).
  • Ensure the parameter is passed as an nvarchar literal using the N prefix, as SQL Server 2025 enforces stricter Unicode string validation for system procedure inputs.

Step 3: Validate Dependent Parameters Match the Type

  • If using @type = N'OBJECT', confirm @module_or_batch contains a valid schema-qualified object name (e.g., N'dbo.usp_GetOrders') rather than a raw SQL string.
  • If using @type = N'SQL', confirm @module_or_batch contains the literal SQL statement text, not an object reference.
  • Re-run the corrected sp_create_plan_guide statement in a test environment (non-production) first to confirm the syntax resolves cleanly.

Step 4: Clean Up Orphaned Plan Guides (If Applicable)

  • Run EXEC sp_control_plan_guide N'DROP', N'<PlanGuideName>'; to remove any broken or half-created plan guide entries from the failed attempt.
  • Restart the SQL Server 2025 instance service via Services.msc on Windows Server 2025/Windows 11 only if the plan guide cache appears stuck (rarely required).

Alternative or Verification Steps

  • Verify the fix by querying SELECT name, scope_type_desc FROM sys.plan_guides WHERE name = '<YourPlanGuideName>'; and confirming the scope_type_desc column shows OBJECT, SQL, or TEMPLATE correctly.
  • If the error persists despite correct syntax, use the Database Engine Tuning Advisor (DTA) to auto-generate a valid plan guide template as a reference, then adapt your custom script to match its exact parameter structure.

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

Troubleshooting Guide: Error 10346 – Assembly Hash Not Trusted (SQL Server 2025)

Why This Error Happens

This error occurs because SQL Server 2025 enforces strict CLR assembly trust validation, and the assembly hash in question has not been registered via sys.sp_add_trusted_assembly. This typically happens when clr strict security is enabled (the default and non-configurable behavior in modern SQL Server versions) and the assembly was signed with a certificate or asymmetric key that lacks a corresponding login with UNSAFE ASSEMBLY permission. It can also occur after migrating a database from an older SQL Server instance where the assembly trust model was less restrictive, or if the DLL file was altered/recompiled, causing its hash to no longer match any trusted entry.

Step-by-Step Resolution Guide

Step 1: Identify the Untrusted Assembly Hash

  • Capture the exact hash value reported in Error 10346 (the 0x%.*ls portion of the message).
  • Run the following query to compute the hash of your assembly file manually if needed:
SELECT HASHBYTES('SHA2_512', 
    (SELECT * FROM OPENROWSET(BULK 'C:\Assemblies\YourAssembly.dll', SINGLE_BLOB) AS x));
  • Compare this output against the hash in the error message to confirm you are targeting the correct file.

Step 2: Add the Assembly to the Trusted List

  • Use sys.sp_add_trusted_assembly to explicitly whitelist the hash at the instance level.
  • Example command:
EXEC sys.sp_add_trusted_assembly 
    @hash = 0xAB12CD34EF56..., 
    @description = N'Trusted Custom Assembly - YourAssembly.dll';
  • Ensure you run this in the context of a login with sysadmin or CONTROL SERVER permission, as trusted assembly management is instance-wide, not database-scoped.

Step 3: Validate CLR Strict Security Configuration

  • Confirm clr strict security is enabled (default in SQL Server 2025) by running:
EXEC sp_configure 'clr strict security';
  • If the assembly is signed, verify an associated asymmetric key/certificate exists in the master database with a login granted UNSAFE ASSEMBLY:
CREATE ASYMMETRIC KEY YourAssemblyKey FROM EXECUTABLE FILE = 'C:\Assemblies\YourAssembly.dll';
CREATE LOGIN YourAssemblyLogin FROM ASYMMETRIC KEY YourAssemblyKey;
GRANT UNSAFE ASSEMBLY TO YourAssemblyLogin;

Step 4: Redeploy or Re-Register the Assembly

  • Drop and recreate the CLR assembly in the target database to force SQL Server to re-evaluate trust status:
DROP ASSEMBLY IF EXISTS YourAssembly;
CREATE ASSEMBLY YourAssembly 
    FROM 'C:\Assemblies\YourAssembly.dll' 
    WITH PERMISSION_SET = SAFE;
  • Restart the SQL Server service via Services.msc (Windows Server 2025 / Windows 11) if the trust change does not take effect immediately: net stop MSSQLSERVER && net start MSSQLSERVER.

Alternative or Verification Steps

  • Verify the fix by querying sys.trusted_assemblies to confirm the hash is listed, then re-run the operation that originally triggered Error 10346.
  • If the error persists, check Windows Event Viewer (Application log, source “MSSQLSERVER”) for underlying file corruption or access-denied messages, and re-copy the DLL from a verified source to rule out file tampering.

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

Troubleshooting Guide: Error 10347 – CLR Is Not Enabled on This Instance

Why This Error Happens

This error occurs because the clr enabled configuration option is set to 0 (disabled) by default in SQL Server 2025 for security hardening purposes. Any attempt to create, execute, or reference CLR-based objects (such as assemblies, SQLCLR functions, triggers, or stored procedures) will fail until this configuration is explicitly enabled via sp_configure. Additionally, this can occur if the instance is running in a restricted security context (such as Azure SQL-style containment policies) that blocks advanced configuration changes.

Step-by-Step Resolution Guide

Step 1: Verify Current CLR Configuration State

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the target instance.
  • Run the following query to check the current state:
  • EXEC sp_configure 'clr enabled';
  • Look at the run_value column; if it shows 0, CLR integration is confirmed disabled.

Step 2: Enable Advanced Options and CLR Integration

  • Advanced options must be shown before clr enabled can be modified.
  • Execute the following T-SQL script in a new query window:
  • EXEC sp_configure 'show advanced options', 1;
  • RECONFIGURE;
  • EXEC sp_configure 'clr enabled', 1;
  • RECONFIGURE;

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

  • While clr enabled is typically a dynamic setting (no restart needed), some locked-down configurations on Windows Server 2025 require a service bounce to apply fully.
  • Open Services.msc (Windows Server 2025/Windows 11) and locate SQL Server (MSSQLSERVER) or the named instance.
  • Right-click and select Restart.
  • Alternatively, use PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force

Step 4: Check CLR Strict Security Settings

  • SQL Server 2025 enforces clr strict security by default, which requires assemblies to be signed or trusted.
  • Run: EXEC sp_configure 'clr strict security';
  • If set to 1 and you are loading an unsigned assembly, add it to the trusted assemblies list:
  • EXEC sp_add_trusted_assembly @hash = <assembly_hash>, @description = N'My CLR Assembly';

Alternative or Verification Steps

  • Verify the Fix: Run EXEC sp_configure 'clr enabled'; again and confirm both config_value and run_value display 1. Then attempt to create a simple test CLR function to ensure no further errors appear.
  • Alternative Approach: If sp_configure fails due to policy restrictions (common in locked-down Windows Server 2025 deployments), check Group Policy or SQL Server Policy-Based Management (PBM) settings that may be overriding instance-level configuration, and consult your DBA security team for an exception.

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

Troubleshooting Guide: SQL Server Error 10344 – Trusted Assemblies Internal Table Access Failure

Why This Error Happens

This error occurs when the SQL Server Database Engine cannot read or write to the internal system table that tracks CLR trusted assemblies, typically due to corruption in the system catalog or the mssqlsystemresource database. It can also be triggered by insufficient permissions on the SQL Server service account when accessing internal metadata, or by a corrupted master database following an improper shutdown or failed upgrade. In some cases, a mismatch between the SQL Server binary version and the resource database version (common after a partial patch to SQL Server 2025) causes the internal table lookup to fail with an HRESULT error.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Service Account Permissions

  • Open Services.msc on Windows Server 2025 / Windows 11 and locate the SQL Server (MSSQLSERVER) service.
  • Confirm the service account has full control over the SQL Server data directory, typically located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA.
  • Right-click the folder, go to Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read/Write/Modify permissions.
  • Restart the SQL Server service after applying permission changes.

Step 2: Check for Resource Database Corruption

  • Run the following query in SQL Server Management Studio (SSMS) to validate the resource database version:
  • SELECT SERVERPROPERTY('ResourceVersion') AS ResourceVersion, SERVERPROPERTY('ProductVersion') AS ProductVersion;
  • If the versions do not match, this confirms a mismatched or corrupted mssqlsystemresource.mdf file.
  • Replace the resource database files by copying a clean mssqlsystemresource.mdf and .ldf from the SQL Server 2025 installation media into the Binn\Templates folder, then restart the instance in single-user mode to apply.

Step 3: Run DBCC CHECKDB on System Databases

  • Open a new query window in SSMS and execute:
  • DBCC CHECKDB ('master') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • Review the output for allocation or consistency errors related to system tables.
  • If corruption is confirmed, restore the master database from a verified backup taken prior to the error occurring.

Step 4: Rebuild or Repair the System Databases

  • If no clean backup is available, rebuild system databases using the setup media:
  • Setup.exe /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=<YourAdminAccount> /SAPWD=<StrongPassword>
  • This resets the master, model, and msdb databases, which also restores the Trusted Assemblies internal table structure.
  • Reapply any custom configurations, logins, and trusted assembly entries (via sys.sp_add_trusted_assembly) after the rebuild.

Step 5: Apply the Latest Cumulative Update

  • Download and install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • This ensures any known internal table access bugs related to CLR integration are patched.
  • Reboot the Windows Server 2025 / Windows 11 host after installation to finalize the update.

Alternative or Verification Steps

  • To verify the fix, run SELECT * FROM sys.trusted_assemblies; in SSMS — if the query returns results (or an empty set) without throwing Error 10344, the internal table is accessible again.
  • As an alternative, if the issue persists after rebuilding system databases, perform a full uninstall and clean reinstall of the SQL Server 2025 instance, restoring user databases only from backup to avoid carrying over the corrupted system catalog.

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

Troubleshooting Guide: Error 10345 – “The assembly hash is already trusted”

Why This Error Happens

This error occurs when attempting to add a trusted assembly hash to sys.trusted_assemblies using sp_add_trusted_assembly, but an entry with that exact hash value already exists in the trusted assemblies catalog. SQL Server 2025 maintains a unique constraint on assembly hashes to prevent duplicate trust entries, so re-registering the same CLR assembly binary without first checking its existing trust status triggers this conflict. This commonly happens during deployment scripts, migration processes, or CLR assembly updates where cleanup of prior trust entries was not performed.

Step-by-Step Resolution Guide

Step 1: Verify the Existing Trusted Assembly Entry

  • Open SQL Server Management Studio (SSMS) and connect to the SQL Server 2025 instance.
  • Run the following query to check if the hash already exists:
  SELECT * FROM sys.trusted_assemblies WHERE hash = 0x<YourAssemblyHash>;
  • Confirm whether the description column matches your expected assembly name/version.

Step 2: Remove the Duplicate Entry (If Safe to Do So)

  • If the existing entry is outdated or no longer needed, drop it using:
  EXEC sp_drop_trusted_assembly @hash = 0x<YourAssemblyHash>;
  • Ensure no production CLR objects (assemblies, stored procedures, or functions) are actively dependent on this hash before dropping it.
  • Re-run your original sp_add_trusted_assembly script after the duplicate is removed.

Step 3: Update Deployment Scripts to Prevent Re-Trust Attempts

  • Modify your deployment or CI/CD pipeline scripts (e.g., PowerShell, DACPAC, or T-SQL migration files) to include a conditional check before insertion:
  IF NOT EXISTS (SELECT 1 FROM sys.trusted_assemblies WHERE hash = 0x<YourAssemblyHash>)
  BEGIN
      EXEC sp_add_trusted_assembly @hash = 0x<YourAssemblyHash>, @description = N'YourAssemblyDescription';
  END
  • Save this updated script template in your source control repository to avoid recurrence in future deployments.

Step 4: Restart the CLR Integration Context (If Needed)

  • If the assembly still fails to load correctly after cleanup, restart the SQL Server service via Windows Server 2025 Services console (services.msc) or run:
  Restart-Service -Name 'MSSQLSERVER'
  • This clears any cached CLR execution context tied to the old trusted hash.

Alternative or Verification Steps

  • Verify the fix by querying sys.trusted_assemblies again and confirming only one entry exists for the intended hash, then test loading the CLR assembly via CREATE ASSEMBLY without errors.
  • As an alternative, if duplicate hashes persist across multiple databases, consider using sys.sp_add_trusted_assembly with a unique @description tag per environment to simplify auditing and prevent future hash collisions during multi-instance deployments.

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

Troubleshooting Guide: SQL Server Error 10343 — CLR Strict Security Blocking Assembly Creation

Why This Error Happens

This error occurs because SQL Server 2025 enforces the clr strict security option by default, which requires all CLR assemblies marked as SAFE or EXTERNAL_ACCESS to be signed with a certificate or asymmetric key mapped to a login with the UNSAFE ASSEMBLY permission. Unsigned assemblies, or assemblies lacking a trusted trust-chain association, are rejected outright regardless of their declared permission set. Essentially, SQL Server no longer distinguishes between SAFE and UNSAFE when clr strict security is enabled — every assembly is treated as potentially unsafe until proven otherwise via signing.

Step-by-Step Resolution Guide

Step 1: Verify the Current CLR Strict Security Configuration

  • Open SQL Server Management Studio (SSMS) or sqlcmd connected to your Windows Server 2025 instance.
  • Run the following to check current settings:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'clr strict security';
  • Confirm the run_value is set to 1, which confirms strict enforcement is active and causing the block.

Step 2: Sign the Assembly with a Certificate or Asymmetric Key

  • Generate a self-signed certificate (or use an existing enterprise cert) in the master database:
  USE master;
  CREATE CERTIFICATE AssemblySignCert
  WITH SUBJECT = 'CLR Assembly Signing Certificate';
  • Create a login mapped to this certificate and grant it the UNSAFE ASSEMBLY permission:
  CREATE LOGIN AssemblySignLogin FROM CERTIFICATE AssemblySignCert;
  GRANT UNSAFE ASSEMBLY TO AssemblySignLogin;
  • Sign your DLL assembly file using sn.exe (Strong Name tool) or embed the certificate reference directly if deploying via CREATE ASSEMBLY ... FROM 'path' WITH PERMISSION_SET = SAFE.

Step 3: Re-deploy the Assembly in the Target Database

  • Back up the certificate and private key from master, then import it into the target user database:
  USE [YourDatabase];
  CREATE CERTIFICATE AssemblySignCert
  FROM FILE = 'C:\Certs\AssemblySignCert.cer'
  WITH PRIVATE KEY (FILE = 'C:\Certs\AssemblySignCert.pvk', DECRYPTION BY PASSWORD = 'YourStrongPassword');
  • Re-run your CREATE ASSEMBLY or ALTER ASSEMBLY statement with SAFE or EXTERNAL_ACCESS permission set.
  • Confirm no errors are returned and the assembly appears in sys.assemblies.

Step 4: (Optional) Adjust clr strict security as a Temporary Workaround

  • If immediate signing isn’t feasible, you can disable strict enforcement — not recommended for production:
  EXEC sp_configure 'clr strict security', 0;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER for the change to take effect.
  • Treat this as a stop-gap only; plan to implement proper certificate signing afterward.

Alternative or Verification Steps

  • Verify the fix by querying sys.assembly_modules and sys.certificates to confirm the assembly is linked to a trusted, signed certificate with the correct login permissions.
  • If the error persists after signing, check that the certificate’s login (not just the user) has UNSAFE ASSEMBLY granted at the server level, since permission mismatches between database-level users and server-level logins are a common root cause of continued failures.

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

Troubleshooting Guide: Error 10341 – Assembly Cannot Be Loaded (User-Defined Assemblies Not Supported)

Why This Error Happens

This error occurs when a CLR-based user-defined assembly (via CREATE ASSEMBLY or sp_execute_external_script dependencies) is deployed against a database configured or templated for Azure SQL Database compatibility, where CLR integration is restricted. On-premises SQL Server 2025 instances can occasionally inherit this restriction when a database is migrated from, or configured to mimic, an Azure SQL Database compatibility level. Additionally, this can surface if the SQL Server instance has CLR strict security enabled incorrectly alongside a containerized or cloud-replicated database configuration that disables custom assembly loading by default.

Step-by-Step Resolution Guide

Step 1: Verify the Database Compatibility Level and Engine Edition

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check the engine edition:
  SELECT SERVERPROPERTY('EngineEdition');
  • An EngineEdition value of 5 indicates Azure SQL Database (or a database restored/configured to behave like one), which blocks custom assemblies. Confirm you are not unintentionally targeting an Azure-mode database file.

Step 2: Enable CLR Integration on the Standalone Instance

  • On your Windows Server 2025 / Windows 11 host, open a new query window in SSMS and run:
  sp_configure 'show advanced options', 1;
  RECONFIGURE;
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Ensure you are connected to the correct on-premises instance (e.g., localhost\SQLEXPRESS or SERVERNAME\MSSQLSERVER), not a linked Azure SQL Database endpoint.

Step 3: Recreate the Database Under Full SQL Server Engine Edition

  • If the database was migrated from Azure SQL Database or created using an Azure-compatible template, export the schema and data using the Generate Scripts wizard in SSMS.
  • Create a new database on the full SQL Server 2025 engine:
  CREATE DATABASE MyLocalDB;
  • Re-import the data and re-run the CREATE ASSEMBLY statement against this new on-premises database.

Step 4: Check CLR Strict Security and Trust Settings

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and confirm the assembly DLL exists and is not blocked by Windows (right-click → Properties → Unblock).
  • Run the following to allow the assembly if strict security is enabled:
  EXEC sp_configure 'clr strict security', 0;
  RECONFIGURE;
  • Alternatively, sign the assembly with a certificate and create a trusted login mapped to that certificate for production environments.

Step 5: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to apply configuration changes.

Alternative or Verification Steps

  • Verify the fix by re-running CREATE ASSEMBLY MyAssembly FROM 'C:\Assemblies\MyAssembly.dll' WITH PERMISSION_SET = SAFE; — it should complete without Error 10341.
  • If the target environment must remain Azure SQL Database, the alternative is to refactor the CLR logic into native T-SQL, Azure Functions, or an external compute service, since user-defined assemblies are permanently unsupported in that engine edition.

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

Troubleshooting Guide: SQL Server Error 10342 – Assembly Load Restricted to SAFE Permission Set

Why This Error Happens

This error occurs because the installed edition of SQL Server 2025 (typically Express or Web edition) enforces a restriction that only allows assemblies with the SAFE permission set to be loaded into the database. When a CLR assembly is registered or altered with EXTERNAL_ACCESS or UNSAFE permissions, the engine rejects the operation because those permission levels require Standard, Enterprise, or Developer edition licensing. Additionally, this can surface if the clr strict security configuration is enforcing stricter validation on assemblies that are not properly signed or trusted.

Step-by-Step Resolution Guide

Step 1: Verify the Current SQL Server Edition

  • Open SQL Server Management Studio (SSMS) and run the following query:
  • SELECT SERVERPROPERTY('Edition') AS Edition, SERVERPROPERTY('EngineEdition') AS EngineEdition;
  • Confirm if the result returns “Express Edition” or “Web Edition,” as these do not support EXTERNAL_ACCESS or UNSAFE assemblies.
  • Check the installation media or Microsoft licensing portal to confirm the SKU purchased for the Windows Server 2025 instance.

Step 2: Modify the Assembly Permission Set to SAFE

  • If upgrading the edition is not immediately possible, alter the assembly to use the supported permission level.
  • Run the following T-SQL command in your target database:
  • ALTER ASSEMBLY YourAssemblyName WITH PERMISSION_SET = SAFE;
  • If the assembly requires file I/O or network access (which SAFE does not allow), you must proceed to Step 3 instead.

Step 3: Upgrade the SQL Server Edition (If Required)

  • If the application logic strictly requires EXTERNAL_ACCESS or UNSAFE permissions, you must upgrade the edition.
  • Navigate to the SQL Server Installation Center via the Start Menu on Windows Server 2025.
  • Select Maintenance > Edition Upgrade.
  • Enter a valid Product Key for Standard or Enterprise edition to lift the SAFE-only restriction.

Step 4: Check CLR Strict Security Settings

  • For SQL Server 2017 and later (including 2025), verify if clr strict security is blocking the load due to unsigned modules.
  • Run sp_configure 'clr strict security'; to check the current value.
  • If assemblies are trusted internally, add the assembly to the trusted list using sys.sp_add_trusted_assembly rather than disabling security features globally.

Alternative or Verification Steps

  • Verification: After altering the permission set or upgrading the edition, run SELECT * FROM sys.assemblies; to confirm the permission_set_desc column now matches the required level (SAFE, EXTERNAL_ACCESS, or UNSAFE) without throwing an error upon database restart.
  • Alternative: If upgrading the edition is not feasible, refactor the CLR code to remove dependencies on external resources (like file systems or network sockets) so it can function correctly within the SAFE sandbox environment.

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

Troubleshooting Guide: SQL Server Error 10339 – Assembly Verification Failure

Why This Error Happens

Error 10339 occurs when SQL Server 2025 attempts to load or verify a CLR assembly but cannot read the physical file from disk, typically because the file has been moved, deleted, or renamed since it was registered. This can also happen due to insufficient NTFS permissions for the SQL Server service account on the file or folder path, file corruption from an incomplete transfer or disk error, or the file being locked by another process (such as antivirus real-time scanning) during the read operation. Additionally, path length restrictions or incorrect UNC path resolution on Windows Server 2025 can trigger this failure when the assembly resides on a network share.

Step-by-Step Resolution Guide

Step 1: Confirm the Assembly File Path and Existence

  • Run SELECT name, file_name FROM sys.assembly_files; in SSMS to identify the exact physical path SQL Server expects.
  • Navigate to that path in Windows Explorer (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\Assemblies\) and confirm the .dll file actually exists there.
  • If the file is missing or was relocated, note the correct current location for use in later steps.

Step 2: Verify NTFS Permissions and Service Account Access

  • Right-click the assembly folder, go to Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has at least Read & Execute permissions.
  • Use icacls "C:\Path\To\Assembly\Folder" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)RX in an elevated PowerShell/Command Prompt to apply permissions if missing.
  • If the file resides on a network share, ensure the share-level permissions and UNC path are accessible by the service account, not just a mapped drive letter.

Step 3: Check for File Locks or Antivirus Interference

  • Open Resource Monitor (resmon.exe) and search the CPU tab for handles matching the assembly file name to identify any process locking it.
  • Add an antivirus exclusion for the SQL Server Binn\Assemblies directory and any custom assembly storage folders to prevent real-time scanning conflicts.
  • Restart the SQL Server service (net stop MSSQLSERVER && net start MSSQLSERVER) after making exclusion changes to clear any stale locks.

Step 4: Rebuild or Re-register the Assembly

  • If the file is confirmed corrupted or unreadable, drop the broken reference using DROP ASSEMBLY [AssemblyName]; (ensure no dependent objects first).
  • Re-create the assembly from a known-good source file using CREATE ASSEMBLY [AssemblyName] FROM 'C:\CorrectPath\Assembly.dll' WITH PERMISSION_SET = SAFE;.
  • Validate the SQL Server CLR integration setting is enabled by running sp_configure 'clr enabled', 1; RECONFIGURE;.

Alternative or Verification Steps

  • Re-run the original query or stored procedure that triggered Error 10339 and confirm it executes without the “Could not read from the physical file” message.
  • As an alternative, export the assembly binary directly from sys.assembly_files using SELECT content FROM sys.assembly_files WHERE assembly_id = ID; and manually rewrite it to disk if the source file is permanently lost.

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

Troubleshooting Guide: SQL Server Error 10340 – DROP ASSEMBLY Failed

Why This Error Happens

Error 10340 occurs when SQL Server’s CLR integration engine cannot remove an assembly because it is still referenced by dependent objects such as user-defined types, triggers, stored procedures, or functions. This can also happen if the assembly’s underlying file on disk is locked, corrupted, or if the internal metadata in the sys.assemblies catalog view has become inconsistent due to an interrupted transaction. Additionally, insufficient permissions (lacking CONTROL permission on the assembly or ALTER ANY ASSEMBLY at the database level) will trigger this specific HRESULT failure.

Step-by-Step Resolution Guide

Step 1: Identify Dependent Objects

  • Open SQL Server Management Studio (SSMS) and connect to the instance running on Windows Server 2025.
  • Run the following query to check for dependencies before attempting the drop again:
  SELECT referencing_major_id, referencing_minor_id 
  FROM sys.sql_expression_dependencies 
  WHERE referenced_id = OBJECT_ID('YourAssemblyName');
  • Alternatively, query sys.assembly_modules and sys.assembly_types to find linked CLR procedures or types that must be dropped first.

Step 2: Verify and Elevate Permissions

  • Ensure the executing login has the CONTROL permission on the specific assembly.
  • Run this T-SQL command to grant the necessary rights if missing:
  GRANT CONTROL ON ASSEMBLY::YourAssemblyName TO [YourUserName];
  • Check Windows Event Viewer (Applications and Services Logs > SQL Server) for any underlying Access Denied errors related to the SQL Server service account.

Step 3: Force Drop Dependent Objects

  • Manually script and drop all dependent CLR Stored Procedures, Functions, Triggers, or Aggregates identified in Step 1.
  • Execute the following sequence to clear the dependency chain:
  DROP PROCEDURE IF EXISTS dbo.YourCLRProcedure;
  DROP TYPE IF EXISTS dbo.YourCLRType;
  • Attempt the DROP ASSEMBLY YourAssemblyName; command again immediately after clearing dependencies.

Step 4: Restart the SQL Server Service

  • If the error persists due to a “ghost” lock on the metadata, restart the SQL Server service via the Services console (services.msc) on Windows Server 2025.
  • Alternatively, use PowerShell to restart the service cleanly:
  Restart-Service -Name 'MSSQLSERVER' -Force
  • This clears any cached execution contexts that might be holding a phantom reference to the assembly.

Alternative or Verification Steps

  • Verify the Fix: Run SELECT * FROM sys.assemblies WHERE name = 'YourAssemblyName'; after the drop command executes; if the query returns zero rows, the assembly has been successfully removed.
  • Alternative Solution: If the assembly remains “stuck” due to corruption, use ALTER DATABASE [YourDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; to force a clean state, execute the drop command, and then switch the database back to MULTI_USER mode.

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

Troubleshooting Guide: SQL Server Error 10338 – Assembly Verification Failure

Why This Error Happens

Error 10338 occurs when SQL Server attempts to load or verify a CLR assembly (typically during a CREATE ASSEMBLY, ALTER ASSEMBLY, or automatic reload at startup) but cannot physically access the DLL file referenced in the assembly metadata. This is most commonly caused by the underlying file being moved, deleted, or renamed after the assembly was registered, or by the SQL Server service account lacking NTFS read permissions on the file path. In some cases, this also surfaces due to file-level corruption, antivirus quarantine actions, or the file residing on a network share/drive letter that is no longer mapped or accessible to the service account.

Step-by-Step Resolution Guide

Step 1: Identify the Broken File Path

  • Run the following query to find the exact path SQL Server is trying to access: SELECT name, file_name FROM sys.assembly_files;
  • Cross-reference the name column with the parent assembly: SELECT a.name AS AssemblyName, f.file_name FROM sys.assemblies a JOIN sys.assembly_files f ON a.assembly_id = f.assembly_id;
  • Note the exact directory path returned (e.g., C:\SQLAssemblies\MyAssembly.dll).

Step 2: Verify File Existence and Permissions

  • Open File Explorer or PowerShell and navigate to the path identified in Step 1.
  • If the file is missing, locate the original source .dll and copy it back to the exact original path.
  • Right-click the file, go to Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER or a custom domain service account) has at least Read & Execute permissions.
  • If permissions are missing, run this in an elevated PowerShell to grant access: icacls "C:\SQLAssemblies\MyAssembly.dll" /grant "NT SERVICE\MSSQLSERVER:(RX)"

Step 3: Check for Antivirus or EDR Interference

  • Open your antivirus/EDR console (Windows Defender, CrowdStrike, etc.) and check the Quarantine or Protection History logs for the specific .dll filename.
  • If quarantined, restore the file to its original location.
  • Add an exclusion rule for the SQL Server data/assembly directory to prevent future lock/quarantine issues: Add-MpPreference -ExclusionPath "C:\SQLAssemblies\"

Step 4: Drop and Re-Register the Assembly

  • If the file path has permanently changed or the original binary is lost, you must re-create the assembly reference.
  • Drop the broken reference (ensure no dependencies break first): DROP ASSEMBLY MyAssembly;
  • Re-add it using the CREATE ASSEMBLY command pointing to the current, verified file location: CREATE ASSEMBLY MyAssembly FROM 'C:\NewPath\MyAssembly.dll' WITH PERMISSION_SET = SAFE;

Step 5: Restart the SQL Server Service

  • Once permissions are fixed, restart the service to clear any cached file handle locks.
  • Open Services.msc, locate SQL Server (MSSQLSERVER), and select Restart.
  • Alternatively, use PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Verify the Fix: Run SELECT * FROM sys.assemblies WHERE name = 'MyAssembly'; and attempt to execute a stored procedure or function dependent on that assembly to confirm it loads without throwing Error 10338.
  • Alternative Fix: If the physical file is irrecoverable and you only have the compiled logic in a database backup, restore the assembly binary directly from sys.assembly_files.content using a binary export script from a working environment, then rewrite it to disk at the expected path before retrying the CREATE ASSEMBLY command.

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

Troubleshooting Guide: SQL Server Error 10337 – “An Internal Error Occurred”

Why This Error Happens

Error 10337 in Microsoft SQL Server 2025 typically occurs when the Service Broker or internal dialog management subsystem encounters a conflict while processing queued messages, often due to corrupted system catalog metadata or insufficient permissions on the msdb database. This can also be triggered by orphaned endpoints or certificates used for internal authentication becoming invalid after a Windows Server 2025 security patch or OS upgrade. In some cases, memory pressure combined with a corrupted transaction log file prevents SQL Server’s internal components from completing a handshake, resulting in this generic internal error.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server 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 msdb and master databases.
  • Run the following T-SQL to check role membership:
  EXEC sp_helprolemember 'db_owner';

Step 2: Rebuild Service Broker Configuration

  • Check if Service Broker is enabled on the affected database:
  SELECT is_broker_enabled FROM sys.databases WHERE name = 'YourDBName';
  • If disabled or corrupted, re-enable it with:
  ALTER DATABASE YourDBName SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
  • Restart the SQL Server service afterward to apply changes.

Step 3: Check and Repair System Database Integrity

  • Run DBCC CHECKDB against msdb and master to rule out corruption:
  DBCC CHECKDB ('msdb') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is found, restore msdb from a known good backup located typically at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\.

Step 4: Clear and Rebuild SQL Server Internal Cache

  • Open SQL Server Management Studio (SSMS) and execute:
  DBCC FREESYSTEMCACHE('ALL');
  • Restart the SQL Server (MSSQLSERVER) service via PowerShell:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the operation that originally triggered Error 10337 and check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for recurrence.
  • If the error persists, apply the latest Cumulative Update (CU) for SQL Server 2025 from Microsoft, as internal errors are frequently patched in CU releases addressing Service Broker and catalog metadata bugs.

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

Troubleshooting Guide: SQL Server Error 10335 – CLR Loaded in an Unsupported Manner

Why This Error Happens

This error occurs when an extended stored procedure (XP) or an OLE Automation object running inside the SQL Server process calls into managed code before the SQL Server CLR integration host has properly initialized and loaded the Common Language Runtime. Because SQL Server requires strict control over how the CLR is hosted within sqlservr.exe to manage memory, threading, and security contexts, any third-party or legacy XP that bypasses this hosting process causes a conflict. This is commonly triggered by outdated third-party DLLs, legacy COM/OLE automation extended stored procedures (like sp_OACreate), or custom XPs that were compiled for older, unsupported .NET Framework integration patterns.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Extended Stored Procedure or Module

  • Check the SQL Server Error Log (via SSMS or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for the specific module name referenced alongside Error 10335.
  • Run the following query to list all non-standard extended stored procedures currently loaded:
  SELECT name, type_desc FROM sys.all_objects WHERE type = 'X';
  • Cross-reference the identified DLL with Windows Event Viewer (Application Log) for load failures tied to clr.dll or mscoree.dll.

Step 2: Disable Legacy OLE Automation Procedures

  • If the error correlates with sp_OACreate, sp_OAMethod, or similar OLE Automation calls, disable this feature entirely, as it is deprecated and unsupported in modern CLR hosting models.
  • Execute the following in a query window:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'Ole Automation Procedures', 0;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Migrate the Extended Stored Procedure to a SQLCLR Assembly

  • Rewrite the legacy XP logic as a proper SQLCLR Stored Procedure/Assembly rather than an unmanaged DLL calling into .NET.
  • Ensure the new assembly is registered correctly using CREATE ASSEMBLY and that clr enabled is set to 1 via sp_configure.
  • Verify the target .NET runtime version matches the CLR version supported by SQL Server 2025 (ensure compatibility with .NET 8/9 integration hosting).

Step 4: Validate CLR Strict Security Settings

  • In SQL Server 2025, clr strict security is enabled by default and cannot be disabled; ensure any custom assembly is signed with a certificate or asymmetric key mapped to a login with UNSAFE ASSEMBLY permissions if required.
  • Run the following to check current permissions mapping:
  SELECT * FROM sys.server_principals WHERE name = 'YourCertificateLogin';

Alternative or Verification Steps

  • Verification: Restart the SQL Server service and re-run the specific stored procedure or application process that originally triggered the error. Monitor the SQL Server Error Log to confirm Error 10335 no longer appears during execution.
  • Alternative: If the third-party vendor providing the XP does not offer a CLR-compliant update, isolate the specific database or workload using that XP onto a separate, legacy-compatible instance to prevent it from destabilizing the primary production environment.

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

Troubleshooting Guide: SQL Server Error 10336 — Failed to Enqueue Task to Start CLR

Why This Error Happens

This error occurs when SQL Server attempts to initialize the Common Language Runtime (CLR) worker thread during startup but cannot enqueue the task due to insufficient worker thread availability or memory pressure within the SQLOS scheduler. It is commonly triggered by resource exhaustion at boot time, restrictive max worker threads configuration settings, or a transient failure in the SQLOS scheduler queue caused by high concurrent startup load. In most cases, this is a non-fatal warning because SQL Server automatically falls back to starting the CLR on-demand when it is first needed (e.g., during execution of a CLR-enabled stored procedure or function).

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration is Actually Required and Enabled

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to check if CLR is enabled:
  EXEC sp_configure 'clr enabled';
  • If the run_value is 0, enable it explicitly:
  sp_configure 'show advanced options', 1;
  RECONFIGURE;
  sp_configure 'clr enabled', 1;
  RECONFIGURE;

Step 2: Check and Adjust Max Worker Threads Configuration

  • Insufficient worker threads at startup is the leading cause of enqueue failures.
  • Check the current setting:
  EXEC sp_configure 'max worker threads';
  • If set too low (non-zero and under 512 for most modern workloads), reset it to allow SQL Server to auto-configure based on CPU count:
  sp_configure 'max worker threads', 0;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER for the change to take effect.

Step 3: Review System Resource Allocation on Windows Server 2025 / Windows 11

  • Open Task Manager or Resource Monitor during the SQL Server startup window to confirm the host is not experiencing CPU or memory saturation from other services.
  • Check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for memory pressure warnings (Error 17890) occurring near the 10336 event.
  • If low memory is detected, adjust the Min/Max Server Memory settings in SSMS under Server Properties > Memory to leave adequate headroom for the OS and CLR threads.

Step 4: Repair or Validate SQL Server CLR Component Files

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and confirm sqlservr.exe and related CLR hosting DLLs (e.g., sqlclrproviders.dll) are present and not flagged by antivirus/EDR software.
  • If corruption is suspected, run a repair via Control Panel > Programs > Microsoft SQL Server 2025 > Change > Repair.
  • Restart the SQL Server service after repair completes.

Alternative or Verification Steps

  • To verify the fix, restart the SQL Server service and check the ERRORLOG for the absence of Event ID 10336; then manually trigger CLR by executing any CLR-based stored procedure to confirm successful on-demand initialization.
  • If the error persists but CLR functions correctly on-demand (confirmed via SELECT * FROM sys.dm_clr_loaded_assemblies; returning expected results), this warning can safely be treated as informational and suppressed via custom error-handling in your monitoring/alerting system.

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

Why This Error Happens

This error occurs when SQL Server’s SQLCLR hosting layer fails to initialize the Common Language Runtime’s resource monitoring interface, typically due to a corrupted or mismatched .NET runtime installation on the host. It can also result from insufficient permissions on the CLR hosting policy files, or from a conflict between the version of the .NET Framework/Runtime that SQL Server 2025 expects and what is actually registered in Windows Server 2025 or Windows 11. In some cases, this is triggered by antivirus or endpoint protection software interfering with CLR assembly loading at the process level.

Step-by-Step Resolution Guide

Step 1: Verify the .NET Runtime Version and Integrity

  • Confirm that the correct .NET Runtime version required by SQL Server 2025 is installed by running dotnet --list-runtimes in an elevated Command Prompt.
  • Check C:\Windows\Microsoft.NET\Framework64\ for the presence of the expected CLR version folder (e.g., v4.0.30319).
  • If files appear missing or corrupted, repair the .NET installation via Settings > Apps > Installed Apps, locate the Microsoft .NET runtime, and select Modify > Repair.

Step 2: Reset CLR Integration in SQL Server

  • Open SQL Server Management Studio (SSMS) and run the following to confirm CLR is enabled:
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Restart the SQL Server service via SQL Server Configuration Manager to force CLR re-initialization.
  • If the error persists, disable and re-enable CLR integration to clear any cached state:
  sp_configure 'clr enabled', 0;
  RECONFIGURE;
  sp_configure 'clr enabled', 1;
  RECONFIGURE;

Step 3: Check Permissions on CLR Hosting Files

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ and confirm the SQL Server service account has Read & Execute permissions on all DLLs in this folder.
  • Verify permissions on C:\Windows\Microsoft.NET\Framework64\<version>\ are not restricted by a recently applied Group Policy or security baseline.
  • Use icacls to grant explicit permissions if needed:
  icacls "C:\Windows\Microsoft.NET\Framework64\v4.0.30319" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)RX

Step 4: Exclude SQL Server Processes from Antivirus Scanning

  • Add sqlservr.exe and the Binn directory to your antivirus/EDR exclusion list.
  • Temporarily disable real-time protection and restart the SQL Server service to test if the error disappears.
  • Re-enable protection once exclusions are confirmed to resolve the issue.

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

  • Download and install the latest Cumulative Update (CU) from the Microsoft Update Catalog, as this issue has been linked to known CLR hosting bugs in early builds.
  • Reboot the server after installation to ensure the CLR hosting components are fully refreshed.

Alternative or Verification Steps

  • After applying the fixes, run a test CLR-based stored procedure or query sys.dm_clr_loaded_assemblies to confirm CLR integration loads without error 10333 appearing in the SQL Server error log.
  • If the issue persists, consider performing a full repair installation of SQL Server 2025 via Control Panel > Programs > Microsoft SQL Server 2025 > Repair, which will restore any corrupted CLR hosting binaries.

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

Troubleshooting Guide: SQL Server Error 10334 — Unchecked Assembly Data After Compatibility Level Change

Why This Error Happens

This error occurs when a database’s compatibility level is changed, causing SQL Server to flag binary data in CLR user-defined type (UDT) or user-defined aggregate columns as “unchecked” because the serialization format validation rules differ between compatibility levels. SQL Server cannot guarantee that previously stored binary data conforms to the validation logic of the new compatibility level, so it marks affected tables and views via the has_unchecked_assembly_data flag rather than risk silent data corruption. This is a protective mechanism, not actual data corruption, but it requires explicit administrator validation before the flag is cleared.

Step-by-Step Resolution Guide

Step 1: Identify All Affected Objects

  • Run the following query against the affected database to locate flagged objects:
  • SELECT name, has_unchecked_assembly_data FROM sys.tables WHERE has_unchecked_assembly_data = 1;
  • SELECT name, has_unchecked_assembly_data FROM sys.views WHERE has_unchecked_assembly_data = 1;
  • Note every schema and object name returned, as each one will require explicit validation in the next step.

Step 2: Validate the Assembly Data Using DBCC CHECKTABLE

  • For each flagged table, execute DBCC CHECKTABLE ('SchemaName.TableName') WITH DATA_PURITY, EXTENDED_LOGICAL_CHECKS; to force SQL Server to re-validate the CLR binary data against the current compatibility level.
  • Review the output carefully for any consistency errors related to assembly or UDT columns.
  • If no errors are reported, SQL Server automatically clears the has_unchecked_assembly_data flag for that table upon successful completion.

Step 3: Re-register or Rebuild Affected CLR Assemblies (If Errors Persist)

  • If DBCC CHECKTABLE reports binary format violations, drop and re-create the associated CLR assembly using ALTER ASSEMBLY AssemblyName FROM 'C:\Assemblies\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure the assembly DLL version matches the serialization format expected by the new compatibility level (check SELECT compatlevel FROM sys.databases WHERE name = 'YourDB';).
  • Re-run DBCC CHECKTABLE on the same objects to confirm the flag clears after the assembly is updated.

Step 4: Review Compatibility Level Change Necessity

  • If multiple objects fail validation, consider temporarily reverting the compatibility level using ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = <previous_level>; while you remediate CLR assemblies in a test environment.
  • Test the compatibility level change in a staging environment before reapplying it to production.

Alternative or Verification Steps

  • Re-query sys.tables and sys.views for has_unchecked_assembly_data = 0 across all previously flagged objects to confirm the issue is fully resolved.
  • If assemblies cannot be immediately fixed, isolate affected tables from application write operations until DBCC CHECKTABLE validation completes successfully to prevent accidental use of unvalidated binary data.

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

Troubleshooting Guide: SQL Server Error 10332 – Assembly .NET Framework Version Mismatch

Why This Error Happens

This error occurs when a SQL CLR assembly registered in SQL Server was compiled against a version of the .NET Framework (or .NET runtime) that does not match the runtime version currently loaded by the SQL Server Database Engine. SQL Server 2025 enforces strict CLR host runtime compatibility checks, so assemblies built with newer target framework versions (or an incompatible .NET build) will fail validation during CREATE ASSEMBLY or execution. This typically happens after a SQL Server upgrade, an OS .NET Framework update, or when developers compile assemblies targeting a mismatched .NET Target Framework in Visual Studio.

Step-by-Step Resolution Guide

Step 1: Identify the Assembly’s Target Framework Version

  • Open the project in Visual Studio and check Project Properties > Application > Target Framework.
  • Alternatively, inspect the DLL metadata using PowerShell: [System.Reflection.AssemblyName]::GetAssemblyName("C:\Path\To\Assembly.dll").Version
  • Cross-reference this with the CLR version SQL Server 2025 expects (check via SELECT @@VERSION; and SQL Server documentation for supported .NET runtime).

Step 2: Recompile the Assembly Against the Correct Framework

  • In Visual Studio, change the Target Framework to match the version supported by SQL Server 2025 (commonly .NET Framework 4.8 or the corresponding .NET CLR integration version specified in SQL Server 2025 release notes).
  • Rebuild the solution in Release mode to ensure a clean binary.
  • Avoid targeting preview or unsupported .NET versions (e.g., .NET 9 preview builds) not yet certified for SQL CLR hosting.

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

  • Run the following T-SQL to remove the outdated assembly:
  • DROP ASSEMBLY YourAssemblyName;
  • Re-register the newly compiled assembly:
  • CREATE ASSEMBLY YourAssemblyName FROM 'C:\Path\To\Assembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure clr strict security and clr enabled configurations are properly set via sp_configure.

Step 4: Verify SQL Server CLR Configuration

  • Confirm CLR integration is enabled: EXEC sp_configure 'clr enabled', 1; RECONFIGURE;
  • Check installed .NET runtime versions on Windows Server 2025 using dotnet --list-runtimes in Command Prompt.
  • Install or repair the required .NET Framework version via Windows Features (Turn Windows features on or off > .NET Framework 4.8 Advanced Services) if missing.

Step 5: Restart SQL Server Services

  • Open SQL Server Configuration Manager.
  • Restart the SQL Server (MSSQLSERVER) service to reload the CLR host environment.
  • Confirm no residual errors appear in SQL Server Error Logs (EXEC sp_readerrorlog;).

Alternative or Verification Steps

  • Run SELECT * FROM sys.assemblies; to confirm the assembly is listed without a “broken” or “invalid” status, and test executing a stored procedure or function that references the assembly.
  • If recompiling is not feasible, consider using the SQL Server CLR Strict Security exception list or deploying an older-compatible build of the assembly sourced from a working environment.

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

Troubleshooting Guide: Error 10330 – ALTER ASSEMBLY Serialization Layout Change

Why This Error Happens

This error occurs when a SQLCLR assembly containing persisted user-defined types (UDTs) or user-defined aggregates is updated with a new version that changes the physical layout of a type marked with Format.Native or Format.UserDefined serialization. SQL Server stores the binary representation of these types on disk, so any modification to field order, data types, [Serializable] attributes, or struct/class layout invalidates existing persisted data. SQL Server blocks the ALTER ASSEMBLY operation to prevent silent data corruption in tables that already contain instances of the affected type.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Type and Dependent Objects

  • Run the following query to find tables/columns using the CLR type:
SELECT t.name AS TypeName, c.name AS ColumnName, o.name AS TableName
FROM sys.columns c
JOIN sys.types t ON c.user_type_id = t.user_type_id
JOIN sys.objects o ON c.object_id = o.object_id
WHERE t.is_assembly_type = 1;
  • Note every table, column, and index that references the persisted type before proceeding.

Step 2: Export and Decouple Existing Data

  • Export the data from affected columns to a staging table or external format (e.g., JSON, binary export via bcp) since the CLR layout is changing.
SELECT * INTO dbo.Staging_OldTypeData FROM dbo.YourTable;
  • Drop the columns, indexes, or constraints referencing the old assembly type:
ALTER TABLE dbo.YourTable DROP COLUMN YourCLRColumn;

Step 3: Drop and Recreate the Assembly

  • Drop the old assembly and its dependent UDT/UDAGG definitions:
DROP TYPE dbo.YourCLRType;
DROP ASSEMBLY YourAssemblyName;
  • Deploy the new assembly version with the updated serialization layout:
CREATE ASSEMBLY YourAssemblyName
FROM 'C:\Deploy\YourAssembly.dll'
WITH PERMISSION_SET = SAFE;

CREATE TYPE dbo.YourCLRType EXTERNAL NAME YourAssemblyName.[YourCLRType];

Step 4: Reload and Reattach Data

  • Add the column(s) back using the new type definition:
ALTER TABLE dbo.YourTable ADD YourCLRColumn dbo.YourCLRType;
  • Migrate data back from the staging table, converting/mapping fields to match the new layout as needed, then drop the staging table once verified.

Alternative or Verification Steps

  • Verify the fix by running ALTER ASSEMBLY YourAssemblyName FROM 'C:\Deploy\YourAssembly.dll'; again on a test instance — it should complete without Error 10330.
  • If data export/reload is not feasible due to volume, consider versioning the type (e.g., create YourCLRType_v2) and run both assemblies side-by-side temporarily, migrating data gradually via a scheduled job instead of a single cutover.

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

Troubleshooting Guide: SQL Server Error 10331 – CLR Type Generic Inheritance Not Supported

Why This Error Happens

This error occurs when a SQLCLR assembly registered in SQL Server 2025 contains a type marked with [SqlUserDefinedType] or [Serializable] that derives from a generic base class (e.g., MyType<T>). SQL Server’s CLR integration engine does not support generic types as the basis for User-Defined Types (UDTs) or User-Defined Aggregates (UDAs) because it cannot resolve the generic type arguments at the SQL metadata level. This typically happens after a developer updates a .NET assembly to use generics for code reuse, then attempts to register or alter that assembly in SQL Server without refactoring the type hierarchy.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Type

  • Run the following query to locate the problematic assembly referenced in the error:
SELECT a.name AS AssemblyName, a.permission_set_desc, m.definition
FROM sys.assemblies a
JOIN sys.assembly_modules m ON a.assembly_id = m.assembly_id;
  • Cross-reference the %ls type name from the error message with your Visual Studio SQLCLR project to find the exact class definition.
  • Open the source .cs or .vb file and confirm the class signature includes a generic base, such as public class SensorData : BaseReading<T>.

Step 2: Refactor the Generic Type to a Concrete Implementation

  • Remove the generic parameter <T> from the class marked with [SqlUserDefinedType(Format.Native)] or [Serializable].
  • Create a concrete, non-generic class that either implements the required interface directly or inherits from a non-generic base class.
  • Example fix:
// Unsupported
public class MyUDT<T> : INullable { ... }

// Supported
public class MyUDT : INullable { ... }
  • Recompile the assembly in Visual Studio 2022/2026 targeting .NET Framework 4.8.1 or the .NET version supported by SQL Server 2025 CLR integration.

Step 3: Drop and Re-register the Corrected Assembly

  • In SQL Server Management Studio (SSMS), drop the existing broken assembly reference:
DROP TYPE IF EXISTS dbo.MyUDT;
DROP ASSEMBLY IF EXISTS MyAssemblyName;
  • Re-add the corrected, compiled DLL using CREATE ASSEMBLY, pointing to the updated binary path:
CREATE ASSEMBLY MyAssemblyName
FROM 'C:\SQLCLR\MyAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • Re-create the UDT definition:
CREATE TYPE dbo.MyUDT EXTERNAL NAME MyAssemblyName.[Namespace.MyUDT];

Step 4: Validate CLR Integration Settings

  • Ensure CLR integration is enabled on the instance, as Windows Server 2025 security defaults may disable it post-patching:
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
  • Verify the clr strict security setting (enabled by default since SQL Server 2017+) is not blocking the load due to an unsigned assembly, and sign the assembly with a certificate if required.

Alternative or Verification Steps

  • Verification: Execute SELECT * FROM sys.assembly_types WHERE name = 'MyUDT'; to confirm the type now appears in the system catalog without throwing a registration error.
  • Alternative: If refactoring the generic class is not feasible due to legacy dependencies, implement the Adapter design pattern—wrap the generic class inside a non-generic “shell” class that exposes only the specific type (e.g., int or string) required by the SQL Server schema, then register the shell class as the UDT instead.

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

Why This Error Happens

Error 10328 typically occurs when SQL Server’s worker thread stack space is exhausted during the creation of a new AppDomain, which is required for CLR integration (SQLCLR) processes. This is often triggered by a high volume of concurrent CLR requests, excessive thread usage from third-party extended stored procedures, or a misconfigured max worker threads setting that leaves insufficient reserved stack memory per thread. In rare cases, this can also be exacerbated by memory pressure on the host OS (Windows Server 2025) that prevents the SQL Server process from committing additional stack pages.

Step-by-Step Resolution Guide

Step 1: Verify and Adjust Max Worker Threads

  • Open SSMS and connect to the affected instance via a Dedicated Admin Connection (DAC) if the instance is unresponsive.
  • Run sp_configure 'max worker threads' to check the current value.
  • If the value is manually set too high for the available hardware threads, reset it to 0 to allow SQL Server to self-configure: EXEC sp_configure 'max worker threads', 0; RECONFIGURE;

Step 2: Audit and Isolate CLR Integration

  • Check if clr enabled is set to 1 via sp_configure. If CLR features are not actively required, disable them to free up stack resources: EXEC sp_configure 'clr enabled', 0; RECONFIGURE;
  • If CLR is required, identify specific assemblies causing excessive AppDomain creation by querying sys.dm_clr_appdomains.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER followed by net start MSSQLSERVER to clear orphaned AppDomains.

Step 3: Increase OS-Level Stack Reservations

  • Navigate to the SQL Server Configuration Manager on Windows Server 2025.
  • Check the Startup Parameters tab for the instance properties.
  • If running on a 32-bit compatibility layer or using specific trace flags, ensure Trace Flag -g (gateway memory) is not set too restrictively, as this limits memory available for the stack guard.

Step 4: Check Windows Server Memory and Handle Limits

  • Open Resource Monitor (resmon.exe) on Windows Server 2025 to check for non-paged pool memory exhaustion.
  • Verify that antivirus or EDR software on the Windows 11/Server 2025 host is not throttling the sqlservr.exe process’s memory allocation requests.
  • Ensure the server has not hit the Virtual Memory paging file limit, located in System Properties > Advanced > Performance Settings.

Alternative or Verification Steps

  • To verify the fix, run SELECT * FROM sys.dm_os_sys_info; and check the stack_size_in_bytes column to ensure it aligns with expected defaults (usually 512KB for 64-bit systems).
  • If the error persists under heavy load, consider isolating the CLR-heavy application to a dedicated instance with a higher max worker threads ceiling or apply the latest Cumulative Update (CU) for SQL Server 2025 to patch potential memory leak regressions in the CLR host.

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

Troubleshooting Guide: SQL Server Error 10329 – “.Net Framework execution was aborted”

Why This Error Happens

This error occurs when SQL Server’s CLR (Common Language Runtime) integration forcibly terminates a running SQLCLR assembly, typically due to resource governor timeouts, memory pressure, or an external host policy violation. It is commonly triggered when a .NET assembly executing inside SQL Server consumes excessive thread quantum or encounters a deadlock state that the SQL Server host environment detects and aborts to protect server stability. Corrupted CLR assemblies or outdated .NET Framework dependencies on Windows Server 2025 / Windows 11 can also trigger premature execution aborts.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Configuration

  • Open SQL Server Management Studio (SSMS) and run sp_configure 'clr enabled' to confirm CLR is active.
  • Check if clr strict security is enabled (default in SQL Server 2017+), as this may block unsigned assemblies and cause abrupt termination.
  • Run: EXEC sp_configure 'clr strict security', 0; RECONFIGURE; only if testing in a non-production environment.

Step 2: Inspect and Repair the SQLCLR Assembly

  • Navigate to Object Explorer > Databases > [YourDB] > Programmability > Assemblies in SSMS.
  • Identify the assembly referenced in the error details (%.*ls placeholder in the error log will show the specific assembly name).
  • Drop and re-register the assembly using an updated DLL:
  ALTER ASSEMBLY YourAssemblyName
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Ensure the DLL path is accessible by the SQL Server service account.

Step 3: Update .NET Framework and Windows Components

  • Confirm Windows Server 2025 / Windows 11 has the latest .NET Framework 4.8.1 (or newer) runtime installed via Settings > Windows Update > Optional Updates.
  • Restart the SQL Server service after updates:
  Restart-Service -Name MSSQLSERVER -Force
  • Check Windows Event Viewer (Applications and Services Logs > Microsoft > Windows > .NET Runtime) for correlating crash dumps.

Step 4: Adjust SQL Server Resource Governor Settings

  • If the abort is caused by timeout thresholds, review and increase the CLR thread quantum via Resource Governor:
  ALTER RESOURCE GOVERNOR RECONFIGURE;
  • Monitor sys.dm_os_threads and sys.dm_exec_requests to check if CLR threads are being starved by concurrent processes.

Alternative or Verification Steps

  • To verify the fix, re-execute the stored procedure or trigger that previously failed and monitor the SQL Server Error Log (Management > SQL Server Logs) for recurrence of Error 10329.
  • If the issue persists, consider migrating the logic out of SQLCLR into a native T-SQL stored procedure or an external microservice to eliminate CLR hosting dependency entirely.

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

Troubleshooting Guide: Error 10327 – Assembly Not Trusted in SQL Server 2025

Why This Error Happens

This error occurs because SQL Server 2025’s CLR security model requires explicit trust verification before loading managed code assemblies, and the database’s TRUSTWORTHY property is set to OFF by default for security hardening. The assembly you are attempting to create or alter lacks a valid trust chain—meaning it is either unsigned, or its signing certificate/asymmetric key has not been mapped to a SQL Server login granted the UNSAFE ASSEMBLY permission. Additionally, this can occur if the clr strict security configuration option is enabled (the default in modern SQL Server versions) and no exception has been carved out via sp_add_trusted_assembly.

Step-by-Step Resolution Guide

Step 1: Verify Current Security Configuration

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to check if clr strict security is enabled: EXEC sp_configure 'clr strict security';
  • Check the TRUSTWORTHY status of your target database: SELECT name, is_trustworthy_on FROM sys.databases WHERE name = 'YourDatabaseName';

Step 2: Generate a Hash and Add the Assembly to the Trusted List

  • Since clr strict security is enabled by default in SQL Server 2025, the most reliable fix is to explicitly trust the assembly’s binary hash rather than disabling security features.
  • Calculate the SHA-512 hash of your DLL file using PowerShell: Get-FileHash -Algorithm SHA512 "C:\Assemblies\YourAssembly.dll"
  • Execute the system stored procedure to register the assembly as trusted (requires sysadmin role):
  • EXEC sys.sp_add_trusted_assembly @hash = 0x<YourCalculatedHash>, @description = N'YourAssembly - Approved for Production';

Step 3: Create a Login and Certificate for Signed Assemblies

  • If the assembly is signed with a certificate, create a login from that specific certificate in the master database.
  • Use the command: CREATE LOGIN AssemblySigningLogin FROM CERTIFICATE YourCertName;
  • Grant the necessary permission to that specific login: GRANT UNSAFE ASSEMBLY TO AssemblySigningLogin;

Step 4: Re-deploy the Assembly

  • Navigate back to your target user database (not master).
  • Re-run the original deployment script: CREATE ASSEMBLY YourAssemblyName FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = UNSAFE;
  • Confirm the command completes without throwing Error 10327.

Alternative or Verification Steps

  • Verification: Query the trusted assemblies list to confirm your hash was successfully registered by running SELECT * FROM sys.trusted_assemblies;.
  • Alternative (Legacy/Dev environments only): If strict security policies are not a concern (e.g., in an isolated dev environment), you may bypass hash-trusting by setting the database property directly: ALTER DATABASE YourDatabaseName SET TRUSTWORTHY ON;. Note: This is generally discouraged in production environments as it widens the security attack surface.

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

Troubleshooting Guide: SQL Server Error 10325 – Stack Overflow Shutdown

Why This Error Happens

Error 10325 occurs when SQL Server’s internal thread stack space is exhausted while executing unmanaged code, typically from an extended stored procedure, a CLR assembly, or a third-party DLL loaded into the SQL Server process space. This is frequently triggered by infinite recursion in custom code, a corrupted or incompatible extended stored procedure (xp_*) DLL, or an outdated driver/module that was not rebuilt for compatibility with SQL Server 2025 on Windows Server 2025 or Windows 11. Because unmanaged code runs inside the SQL Server process, a stack overflow in that code forces SQL Server to terminate immediately to prevent memory corruption.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Module from the Error Log

  • Open the SQL Server Error Log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Search for the stack trace entries immediately preceding Error 10325 to identify the specific DLL or extended stored procedure named in the call stack.
  • Cross-reference the module name with sys.dm_os_loaded_modules using a recent monitoring snapshot or Extended Events trace if the server is still reachable.

Step 2: Disable or Remove the Problematic Extended Stored Procedure / CLR Assembly

  • If a legacy extended stored procedure (e.g., a custom xp_ DLL) is identified, drop it using:
  EXEC sp_dropextendedproc 'xp_YourCustomProc';
  • If the issue stems from a SQL CLR assembly, disable CLR integration temporarily to confirm the root cause:
  EXEC sp_configure 'clr enabled', 0;
  RECONFIGURE;
  • Remove or replace any .dll files under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ that are not digitally signed or that predate SQL Server 2025 compatibility.

Step 3: Update or Rebuild Unmanaged Code for Compatibility

  • Recompile any custom unmanaged DLLs against the SQL Server 2025 SDK and ensure they target the correct thread stack size (default 512KB per worker thread, 2MB for 64-bit).
  • Check for recursive function calls in the custom code that lack a proper base case or depth limit.
  • Update third-party vendor drivers (e.g., backup agents, antivirus SQL plugins) to versions explicitly certified for Windows Server 2025 / Windows 11.

Step 4: Increase Thread Stack Monitoring and Apply the Latest Cumulative Update

  • Install the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog, as stack handling fixes are frequently included in servicing releases.
  • Run Windows Update on Windows Server 2025 / Windows 11 to ensure the latest C++ Redistributable packages are installed, since mismatched runtime libraries can cause stack corruption in unmanaged code.
  • Restart the SQL Server service via services.msc or NET START MSSQLSERVER after applying updates.

Alternative or Verification Steps

  • Re-run the workload or job that previously triggered the crash and monitor the Error Log in real time using Get-Content ERRORLOG -Wait in PowerShell to confirm Error 10325 no longer appears.
  • If the crash persists, isolate the unmanaged code in a separate out-of-process COM+ application or convert the logic to a managed CLR procedure with proper exception handling to prevent direct impact on the SQL Server process.

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

Troubleshooting Guide: SQL Server Error 10326 – Assembly Version Conflict

Why This Error Happens

This error occurs when SQL Server detects that two different versions of the same CLR assembly are registered within the same database, which violates assembly versioning rules enforced by SQL Server 2025. This typically happens after a redeployment or upgrade process where an older assembly version was not properly dropped before a newer version was registered. It can also occur when dependent assemblies reference conflicting versions of a shared assembly, creating an ambiguous resolution path for the CLR integration engine.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Assembly Versions

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to list all registered assemblies and their versions:
  SELECT name, assembly_id, create_date, modify_date 
  FROM sys.assemblies 
  WHERE name = 'YourAssemblyName';
  • Note the assembly_id values for both conflicting versions reported in the error message.

Step 2: Check Dependencies Before Dropping

  • Query sys.assembly_modules and sys.assembly_references to confirm which stored procedures, triggers, or functions depend on each assembly version.
  SELECT * FROM sys.assembly_modules WHERE assembly_id = <ID_from_Step1>;
  • Document any dependent objects, as these will need to be re-pointed to the correct assembly version before removal.

Step 3: Drop the Outdated Assembly Version

  • Use the DROP ASSEMBLY command targeting the older, unwanted version:
  DROP ASSEMBLY [YourAssemblyName_OldVersion];
  • If the drop fails due to dependency locks, first alter or drop the dependent CLR objects, then retry the drop command.

Step 4: Re-register the Correct Assembly Version

  • Ensure the correct .dll file is located in a trusted path, such as C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Re-register the assembly using CREATE ASSEMBLY, specifying the correct permission set (SAFE, EXTERNAL_ACCESS, or UNSAFE):
  CREATE ASSEMBLY [YourAssemblyName] 
  FROM 'C:\Path\To\CorrectVersion.dll' 
  WITH PERMISSION_SET = SAFE;

Step 5: Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 or Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to clear any cached CLR metadata locks.

Alternative or Verification Steps

  • Verify the fix by querying sys.assemblies again to confirm only a single version of the assembly exists for the specific name value.
  • If the conflict persists, consider dropping all versions of the assembly entirely and performing a clean CREATE ASSEMBLY import to reset the CLR binding metadata.

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

Troubleshooting Guide: Error 10324 — WITH ENCRYPTION Not Applicable to CLR Triggers

Why This Error Happens

This error occurs because the WITH ENCRYPTION clause in a CREATE TRIGGER or ALTER TRIGGER statement is designed exclusively for T-SQL triggers, where SQL Server encrypts the stored procedure text in the syscomments/sys.sql_modules system views. CLR triggers, however, do not store their logic as plain T-SQL text in the database—their executable logic resides in a compiled .NET assembly registered via CREATE ASSEMBLY. Since there is no T-SQL definition text to obscure for a CLR trigger, SQL Server 2025 rejects the syntax combination and raises Error 10324 rather than silently ignoring the invalid option.

Step-by-Step Resolution Guide

Step 1: Identify the Trigger Type in Your Script

  • Open the failing script in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate the CREATE TRIGGER or ALTER TRIGGER statement that includes the WITH ENCRYPTION keyword.
  • Check whether the trigger body uses AS EXTERNAL NAME <Assembly>.<Class>.<Method> (this confirms it is a CLR trigger, not a T-SQL trigger).

Step 2: Remove the WITH ENCRYPTION Clause for CLR Triggers

  • Edit the CREATE TRIGGER statement to strip out WITH ENCRYPTION entirely.
  • Example of the corrected syntax:
  CREATE TRIGGER trg_CLR_Example
  ON dbo.YourTable
  AFTER INSERT
  AS EXTERNAL NAME YourAssembly.TriggerClass.TriggerMethod;
  • Re-run the script in SSMS to confirm Error 10324 no longer appears.

Step 3: Secure the Logic at the Assembly Level Instead

  • Since encryption isn’t available at the T-SQL layer for CLR objects, protect your intellectual property by obfuscating or encrypting the compiled .NET assembly (.dll) before registering it.
  • Use CREATE ASSEMBLY YourAssembly FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE; to load the protected binary.
  • Restrict access to the assembly source files on disk via NTFS permissions (right-click folder → Properties → Security tab) to prevent unauthorized decompilation.

Step 4: Validate Permission Sets and Trigger Registration

  • Confirm the CLR integration feature is enabled by running:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Verify the trigger is correctly bound to the assembly by querying sys.triggers and sys.assembly_modules to ensure is_disabled = 0.

Alternative or Verification Steps

  • To verify the fix, query sys.triggers WHERE name = 'trg_CLR_Example' and confirm the is_ms_shipped and type_desc columns show CLR_TRIGGER with no error on redeployment.
  • If you specifically need encrypted trigger logic and cannot use a CLR assembly, convert the trigger back to a standard T-SQL trigger (AS BEGIN ... END syntax) where WITH ENCRYPTION is fully supported.

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

Troubleshooting Guide: Error 10322 – “Type %.ls not found in database %.ls”

Why This Error Happens

This error occurs when SQL Server attempts to resolve a user-defined type (UDT), alias type, or system type reference that does not exist in the current database context, typically because the type was created in a different database or schema than the one currently active. It can also surface after a database restore or migration where type dependencies were not scripted or transferred along with the referencing objects. Additionally, mismatched schema bindings or incorrect two-part/three-part naming conventions in queries, stored procedures, or CLR assemblies can trigger this error even when the type technically exists elsewhere on the server.

Step-by-Step Resolution Guide

Step 1: Identify the Missing Type and Target Database

  • Run SELECT * FROM sys.types WHERE name = 'YourTypeName'; in the suspected database to confirm whether the type is missing.
  • Check the exact database context using SELECT DB_NAME(); before executing the failing query or procedure.
  • Review the full error message to extract the placeholder values for %.*ls (type name and database name) from the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.

Step 2: Recreate or Migrate the Missing User-Defined Type

  • If the type was defined in a source database, script it out using SSMS: right-click the type under Databases > [DB] > Programmability > Types > User-Defined Data Types, then select Script Type as > CREATE To.
  • Execute the generated CREATE TYPE [schema].[TypeName] FROM [base_type] statement in the target database where the error occurred.
  • For CLR-based UDTs, ensure the corresponding assembly is also deployed using CREATE ASSEMBLY before recreating the type.

Step 3: Correct Schema and Database Context References

  • Update any stored procedures, functions, or application connection strings that reference the type using two-part naming (schema.type) instead of assuming dbo is correct.
  • If cross-database references are required, use fully qualified three-part names (e.g., OtherDB.dbo.TypeName) and confirm cross-database ownership chaining or permissions are configured via sp_configure 'cross db ownership chaining'.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER on Windows Server 2025 after making schema changes to clear cached execution plans.

Step 4: Rebuild Dependencies After Restore/Migration

  • If this occurred after a database restore, run sp_helptext or dependency-check scripts against all stored procedures and functions that reference user-defined types to flag broken links.
  • Use SQL Server Management Studio’s Generate Scripts Wizard on the source server with the “Types” object type explicitly included, then re-run the script on the destination server.

Alternative or Verification Steps

  • Verify the fix by re-executing the original failing query or stored procedure and confirming no Error 10322 is raised in SSMS or the Windows Event Viewer (Application log, source: MSSQLSERVER).
  • If the issue persists, use sp_depends or query sys.sql_expression_dependencies to trace all objects still referencing the orphaned type and systematically recreate each dependency in the correct database.

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

Troubleshooting Guide: SQL Server Error 10323 — Invalid User Code Identified by .NET Framework Managed Debug Assistant

Why This Error Happens

This error occurs when SQL Server’s CLR integration (SQLCLR) loads a managed assembly that violates the .NET Framework’s hosting and reliability contracts, triggering the Managed Debug Assistant (MDA) to flag unsafe code execution inside the SQL Server process. This is typically caused by a CLR assembly registered with an incorrect PERMISSION_SET (such as UNSAFE or EXTERNAL_ACCESS when SAFE is expected), corrupted assembly metadata, or incompatibility between the assembly’s target .NET Framework version and the CLR runtime hosted by SQL Server 2025. It can also surface when third-party or custom CLR stored procedures/triggers call into unmanaged memory or perform illegal type casts that the hosting environment does not permit.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly

  • Check the SQL Server error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full text following Error 10323 to identify the assembly name and module.
  • Run the following query to list all CLR assemblies and their permission sets:
SELECT name, permission_set_desc, is_user_defined FROM sys.assemblies;
  • Cross-reference the flagged assembly with any recently deployed CLR stored procedures, functions, or triggers.

Step 2: Validate and Reconfigure the Assembly Permission Set

  • Drop and re-register the assembly with the correct permission set (prefer SAFE unless external access is explicitly required):
ALTER ASSEMBLY YourAssemblyName
WITH PERMISSION_SET = SAFE;
  • If the assembly requires file or network access, use EXTERNAL_ACCESS only after enabling TRUSTWORTHY on the database or signing the assembly with a certificate-based login, per Microsoft’s CLR strict security model (enabled by default since SQL Server 2017+).
  • Verify clr strict security is enabled (default = 1) using:
EXEC sp_configure 'clr strict security';

Step 3: Rebuild and Redeploy the Managed Assembly

  • Recompile the source .dll targeting a .NET Framework version fully compatible with SQL Server 2025’s hosted CLR (typically .NET Framework 4.8 or later).
  • Remove any unmanaged code calls, unsafe blocks, or illegal P/Invoke operations from the assembly source.
  • Redeploy using CREATE ASSEMBLY with the binary path or hex image:
CREATE ASSEMBLY YourAssemblyName
FROM 'C:\Deploy\YourAssembly.dll'
WITH PERMISSION_SET = SAFE;

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

  • Restart the SQL Server instance via SQL Server Configuration Manager or:
Restart-Service -Name 'MSSQLSERVER' -Force
  • Clear the CLR procedure cache to force reloading of the corrected assembly:
DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Re-run the operation that triggered the CLR call and monitor the SQL Server error log and Windows Event Viewer (Application log) to confirm Error 10323 no longer appears.
  • If the issue persists, disable CLR integration entirely (EXEC sp_configure 'clr enabled', 0;) as a temporary workaround while auditing all deployed assemblies for non-compliant managed code.

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

Troubleshooting Guide: SQL Server Error 10320 – “Method name ‘%.ls’ is invalid for ‘%.ls'”

Why This Error Happens

This error occurs when SQL Server attempts to invoke a method on a CLR (Common Language Runtime) user-defined type or object, but the method name specified does not exist or is not properly exposed in the assembly’s metadata. This typically results from a mismatch between the assembly version registered in SQL Server and the actual compiled .NET assembly, often caused by an incomplete deployment, an outdated assembly reference, or corruption in the sys.assemblies catalog. It can also occur after an in-place upgrade to SQL Server 2025 if legacy CLR assemblies were not recompiled against the updated .NET runtime bindings.

Step-by-Step Resolution Guide

Step 1: Verify the CLR Assembly and Method Signature

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run SELECT * FROM sys.assemblies WHERE name = 'YourAssemblyName'; to confirm the assembly is registered correctly.
  • Cross-check the method name referenced in your T-SQL call (e.g., ::YourType::MethodName) against the actual public method names in the source .dll using a decompiler like ILSpy or dotPeek.
  • Ensure case sensitivity matches exactly, as CLR method names are case-sensitive even if your SQL Server collation is not.

Step 2: Drop and Re-register the Assembly

  • Script out the existing assembly and any dependent UDTs/functions before making changes.
  • Drop the assembly using:
  DROP AGGREGATE IF EXISTS YourAggregate;
  DROP TYPE IF EXISTS YourType;
  DROP ASSEMBLY IF EXISTS YourAssemblyName;
  • Re-add the assembly from the updated binary path, typically located in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ or your custom deployment folder:
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\Path\To\Updated\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;

Step 3: Check .NET Runtime Compatibility

  • Confirm that SQL Server 2025 is using the correct CLR integration version by running SELECT SERVERPROPERTY('ProductVersion'); to verify the build.
  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025/Windows 11 and ensure the required .NET Framework or .NET runtime version matches the one used to compile your assembly.
  • If using a newer .NET target framework, recompile the assembly against the SQL CLR-compatible runtime version supported in SQL Server 2025.

Step 4: Rebuild Dependent Objects

  • Recreate any user-defined functions, stored procedures, or triggers that reference the CLR method.
  • Use sp_refreshsqlmodule 'YourObjectName'; to force SQL Server to refresh cached metadata bindings for dependent objects.
  • Restart the SQL Server service via services.msc or run:
  Restart-Service -Name MSSQLSERVER -Force

Alternative or Verification Steps

  • To verify the fix, execute the original query or stored procedure that triggered Error 10320 and confirm it completes without exception; also check the SQL Server Error Log (Management > SQL Server Logs in SSMS) for any residual CLR binding warnings.
  • If the error persists, consider enabling CLR strict security checks via sp_configure 'clr strict security', 1; and re-sign the assembly with a certificate or asymmetric key to rule out permission-based method resolution failures.

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

Troubleshooting Guide: SQL Server Error 10321 – Invalid Method Name for UserDefinedType

Why This Error Happens

This error occurs when a Transact-SQL statement attempts to invoke a method on a CLR User-Defined Type (UDT) using a method name that does not exist in the compiled assembly, or the name is misspelled/case-mismatched. It can also arise when the assembly registered in SQL Server is outdated, corrupted, or was updated externally without re-registering (ALTER ASSEMBLY) in the database, causing a mismatch between the metadata SQL Server expects and the actual class definition. Permission issues rarely cause this specific error—it is almost always a code-to-metadata mismatch.

Step-by-Step Resolution Guide

Step 1: Verify the Method Name and Casing

  • Open the T-SQL query calling the UDT method (e.g., SELECT MyColumn.MethodName() FROM TableName).
  • Confirm the exact method name, including case sensitivity, matches the public method defined in the CLR class (C#/VB.NET source).
  • Check for typos such as extra spaces, incorrect capitalization, or use of a property name instead of a method name.

Step 2: Inspect the Registered Assembly in SQL Server

  • Run the following query to confirm the assembly version currently loaded in the database:
  SELECT name, create_date, modify_date 
  FROM sys.assemblies 
  WHERE name = 'YourAssemblyName';
  • Compare the modify_date against the last build date of your Visual Studio project to detect if an outdated DLL is registered.
  • If outdated, drop and re-register the assembly using CREATE ASSEMBLY or ALTER ASSEMBLY with the updated .dll file path.

Step 3: Rebuild and Redeploy the CLR Assembly

  • In Visual Studio 2022/2025, clean and rebuild the SQL CLR project targeting .NET Framework (not .NET Core, as SQL Server 2025 CLR integration still requires Framework-compatible assemblies).
  • Deploy the updated .dll using:
  ALTER ASSEMBLY YourAssemblyName 
  FROM 'C:\Deploy\YourAssembly.dll';
  • Ensure the CREATE TYPE definition referencing the UDT is dropped and recreated if the method signature changed.

Step 4: Check for Multiple Assembly Versions on Disk

  • On Windows Server 2025 / Windows 11, search for duplicate or conflicting versions of the DLL in:
  • C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\
  • Any custom deployment folder referenced in your build pipeline.
  • Remove outdated copies to prevent SQL Server from loading a stale assembly during a service restart.

Step 5: Restart SQL Server Service and Clear Plan Cache

  • Open Services.msc, locate SQL Server (MSSQLSERVER), and restart it to force a reload of all CLR assemblies.
  • Clear the cached execution plans that may reference the old method signature:
  DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Re-run the original query that triggered Error 10321; if successful, validate output data types match expectations using SELECT MyColumn.ToString() as a baseline sanity check.
  • If the error persists, use sp_helptype and sys.assembly_types to confirm the UDT’s method list matches your source code exactly, then redeploy from a clean build output folder to rule out stale binaries.

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

Troubleshooting Guide: SQL Server Error 10318 (ParamArrayAttribute Not Supported)

Why This Error Happens

This error occurs when registering a SQLCLR assembly (a .NET method, stored procedure, trigger, or user-defined function) in SQL Server that contains a method parameter decorated with the System.ParamArrayAttribute (i.e., a C# params keyword argument). SQL Server’s CLR integration host does not support variable-length argument lists because it requires a fixed, strongly-typed parameter signature to map to T-SQL data types at registration time. This typically surfaces after migrating an older assembly to SQL Server 2025 or after a .NET recompilation introduced a params array into a public method signature that is exposed via CREATE ASSEMBLY or CREATE PROCEDURE ... EXTERNAL NAME.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Method

  • Run the following query to locate the problematic assembly causing the registration failure:
  SELECT name, clr_name, permission_set_desc 
  FROM sys.assemblies 
  WHERE is_user_defined = 1;
  • Cross-reference the error message text (which includes the method name, type name, and parameter index) to locate the exact .cs or .vb source file in your Visual Studio SQLCLR project.
  • Open the project and search for the params keyword in method signatures that are marked with [SqlProcedure], [SqlFunction], or [SqlTrigger] attributes.

Step 2: Refactor the Method Signature

  • Remove the params keyword from any method exposed to SQL Server; replace it with an explicit, fixed-type parameter, such as a SqlString, SqlXml, or a delimited NVARCHAR(MAX) input.
  • Example fix — change this:
  public static void MyProc(params int[] values)

to this:

  public static void MyProc(SqlString commaSeparatedValues)
  • If multiple inputs are required, use a Table-Valued Parameter (TVP) or pass a serialized JSON/XML string and deserialize it inside the method body instead of relying on variable-length arguments.

Step 3: Rebuild and Redeploy the Assembly

  • Recompile the .NET project in Visual Studio targeting a CLR version compatible with SQL Server 2025 (ensure TargetFramework aligns with supported CLR hosting, typically .NET Framework 4.8 compatibility mode or the specific SQLCLR runtime documented for SQL 2025).
  • Drop the old assembly and dependent objects in SQL Server:
  DROP PROCEDURE IF EXISTS dbo.MyProc;
  DROP ASSEMBLY IF EXISTS MyAssembly;
  • Re-register the corrected assembly:
  CREATE ASSEMBLY MyAssembly 
  FROM 'C:\Deploy\MyAssembly.dll' 
  WITH PERMISSION_SET = SAFE;

Step 4: Validate SQL Server CLR Configuration

  • Confirm that clr enabled is set to 1 at the instance level, since misconfiguration can sometimes mask or compound registration errors:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator on Windows Server 2025) if configuration values were changed.

Alternative or Verification Steps

  • Verify the fix by re-running CREATE ASSEMBLY and the corresponding CREATE PROCEDURE/FUNCTION statements; a successful execution with no Error 10318 confirms the signature issue is resolved.
  • As an alternative if refactoring isn’t immediately feasible, wrap the original params-based method in a new internal “shim” method that accepts a standard array type (int[] without params) or a single delimited string, and expose only the shim method to SQL Server via the [SqlProcedure] attribute.

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

Troubleshooting Guide: SQL Server Error 10319 — Unsupported ParamArrayAttribute in UserDefinedType Method

Why This Error Happens

This error occurs when a SQLCLR User-Defined Type (UDT) assembly contains a method or property signature that uses the C# params keyword (which compiles to System.ParamArrayAttribute). SQL Server’s CLR integration engine does not support variable-length argument lists for UDT methods because the type system requires a fixed, strongly-typed method signature to marshal data correctly between .NET and the SQL Server engine. This typically surfaces after deploying a newly compiled assembly or after migrating a legacy UDT assembly to be compatible with SQL Server 2025 and its updated .NET runtime host.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Method

  • Review the full error message to extract the method name, ordinal parameter number, and type name referenced in the 10319 output.
  • Run the following query to locate the assembly tied to the UDT:
  • SELECT name, assembly_class FROM sys.assembly_types WHERE name = 'YourUDTName';
  • Locate the source project or DLL on disk, typically under C:\inetpub\wwwroot\CLRAssemblies\ or your custom build output folder.

Step 2: Refactor the Method Signature in Source Code

  • Open the .cs or .vb source file for the UDT in Visual Studio 2022/2025.
  • Locate the method using the params keyword, for example: public void MyMethod(params int[] values).
  • Replace the params array with a standard fixed-type parameter, an explicit array parameter without the params modifier, or a SqlString/XML-serialized input that SQL Server can marshal.
  • Example fix: change public void MyMethod(params int[] values) to public void MyMethod(int[] values).
  • Recompile the project to generate a clean DLL with no ParamArrayAttribute references.

Step 3: Drop and Redeploy the Assembly in SQL Server

  • Connect via SQL Server Management Studio (SSMS) 21 or Azure Data Studio to the Windows Server 2025 instance.
  • Drop the existing type and assembly:
  • DROP TYPE dbo.YourUDTName;
  • DROP ASSEMBLY YourAssemblyName;
  • Re-register the corrected assembly:
  • CREATE ASSEMBLY YourAssemblyName FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • CREATE TYPE dbo.YourUDTName EXTERNAL NAME YourAssemblyName.[YourClassName];

Step 4: Validate CLR Strict Security Settings

  • Confirm clr strict security is enabled (default in SQL Server 2025) via sp_configure 'clr strict security';.
  • Ensure the assembly is signed with a certificate or asymmetric key and has a corresponding login granted UNSAFE ASSEMBLY permission if the permission set is not SAFE.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell if configuration changes were made.

Alternative or Verification Steps

  • Verify the fix by executing a test query that invokes the previously failing UDT method (e.g., SELECT dbo.YourUDTName::MyMethod(1,2,3);) and confirm it returns results without raising Error 10319.
  • If refactoring the source isn’t possible (e.g., third-party vendor DLL), contact the vendor for a SQL Server–compatible build, or wrap the UDT logic in a CLR Stored Procedure instead, which has more flexible parameter-handling support than UDT methods.

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

Troubleshooting Guide: Error 10317 – File Version Info Retrieval Failure

Why This Error Happens

Error 10317 occurs when SQL Server 2025 attempts to read the file version resource from a binary (such as a DLL, EXE, or SQL Server module) but cannot access or parse this metadata. This typically happens due to insufficient NTFS permissions on the target file, file corruption that damages the version resource block, or the file being locked/blocked by antivirus software, Windows Defender, or another process. In some cases, a failed or incomplete SQL Server update on Windows Server 2025 can leave a binary in a partially-patched state, stripping its version information entirely.

Step-by-Step Resolution Guide

Step 1: Identify the Problem File and Check Permissions

  • Review the SQL Server Error Log (ERRORLOG) or Windows Event Viewer to extract the exact file path referenced in the %s placeholder.
  • Navigate to the file location, typically under C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Right-click the file, go to Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has at least Read & Execute permissions.
  • If permissions are missing, click Edit, add the service account, and grant the required access level.

Step 2: Verify File Integrity and Replace Corrupted Binaries

  • Run sfc /scannow from an elevated Command Prompt to check for corrupted system files on Windows Server 2025 / Windows 11.
  • For SQL Server-specific binaries, compare the file hash or version against a known-good installation media or Cumulative Update (CU) package.
  • If the file is confirmed corrupted, re-run the SQL Server 2025 setup in Repair mode via Control Panel > Programs > Microsoft SQL Server 2025 > Uninstall/Change > Repair.

Step 3: Exclude SQL Server Directories from Antivirus Scanning

  • Open Windows Security (or your third-party antivirus console) and navigate to Virus & threat protection > Exclusions.
  • Add exclusions for the SQL Server installation directory (e.g., C:\Program Files\Microsoft SQL Server\) and the data directory.
  • Restart the SQL Server service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER to release any file locks.

Step 4: Reapply the Latest Cumulative Update

  • Download the latest Cumulative Update (CU) for SQL Server 2025 from the Microsoft Update Catalog.
  • Run the update package to force an overwrite of potentially corrupted binaries with clean, version-stamped files.
  • Reboot the server after installation completes to ensure all file handles are released and reloaded correctly.

Alternative or Verification Steps

  • After applying fixes, restart the SQL Server service and check the ERRORLOG to confirm Error 10317 no longer appears during startup or operation.
  • If the error persists, use Process Monitor (ProcMon) from Sysinternals to trace real-time file access denials on the specific file path, which can reveal a lingering permission or lock issue not caught by manual inspection.

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

Troubleshooting Guide: SQL Server Error 10314 – CLR Assembly Load Failure

Why This Error Happens

Error 10314 occurs when the SQL Server CLR (Common Language Runtime) integration fails to load a managed assembly, typically because the server has exhausted available memory or virtual address space needed by the .NET Framework host. This can also result from a corrupted assembly in the database, conflicting CLR versions, or the clr enabled configuration interacting poorly with memory pressure from other SQL Server subsystems. In some cases, Windows Server 2025 security policies (like AppLocker or Code Integrity) may block the assembly load, which SQL Server misreports as a resource issue.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Status and Memory Pressure

  • Run sp_configure 'clr enabled' to confirm CLR is active on the instance.
  • Check sys.dm_os_memory_clerks for the MEMORYCLERK_SQLCLR entry to see current memory consumption.
  • Review Windows Performance Monitor counters (SQL Server:Memory Manager > Target Server Memory vs Total Server Memory) for signs of memory exhaustion.

Step 2: Increase Server Resources or Adjust Memory Configuration

  • Open SQL Server Management Studio (SSMS) and navigate to Server Properties > Memory.
  • Increase the “Maximum server memory” value if it’s set too restrictively, leaving at least 4–6 GB for the OS on Windows Server 2025.
  • If running in a virtualized environment, confirm the VM has not hit a memory ballooning or Hyper-V dynamic memory limit.
  • Restart the SQL Server service after adjustments via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Step 3: Rebuild or Re-register the Faulty Assembly

  • Identify the problematic assembly using the id referenced in the error:
  SELECT name, assembly_id FROM sys.assemblies WHERE assembly_id = <id>;
  • Drop and re-add the assembly if corruption is suspected:
  DROP ASSEMBLY [YourAssemblyName];
  CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure the assembly file itself isn’t blocked by Windows (right-click DLL > Properties > Unblock).

Step 4: Check Windows Security and Code Integrity Policies

  • Review Windows Defender Application Control (WDAC) or AppLocker logs in Event Viewer under Applications and Services Logs > Microsoft > Windows > CodeIntegrity.
  • Temporarily disable Code Integrity enforcement in a test environment to confirm if it’s blocking the assembly load.
  • Add an explicit allow rule for the SQL Server CLR assembly path if policies are confirmed to be the cause.

Alternative or Verification Steps

  • After applying fixes, run a test query that invokes the CLR function/assembly directly and confirm no Error 10314 appears in the SQL Server logs (EXEC xp_readerrorlog).
  • If the issue persists, consider migrating the CLR assembly logic to a native T-SQL or external service (e.g., Azure Function) to eliminate reliance on in-process CLR hosting entirely.

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

Troubleshooting Guide: SQL Server Error 10316 – App Domain Unloaded Due to Memory Pressure

Why This Error Happens

This error occurs when the SQL Server CLR (Common Language Runtime) host experiences severe memory pressure and is forced to unload an application domain to reclaim resources. When subsequent requests attempt to reference that specific app domain version ID, SQL Server can no longer locate it because it has already been purged from memory. This is typically triggered by excessive memory consumption from CLR integration objects (SQLCLR assemblies), insufficient server memory allocation, or a memory leak within a custom CLR stored procedure or function.

Step-by-Step Resolution Guide

Step 1: Verify Current Memory Configuration

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'max server memory'; to check current allocation.
  • Ensure “max server memory” is not set too restrictively for your workload; leave at least 20-25% of total RAM for the OS on Windows Server 2025.

Step 2: Identify Problematic CLR Assemblies

  • Query sys.dm_clr_loaded_assemblies and sys.dm_clr_appdomains to identify which app domains are consuming excessive memory.
  • Check sys.dm_os_memory_clerks filtering on type = 'MEMORYCLERK_SQLCLR' to see current CLR memory usage.
  • Review any custom SQLCLR stored procedures for unmanaged resource leaks (unclosed SqlConnection, SqlDataReader, or large object allocations that aren’t disposed properly).

Step 3: Adjust CLR Memory Thresholds

  • Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQLSERVER\CLR in the Windows Registry Editor (adjust instance name as needed for your SQL Server 2025 install).
  • If using Resource Governor, review the CLR memory pool settings via ALTER RESOURCE GOVERNOR to ensure the pool isn’t artificially capped too low.
  • Restart the SQL Server service via services.msc or NET STOP MSSQLSERVER && NET START MSSQLSERVER after making registry changes to clear the stale app domain cache.

Step 4: Patch or Isolate the Offending Assembly

  • Update the .NET assembly referenced in the error to a version that properly disposes of memory-heavy objects (wrap IDisposable objects in using blocks).
  • Redeploy using ALTER ASSEMBLY [YourAssemblyName] FROM 'C:\Path\To\UpdatedAssembly.dll' WITH PERMISSION_SET = SAFE; to force a clean reload of the app domain.

Step 5: Increase System-Level Resources

  • If the server is physically constrained, increase physical RAM on the Windows Server 2025 host or adjust the VM’s allocated memory if virtualized.
  • On Windows 11 development environments, close competing memory-intensive applications before running CLR-heavy workloads.

Alternative or Verification Steps

  • To verify the fix, run your previously failing CLR stored procedure or query in a loop under load and monitor sys.dm_clr_appdomains to confirm the app domain remains stable (State = “Enabled Active”) without forced unloads.
  • If the error persists, as a temporary workaround, restart the SQL Server service to clear all cached app domains, then isolate and disable the specific CLR assembly using ALTER ASSEMBLY ... WITH PERMISSION_SET = SAFE until a permanent code fix for the memory leak is deployed.

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

Troubleshooting Guide: SQL Server Error 10312 – .NET Framework Execution Aborted (Thread Token Not Reverted)

Why This Error Happens

This error occurs when a SQLCLR routine (User-Defined Procedure, Function, or Type) running inside SQL Server impersonates a Windows thread token—typically via P/Invoke calls or unsafe assembly code—and fails to revert that token before returning control to the SQL Server execution engine. Because the CLR host inside SQL Server 2025 strictly monitors thread state for security isolation, it forcibly aborts the AppDomain or task when it detects a lingering impersonation context. This is almost always caused by custom CLR assemblies marked as UNSAFE or EXTERNAL_ACCESS that contain improperly scoped WindowsImpersonationContext calls or third-party DLLs that manipulate thread tokens without proper try/finally cleanup.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly

  • Query sys.assembly_modules and sys.assemblies to locate recently deployed or modified CLR objects.
  • Run: SELECT a.name, m.assembly_class, m.assembly_method FROM sys.assembly_modules m JOIN sys.assemblies a ON m.assembly_id = a.assembly_id;
  • Check the SQL Server Error Log (via xp_readerrorlog or C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for the exact object name tied to the 10312 event.

Step 2: Audit and Patch the CLR Source Code

  • Open the source project for the identified assembly in Visual Studio 2022/2025.
  • Search for WindowsIdentity.Impersonate(), WindowsImpersonationContext, or any native advapi32.dll P/Invoke signatures (e.g., LogonUser, DuplicateToken).
  • Ensure every impersonation call is wrapped in a try { ... } finally { context.Undo(); } block to guarantee the token reverts even if an exception is thrown.
  • Recompile the assembly targeting .NET Framework 4.8.1 (required for SQL Server 2025 CLR integration).

Step 3: Redeploy with Correct Permission Set

  • Drop the faulty assembly: DROP ASSEMBLY YourAssemblyName;
  • Re-register the patched DLL using the lowest permission level required (avoid UNSAFE unless absolutely necessary):
    CREATE ASSEMBLY YourAssemblyName FROM 'C:\SQLAssemblies\YourAssembly.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS;
  • If UNSAFE is mandatory, verify the assembly is signed and the login is mapped to the sysadmin role or has UNSAFE ASSEMBLY permission granted explicitly.

Step 4: Restart the SQL Server CLR Host

  • Restart the SQL Server service (MSSQLSERVER) via services.msc or run NET STOP MSSQLSERVER && NET START MSSQLSERVER in an elevated PowerShell/Command Prompt to clear any corrupted AppDomains left in memory.
  • Alternatively, run ALTER DATABASE [YourDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; followed by a database restart if the issue is isolated to one database’s AppDomain.

Alternative or Verification Steps

  • Verify the fix by executing the CLR object under load (loop it 50-100 times) and monitoring Event Viewer (Windows Logs > Application) for Event ID 10312; a clean run indicates successful token management.
  • If recompiling isn’t feasible immediately, run sp_configure 'clr strict security', 0; as a temporary workaround (not recommended for production) to reduce AppDomain restrictions while you source a patched DLL from the vendor.

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

Troubleshooting Guide: SQL Server Error 10313 — .NET Framework Resource Error

Why This Error Happens

Error 10313 occurs when SQL Server’s CLR (Common Language Runtime) integration encounters a failure while executing managed code, typically due to memory pressure or resource exhaustion within the SQLCLR hosting environment. This can be triggered by a corrupted .NET Framework installation, insufficient memory allocated to SQL Server causing AppDomain failures, or conflicts between the CLR version and SQL Server 2025’s runtime host policies. In some cases, it stems from fragmented memory in the “CLR” memory clerk, preventing the Common Language Runtime from allocating resources for query execution.

Step-by-Step Resolution Guide

Step 1: Verify and Repair .NET Framework Installation

  • Open Control Panel > Programs > Programs and Features > Turn Windows features on or off.
  • Ensure .NET Framework 4.8 (or higher) is enabled; on Windows Server 2025, confirm via Server Manager under Features.
  • Run DISM /Online /Cleanup-Image /RestoreHealth in an elevated PowerShell terminal to repair underlying OS component corruption.
  • Reboot the server and re-test the failing query.

Step 2: Check SQL Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and run:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'max server memory';
  • Ensure “max server memory” isn’t set too restrictively (leave at least 20% of total RAM for the OS and CLR overhead).
  • Increase the value if necessary using:
  EXEC sp_configure 'max server memory', 16384;
  RECONFIGURE;

Step 3: Rebuild or Reset the CLR Integration

  • Disable and re-enable CLR integration to clear any corrupted AppDomains:
  EXEC sp_configure 'clr enabled', 0;
  RECONFIGURE;
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • If using CLR Strict Security (default in SQL Server 2025), verify assemblies are signed and trusted:
  SELECT * FROM sys.trusted_assemblies;
  • Restart the SQL Server (MSSQLSERVER) service via services.msc to flush the CLR host.

Step 4: Monitor System Resource Usage

  • Use Performance Monitor (PerfMon) to track SQLServer:Memory Manager > Memory Grants Pending and Process > Private Bytes for sqlservr.exe.
  • Check Windows Event Viewer under Application Logs for correlating MSSQLSERVER errors or out-of-memory (OOM) warnings.
  • If running in a virtualized environment (Hyper-V on Windows Server 2025), ensure dynamic memory allocation isn’t starving the SQL VM.

Alternative or Verification Steps

  • Re-run the original failing query or stored procedure that invoked the CLR function; confirm no 10313 error appears in the SQL error log (EXEC xp_readerrorlog;).
  • If the error persists, consider rewriting the specific CLR-dependent function using native T-SQL logic to bypass the .NET Framework dependency entirely.

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

Troubleshooting Guide: SQL Server Error 10311 — AppDomain Marked for Unload Due to Memory Pressure

Why This Error Happens

This error occurs when the SQL CLR (Common Language Runtime) host detects that an AppDomain is consuming excessive memory and marks it for unload to relieve pressure on the server. This is typically triggered by inefficient or memory-leaking CLR integration code (SQLCLR assemblies, stored procedures, or functions) running within SQL Server, combined with insufficient memory allocated to the instance or competition from other processes on Windows Server 2025 / Windows 11. It can also surface when the max server memory configuration is set too conservatively, forcing SQL Server to reclaim memory from CLR-hosted AppDomains more aggressively than expected.

Step-by-Step Resolution Guide

Step 1: Identify the Offending AppDomain and Assembly

  • Query sys.dm_clr_appdomains to see which AppDomain is under pressure and note its ID.
  • Cross-reference with sys.dm_clr_loaded_assemblies to identify the specific CLR assembly consuming memory.
  • Check the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for repeated occurrences and timestamps correlating with high load.

Step 2: Review and Adjust SQL Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and run EXEC sp_configure 'show advanced options', 1; RECONFIGURE;.
  • Check current max server memory (MB) setting via EXEC sp_configure 'max server memory';.
  • Increase the value if the OS has sufficient available RAM (leave at least 4-8 GB for Windows Server 2025/Windows 11 OS overhead).
  • Apply changes with RECONFIGURE; and restart the SQL Server service if required via services.msc.

Step 3: Audit and Optimize the CLR Code

  • Review the custom SQLCLR assembly for unmanaged memory leaks, large object allocations, or excessive string manipulation.
  • Rebuild the assembly using .NET Framework 4.8 or later compatibility settings validated against SQL Server 2025 CLR integration requirements.
  • Redeploy using ALTER ASSEMBLY [YourAssemblyName] FROM 'C:\Path\To\UpdatedAssembly.dll' WITH PERMISSION_SET = SAFE;.

Step 4: Enable CLR Strict Security and Resource Governance

  • Confirm clr strict security is enabled: EXEC sp_configure 'clr strict security'; (should be 1 by default in SQL Server 2025).
  • Implement Resource Governor to cap memory usage for CLR-heavy workloads using CREATE RESOURCE POOL and ALTER RESOURCE GOVERNOR RECONFIGURE;.
  • Restart the SQL Server instance for policy changes to take full effect.

Step 5: Monitor System-Level Memory Pressure

  • Open Performance Monitor (perfmon.exe) on Windows Server 2025 and add the counter SQLServer:Memory Manager > Total Server Memory (KB).
  • Compare against Process > Working Set for sqlservr.exe to confirm no external memory contention from other Windows services.

Alternative or Verification Steps

  • Re-run the workload that triggered the original error and monitor sys.dm_clr_appdomains to confirm the AppDomain no longer shows a status of “Unload Requested” or “Unloaded.”
  • If the issue persists, as a temporary workaround, disable and re-enable CLR integration entirely using EXEC sp_configure 'clr enabled', 0; RECONFIGURE; followed by re-enabling it after isolating the problematic assembly, ensuring no production dependencies break during the toggle.

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

Troubleshooting Guide: SQL Server Error 10309 — CLR Assembly Compatibility Warning

Why This Error Happens

This warning occurs when registering a .NET assembly (via CREATE ASSEMBLY) that targets a CLR runtime version or framework profile not explicitly validated against SQL Server’s hosted CLR environment (SQLCLR). It commonly arises because the assembly was compiled against a newer or unsupported .NET target framework, references libraries that rely on APIs restricted inside the SQLCLR sandbox, or was built without the PERMISSION_SET constraints SQL Server expects. In SQL Server 2025 running on Windows Server 2025, stricter CLR host policies and updated .NET integration layers make this check more aggressive than in older versions.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly’s Target Framework

  • Open the project in Visual Studio or inspect the DLL using ildasm.exe / dotnet-ildasm to confirm the target framework version.
  • Ensure the assembly targets a framework version officially supported by SQL Server 2025 SQLCLR hosting (check the current Microsoft documentation matrix for supported CLR versions).
  • Recompile the project targeting .NET Framework 4.8 or the SQL Server–supported CLR runtime if a mismatch is found.

Step 2: Rebuild the Assembly with Correct Permission Set

  • In Visual Studio, set the project’s Permission Level to SAFE, EXTERNAL_ACCESS, or UNSAFE depending on actual requirements (avoid defaulting to UNSAFE).
  • Remove any references to unsupported namespaces (e.g., System.IO file access, threading APIs, or unmanaged code calls) if using SAFE permission.
  • Rebuild the DLL and confirm no build warnings reference incompatible APIs.

Step 3: Register the Assembly Using Explicit Permission Clauses

  • Run the registration command manually with explicit permissions instead of relying on defaults:
CREATE ASSEMBLY MyAssembly
FROM 'C:\SQLAssemblies\MyAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • If EXTERNAL_ACCESS or UNSAFE is required, ensure the database has TRUSTWORTHY set appropriately or the assembly is signed with a certificate trusted by SQL Server:
ALTER DATABASE CURRENT SET TRUSTWORTHY ON;

Step 4: Update SQL Server CLR Integration Settings

  • Confirm CLR integration is enabled on the instance:
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
  • Apply the latest Cumulative Update (CU) for SQL Server 2025, as CLR hosting compatibility lists are frequently patched.
  • Restart the SQL Server service via SQL Server Configuration Manager after applying updates.

Step 5: Re-test Assembly Registration

  • Drop and re-register the assembly in a test database first:
DROP ASSEMBLY IF EXISTS MyAssembly;
  • Re-run the CREATE ASSEMBLY statement and check the SQL Server Error Log for confirmation that no warning (Error 10309) is raised.

Alternative or Verification Steps

  • Query sys.assemblies and sys.assembly_files to confirm the assembly registered successfully with the intended permission_set_desc value.
  • If the warning persists despite a supported framework target, isolate the issue by testing the same DLL registration on a clean SQL Server 2025 instance (no other CLR assemblies loaded) to rule out environment-specific corruption or conflicting assemblies.

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

Troubleshooting Guide: SQL Server Error 10310 – AppDomain Marked for Unload

Why This Error Happens

Error 10310 occurs when SQL Server’s CLR (Common Language Runtime) integration triggers an AppDomain unload because a DDL operation (such as ALTER ASSEMBLY, DROP ASSEMBLY, or a security/permission change) has modified an assembly or database currently in use. This typically happens when CLR-based objects (stored procedures, functions, or triggers) are actively executing while a schema change is applied to the same database, forcing SQL Server to recycle the AppDomain to maintain consistency. It can also surface due to corrupted assembly metadata or conflicting permission updates at the database or server level while CLR code is mid-execution.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting CLR Activity

  • Query sys.dm_clr_appdomains to see which AppDomain is marked for unload and which database it belongs to.
  • Check sys.dm_exec_requests and sys.dm_os_tasks for any long-running CLR procedures or functions executing at the time of the error.
  • Review SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for timestamps correlating with DDL operations.

Step 2: Isolate and Pause Conflicting DDL Operations

  • Avoid running ALTER ASSEMBLY, DROP ASSEMBLY, or ALTER DATABASE ... SET TRUSTWORTHY while CLR procedures are actively executing.
  • Schedule assembly updates or security DDL changes during maintenance windows with minimal active sessions.
  • Use sp_who2 or Activity Monitor to confirm no active CLR sessions are running against the target database before applying changes.

Step 3: Rebuild or Re-register the Affected Assembly

  • Drop and re-create the problematic assembly using:
  ALTER ASSEMBLY YourAssemblyName
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • If corruption is suspected, drop the assembly entirely and re-deploy it from a verified .dll source.

Step 4: Restart the CLR Host Environment

  • Disable and re-enable CLR integration to force a clean AppDomain reload:
  EXEC sp_configure 'clr enabled', 0;
  RECONFIGURE;
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • If the issue persists, restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025.

Step 5: Apply Latest Cumulative Update

  • Verify your SQL Server 2025 build number using SELECT @@VERSION; and compare against the latest Cumulative Update (CU) on Microsoft’s official download page.
  • Install any pending CU, as CLR AppDomain handling bugs are frequently patched in these releases.

Alternative or Verification Steps

  • After applying fixes, re-run the previously failing CLR stored procedure or function and confirm no Error 10310 appears in the Error Log or sys.dm_clr_appdomains output.
  • If the error recurs intermittently, consider isolating CLR-heavy databases onto a dedicated SQL Server instance to prevent cross-database DDL conflicts from triggering AppDomain unloads.

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

Troubleshooting Guide: Error 10307 — Invalid FillRowMethodName in SqlFunctionAttribute

Why This Error Happens

This error occurs when a table-valued function (TVF) implemented as a CLR user-defined function in SQL Server has a SqlFunctionAttribute.FillRowMethodName property that references a method name not found in the assembly, or the method signature does not match the expected format. This typically results from a typo in the method name string, a method that was renamed or removed during development without updating the attribute, or a mismatch between the compiled assembly loaded into SQL Server and the source code being referenced. It can also occur when the assembly registered in SQL Server (via CREATE ASSEMBLY) is an outdated or corrupted version that does not match the current class definitions.

Step-by-Step Resolution Guide

Step 1: Verify the FillRowMethodName String Matches the Actual Method

  • Open the CLR project source file containing the SqlFunction attribute declaration.
  • Confirm the FillRowMethodName = "MethodName" string exactly matches a public static method name in the same class (case-sensitive).
  • Check for extra spaces, incorrect casing, or leftover references to a deleted method.
  • Example of correct syntax:
  [SqlFunction(FillRowMethodName = "FillRow")]
  public static IEnumerable MyTableFunction() { ... }
  public static void FillRow(object obj, out SqlString result) { ... }

Step 2: Confirm the FillRow Method Signature is Valid

  • Ensure the FillRow method is declared as public static void.
  • Verify the first parameter is of type object.
  • Confirm all remaining parameters are passed using the out keyword and use SQL-compatible types (e.g., SqlString, SqlInt32).
  • Rebuild the project in Visual Studio to catch any signature mismatches before redeploying.

Step 3: Rebuild and Redeploy the Assembly in SQL Server

  • In SQL Server Management Studio (SSMS), drop the outdated assembly:
  DROP FUNCTION dbo.MyTableFunction;
  DROP ASSEMBLY MyAssemblyName;
  • Recompile the CLR project into a fresh .dll file.
  • Re-register the assembly and function:
  CREATE ASSEMBLY MyAssemblyName FROM 'C:\Path\To\MyAssembly.dll' WITH PERMISSION_SET = SAFE;
  CREATE FUNCTION dbo.MyTableFunction()
  RETURNS TABLE (...)
  AS EXTERNAL NAME MyAssemblyName.ClassName.MyTableFunction;

Step 4: Clear Cached Metadata and Restart the SQL Server Service

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart the SQL Server (MSSQLSERVER) service to clear any cached CLR metadata.
  • Re-run the CREATE FUNCTION statement to confirm Error 10307 no longer appears.

Alternative or Verification Steps

  • Run SELECT * FROM dbo.MyTableFunction(); in SSMS to confirm the function executes without throwing Error 10307.
  • If the error persists, use a decompiler (such as ILSpy) on the deployed .dll to confirm the FillRow method truly exists in the compiled binary, as a stale build artifact may be the root cause.

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

Troubleshooting Guide: SQL Server Error 10308 — Unsupported .NET Framework Assembly Warning

Why This Error Happens

This warning occurs when SQL Server’s CLR integration detects that an assembly being registered via CREATE ASSEMBLY targets a .NET Framework version or API surface that has not been certified for the SQL Server hosted runtime environment. SQL Server 2025 restricts CLR hosting to a specific subset of .NET functionality for stability and security reasons, and assemblies compiled against unsupported libraries (such as unverifiable code, certain reflection APIs, or newer runtime features) trigger this flag. This is often seen when legacy assemblies or third-party DLLs compiled outside the SAFE/EXTERNAL_ACCESS permission boundaries are pushed into a database without validation.

Step-by-Step Resolution Guide

Step 1: Verify the Assembly’s Permission Set and Target Framework

  • Run SELECT name, permission_set_desc, clr_name FROM sys.assemblies; to check how the assembly is currently registered.
  • Confirm the source DLL was compiled against a supported .NET Framework version (check project properties in Visual Studio under Target Framework).
  • Avoid targeting .NET Standard or .NET Core libraries directly, as SQL CLR only supports specific .NET Framework profiles.

Step 2: Re-register the Assembly with Correct Permissions

  • Drop the existing assembly using DROP ASSEMBLY [YourAssemblyName]; if it is not in use.
  • Re-create it explicitly with a supported permission set:
  CREATE ASSEMBLY [YourAssemblyName]
  FROM 'C:\SQLAssemblies\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Avoid UNSAFE or EXTERNAL_ACCESS permission sets unless absolutely required, as these increase the likelihood of triggering compatibility warnings.

Step 3: Enable and Validate CLR Strict Security Settings

  • Open SQL Server Configuration Manager or SSMS and run:
  EXEC sp_configure 'clr strict security', 1;
  RECONFIGURE;
  • Ensure the assembly is signed with a certificate or asymmetric key and mapped to a login with UNSAFE ASSEMBLY permission if strict security is enforced.
  • Restart the SQL Server service via services.msc on Windows Server 2025 or Windows 11 for the configuration change to take effect.

Step 4: Rebuild the Assembly Using a Supported .NET Framework Version

  • In Visual Studio, change the project’s Target Framework to .NET Framework 4.8 (the last widely supported SQL CLR-compatible version).
  • Recompile the DLL and redeploy it to the path referenced in Step 2.
  • Confirm no references to unsupported namespaces (e.g., System.Net.Http in newer forms) exist in the codebase.

Alternative or Verification Steps

  • Query sys.assembly_modules and check the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm Error 10308 no longer appears after re-registration.
  • If the warning persists, consider migrating the logic out of SQL CLR entirely and into an external service or Azure Function, since Microsoft has been deprecating CLR integration support in favor of modern compute options.

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

Troubleshooting Guide: SQL Server Error 10305 — CLR Table-Valued Function Init Method Missing SqlFunctionAttribute

Why This Error Happens

This error occurs when a CLR table-valued function (TVF) is compiled or deployed with an Init method (used for fill-row/IEnumerable pattern) that lacks the required [SqlFunction] attribute annotation. SQL Server’s CLR integration engine specifically validates that the initialization method is decorated with this attribute to correctly map the FillRowMethodName and return type metadata. Without this annotation, the SQL Server runtime cannot bind the method signature to the TVF schema, causing assembly registration or execution to fail with Error 10305.

Step-by-Step Resolution Guide

Step 1: Locate and Inspect the CLR Source Code

  • Open the .cs or .vb file containing the CLR table-valued function definition in Visual Studio 2022/2025.
  • Identify the method marked as the Init method (the one returning IEnumerable or IEnumerator).
  • Confirm whether [SqlFunction] or [Microsoft.SqlServer.Server.SqlFunction] is present directly above the method declaration.

Step 2: Add the Required SqlFunctionAttribute

  • Add the attribute explicitly above the method, specifying FillRowMethodName, for example:
  [SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "col1 int, col2 nvarchar(100)")]
  public static IEnumerable InitMethod(SqlInt32 param)
  • Ensure the using Microsoft.SqlServer.Server; namespace is included at the top of the file.
  • Save the file and rebuild the project in Release mode.

Step 3: Redeploy the Assembly to SQL Server 2025

  • Drop the existing assembly using:
  DROP FUNCTION dbo.YourTVFName;
  DROP ASSEMBLY YourAssemblyName;
  • Re-register the updated DLL:
  CREATE ASSEMBLY YourAssemblyName
  FROM 'C:\SQLCLR\YourAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Recreate the table-valued function referencing the corrected Init method and class name.

Step 4: Validate CLR Integration Settings

  • Confirm CLR integration is enabled on the instance:
  sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • On Windows Server 2025/Windows 11, verify the .NET Framework (or .NET CLR version supported by SQL Server 2025) is properly installed and not corrupted via sfc /scannow.

Alternative or Verification Steps

  • Run SELECT * FROM dbo.YourTVFName(parameters) in SQL Server Management Studio to confirm the function executes without raising Error 10305.
  • If the error persists, use ildasm.exe on the compiled DLL to verify the [SqlFunction] metadata attribute was actually embedded in the assembly, ensuring no stale DLL is cached in the SQL Server assembly catalog.

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

Troubleshooting Guide: SQL Server Error 10306 — Missing FillRowMethodName Property

Why This Error Happens

This error occurs when a CLR table-valued function (TVF) is defined with a SqlFunctionAttribute but the developer has not explicitly set the FillRowMethodName property in the function’s metadata. SQL Server 2025 requires this property because it tells the engine which method in the assembly is responsible for mapping the data returned by the IEnumerable/IEnumerator Init method into the actual output columns of the table. Without this mapping defined, SQL Server cannot resolve how to populate rows during execution, causing the CLR integration layer to reject the function registration or execution at the point the assembly is loaded or called.

Step-by-Step Resolution Guide

Step 1: Locate the CLR Project Source Code

  • Open the Visual Studio SQL CLR Database Project associated with the deployed assembly.
  • Identify the C# or VB.NET class decorated with [SqlFunction] that defines the table-valued function.
  • Confirm the method signature returns IEnumerable or IEnumerator, which confirms it is intended as a TVF Init method.

Step 2: Edit the SqlFunctionAttribute Declaration

  • Add the FillRowMethodName property directly into the attribute declaration, pointing to the static method that fills the output row.
  • Example correction:
[SqlFunction(FillRowMethodName = "FillRow")]
public static IEnumerable InitMethod(SqlInt32 input)
{
    // Init logic returning enumerable collection
}

public static void FillRow(object obj, out SqlInt32 output)
{
    output = (SqlInt32)obj;
}
  • Ensure the FillRow method name in the attribute string exactly matches the actual method name (case-sensitive) in the class.

Step 3: Rebuild and Redeploy the Assembly

  • In Visual Studio, select Build > Rebuild Solution to compile the corrected DLL.
  • On the SQL Server 2025 instance, drop the outdated assembly using DROP ASSEMBLY YourAssemblyName; (ensure dependent functions are dropped first with DROP FUNCTION).
  • Re-import the updated DLL using CREATE ASSEMBLY YourAssemblyName FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Re-create the table-valued function using CREATE FUNCTION referencing the corrected EXTERNAL NAME binding.

Step 4: Verify SQL CLR Integration Settings

  • On Windows Server 2025, confirm CLR integration is enabled by running:
sp_configure 'clr enabled', 1;
RECONFIGURE;
  • Check that the PERMISSION_SET (SAFE, EXTERNAL_ACCESS, or UNSAFE) matches the trust level required by your assembly to avoid secondary load failures after the fix.

Alternative or Verification Steps

  • Execute the newly created function directly (e.g., SELECT * FROM dbo.YourTableValuedFunction(1);) to confirm no Error 10306 appears and rows are returned correctly.
  • If the error persists, use SELECT * FROM sys.assembly_modules to verify the col_name bindings correctly match the output parameters defined in your FillRow method signature.

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

Troubleshooting Guide: SQL Server Error 10304 – Failed to Enter CLR Host

Why This Error Happens

Error 10304 occurs when SQL Server’s SQLCLR hosting layer cannot successfully initialize or enter the .NET Common Language Runtime, typically because the server is under memory pressure or has hit a virtual address space limit. This can also stem from a misconfigured max server memory setting that leaves insufficient room for the CLR to allocate its AppDomain, or from a corrupted/outdated .NET runtime installation that SQL Server 2025 depends on. In some cases, it is triggered by excessive concurrent CLR AppDomains being spun up without being unloaded, exhausting available worker threads or memory pools.

Step-by-Step Resolution Guide

Step 1: Check and Adjust SQL Server Memory Configuration

  • Open SQL Server Management Studio (SSMS) and run EXEC sp_configure 'max server memory (MB)'; to review current limits.
  • Ensure max server memory is not set so high that it starves the OS and CLR of physical RAM; a common rule is to leave at least 10-20% of total RAM (minimum 4 GB) for the OS and CLR overhead.
  • Reconfigure using EXEC sp_configure 'max server memory (MB)', <new_value>; RECONFIGURE;.

Step 2: Verify and Repair the .NET Runtime Dependency

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 / Windows 11 and confirm the .NET runtime version required by SQL Server 2025 is installed and not flagged as corrupted.
  • Run sfc /scannow from an elevated Command Prompt to check for corrupted system files that may affect the CLR.
  • If corruption is found, repair or reinstall the .NET Framework/Runtime via the offline installer from the Microsoft Download Center.

Step 3: Review and Limit Active CLR AppDomains

  • Query active CLR sessions using SELECT * FROM sys.dm_clr_appdomains; to identify if too many AppDomains are loaded simultaneously.
  • If excessive AppDomains are present, restart the SQL Server instance during a maintenance window to flush the CLR host state: net stop MSSQLSERVER && net start MSSQLSERVER.
  • Review any custom CLR assemblies for memory leaks or unclosed handles that may prevent AppDomain unloading.

Step 4: Increase Virtual Address Space or Enable Lock Pages in Memory

  • Open secpol.msc (Local Security Policy) on the Windows Server 2025 host and navigate to Local Policies > User Rights Assignment.
  • Add the SQL Server service account to the Lock pages in memory policy to prevent the OS from paging out critical SQL Server memory needed by the CLR.
  • Restart the SQL Server service for the policy change to take effect.

Alternative or Verification Steps

  • To verify the fix, run a test CLR-based stored procedure or function and check the SQL Server Error Log (EXEC sp_readerrorlog;) to confirm Error 10304 no longer appears.
  • If the issue persists, as an alternative, temporarily disable and re-enable CLR integration entirely using EXEC sp_configure 'clr enabled', 0; RECONFIGURE; EXEC sp_configure 'clr enabled', 1; RECONFIGURE; to force a clean re-initialization of the hosting environment.

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

Troubleshooting Guide: SQL Server Error 10302 – “Could not get path for SQL Server: ‘%ls'”

Why This Error Happens

This error typically occurs when SQL Server 2025 is unable to resolve or access the file system path referenced in the registry or configuration metadata, often due to corrupted registry keys under the instance’s Setup hive. It can also happen when the SQL Server service account lacks the necessary NTFS permissions to read the installation directory, or when a prior failed patch/upgrade left the SQLPath, SQLBinRoot, or SQLDataRoot registry values pointing to a non-existent or relocated directory. Additionally, this can surface when Windows Server 2025 security policies (such as newly enforced path virtualization or Controlled Folder Access) block the SQL Server process from resolving the path at runtime.

Step-by-Step Resolution Guide

Step 1: Verify the SQL Server Installation Path in the Registry

  • Open regedit and navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.<InstanceName>\Setup.
  • Confirm that the SQLPath, SQLBinRoot, and SQLDataRoot values point to valid, existing directories (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL).
  • If any path is blank, malformed, or points to a deleted folder, this is the root cause — do not edit manually yet; proceed to repair instead.

Step 2: Check NTFS Permissions on the SQL Server Directories

  • Right-click the SQL Server installation folder (typically C:\Program Files\Microsoft SQL Server\) and open Properties > Security.
  • Ensure the service account (e.g., NT Service\MSSQLSERVER or your custom domain service account) has Read, Write, and Modify permissions.
  • Run the following PowerShell command to reapply inherited permissions if needed:
  icacls "C:\Program Files\Microsoft SQL Server" /reset /T /C

Step 3: Run SQL Server Setup Repair

  • Launch SQL Server Installation Center from the Start Menu.
  • Select Maintenance > Repair, then choose the affected instance.
  • Allow the repair wizard to rebuild missing registry path entries and restore binary/data root references automatically.

Step 4: Check Controlled Folder Access and Windows Defender Exclusions

  • Open Windows Security > Virus & threat protection > Manage settings > Controlled folder access.
  • Add sqlservr.exe and the SQL Server data/log directories as allowed applications/exclusions.
  • Restart the SQL Server (MSSQLSERVER) service after applying exclusions.

Step 5: Restart the SQL Server Service and Validate Startup

  • Open SQL Server Configuration Manager.
  • Right-click the affected instance and select Restart.
  • Monitor the SQL Server Error Log (ERRORLOG in the Log folder) for confirmation that the path resolves correctly on startup.

Alternative or Verification Steps

  • Run SELECT SERVERPROPERTY('InstanceDefaultDataPath') and SELECT SERVERPROPERTY('InstanceDefaultLogPath') in SQL Server Management Studio to confirm the paths now resolve without error.
  • If the issue persists after repair, uninstall and reinstall the specific SQL Server instance using a clean installation path, ensuring no legacy registry remnants remain (use the Microsoft SQL Server Uninstall Cleanup Utility beforehand).

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

Troubleshooting Guide: SQL Server Error 10303 — “Could not create AppDomain manager”

Why This Error Happens

This error occurs when the SQL Server CLR (Common Language Runtime) integration layer fails to instantiate a custom AppDomain manager, typically due to corrupted or mismatched .NET Framework/.NET runtime assemblies referenced by SQL Server 2025. It can also result from insufficient permissions on the SQL Server service account to access the CLR hosting policy files, or from a damaged mscoree.dll/hostfxr binding on Windows Server 2025. Additionally, security software or Windows Defender Application Control (WDAC) policies blocking SQL Server’s managed code execution can trigger this failure during instance startup or CLR-enabled query execution.

Step-by-Step Resolution Guide

Step 1: Verify .NET Runtime Integrity

  • Confirm the correct .NET runtime version required by SQL Server 2025 is installed by running dotnet --list-runtimes in an elevated PowerShell prompt.
  • Reinstall or repair the .NET Hosting Bundle via Control Panel > Programs > Programs and Features, selecting the runtime and clicking Repair.
  • Restart the SQL Server (MSSQLSERVER) service after repair completes.

Step 2: Check SQL Server Service Account Permissions

  • Open Services.msc and confirm the account running SQL Server has read/execute permissions on C:\Windows\Microsoft.NET\Framework64\<version>\.
  • Grant explicit Read & Execute permissions on C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ to the service account via right-click Properties > Security.
  • Run sc qc MSSQLSERVER in Command Prompt to confirm the correct service account is configured.

Step 3: Review CLR Strict Security and Enable CLR Integration

  • Open SQL Server Management Studio (SSMS) and run the following to confirm CLR is enabled:
  EXEC sp_configure 'clr enabled', 1;
  RECONFIGURE;
  • Check clr strict security settings, since SQL Server 2025 enforces stricter assembly signing by default:
  EXEC sp_configure 'clr strict security', 1;
  RECONFIGURE;
  • If using custom assemblies, ensure they are signed with a certificate trusted in the master database using CREATE ASSEMBLY ... WITH PERMISSION_SET = SAFE.

Step 4: Inspect Windows Defender / WDAC and Antivirus Exclusions

  • Add exclusions for sqlservr.exe and the SQL Server Binn directory in Windows Defender under Virus & threat protection > Exclusions.
  • If WDAC or AppLocker policies are active, verify that SQL Server’s managed DLLs are included in the allow list via Local Security Policy > Application Control Policies.
  • Re-run the failing operation or restart the SQL Server service to confirm the block is cleared.

Step 5: Rebuild the CLR Hosting Environment (If Issue Persists)

  • Use the SQL Server 2025 Installation Media to run a Repair operation via Setup.exe > Maintenance > Repair.
  • This re-registers CLR hosting components and restores any corrupted sqlservr.exe-to-CLR bindings without affecting databases.
  • Restart the server after repair completes to ensure all hosting policies reload cleanly.

Alternative or Verification Steps

  • After applying fixes, verify resolution by executing a simple CLR-enabled stored procedure or query (e.g., one using SqlFunction or a custom assembly) and confirm it completes without raising Error 10303 in the SQL Server Error Log (ERRORLOG file in the Log directory).
  • If the error persists, consider performing a full uninstall/reinstall of the .NET Hosting Bundle alongside a SQL Server feature repair, as a last resort to eliminate deep runtime corruption.

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

Troubleshooting Guide: SQL Server Error 10301 — Assembly Dependency Reference Failure

Why This Error Happens

Error 10301 occurs when SQL Server attempts to load, alter, or drop a CLR assembly that has a dependency relationship with another assembly, but that dependent assembly reference is broken, mismatched in version, or missing from the database. This typically happens after an in-place upgrade to SQL Server 2025, a database migration, or a manual deployment where the referenced assembly was dropped, updated independently, or never registered with matching permission sets (SAFE, EXTERNAL_ACCESS, or UNSAFE). It can also surface when the CLR assembly catalog metadata (sys.assembly_references) becomes inconsistent due to corrupted system catalog entries or an incomplete transaction during assembly registration.

Step-by-Step Resolution Guide

Step 1: Identify the Broken Assembly Reference

  • Run the following query to find the exact assembly and its dependency:
SELECT a.name AS AssemblyName, ar.referenced_assembly_id, a2.name AS ReferencedAssemblyName
FROM sys.assemblies a
LEFT JOIN sys.assembly_references ar ON a.assembly_id = ar.assembly_id
LEFT JOIN sys.assemblies a2 ON ar.referenced_assembly_id = a2.assembly_id
WHERE a.name = 'YourAssemblyName';
  • Check the SQL Server Error Log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full error context, including the exact assembly names referenced in the 10301 message.

Step 2: Re-register the Missing or Mismatched Assembly

  • Drop the dependent assembly chain in the correct order (dependents first, then the parent assembly) using:
DROP ASSEMBLY [DependentAssemblyName];
DROP ASSEMBLY [ParentAssemblyName];
  • Re-create both assemblies in the correct dependency order, ensuring the referenced assembly is created before the one that depends on it:
CREATE ASSEMBLY [ParentAssemblyName]
FROM 'C:\SQLAssemblies\ParentAssembly.dll'
WITH PERMISSION_SET = SAFE;

CREATE ASSEMBLY [DependentAssemblyName]
FROM 'C:\SQLAssemblies\DependentAssembly.dll'
WITH PERMISSION_SET = SAFE;
  • Confirm both DLL files exist at the specified path and that the binary versions match what was originally compiled against the database schema.

Step 3: Validate CLR Integration and Trust Settings

  • Ensure CLR integration is enabled on the instance:
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
  • On SQL Server 2025 / Windows Server 2025, verify the assembly is signed and trusted if using EXTERNAL_ACCESS or UNSAFE permission sets:
EXEC sp_configure 'clr strict security', 1;
sys.sp_add_trusted_assembly @hash, N'Description';
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) to clear any cached assembly metadata.

Step 4: Rebuild Corrupted System Catalog Metadata (If Needed)

  • If the reference remains broken after re-registration, run DBCC CHECKDB on the affected database to rule out catalog corruption:
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If corruption is confirmed in system tables, restore the database from the most recent verified backup rather than attempting manual catalog edits.

Alternative or Verification Steps

  • Verify the fix by querying sys.assembly_references again and confirming no NULL or orphaned referenced_assembly_id values remain for the affected assembly.
  • As an alternative, export the CLR object definitions (stored procedures, functions, triggers) tied to the assembly, drop all related assemblies entirely, and redeploy them as a fresh, correctly ordered script using SQL Server Management Studio (SSMS) 21 or Azure Data Studio.

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

Troubleshooting Guide: Error 10240 – Could Not Find UdtExtensions.dll

Why This Error Happens

This error typically occurs when the SQL Server installation directory is missing the UdtExtensions.dll file due to an incomplete, corrupted, or interrupted installation/update process. It can also happen if antivirus software or Windows Defender quarantined the file, or if a repair/patch operation did not correctly register the shared components in the Binn directory. Additionally, incorrect file system permissions on the SQL Server installation folder can prevent the service from locating or loading the DLL at startup.

Step-by-Step Resolution Guide

Step 1: Verify the File Exists in the Installation Directory

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ (adjust the version folder, e.g., MSSQL17 for SQL Server 2025).
  • Check if UdtExtensions.dll is present; if missing, this confirms file corruption or deletion.
  • Check Windows Defender / third-party antivirus quarantine logs for any recent removal of this file.

Step 2: Restore the Missing File via Repair Installation

  • Open Control Panel > Programs and Features, locate Microsoft SQL Server 2025, and select Uninstall/Change.
  • Choose Repair from the SQL Server Installation Center wizard.
  • Allow the repair process to complete fully, then restart the SQL Server (MSSQLSERVER) service via services.msc.

Step 3: Manually Copy the DLL from Installation Media (If Repair Fails)

  • Mount the original SQL Server 2025 ISO or extract the setup package.
  • Locate UdtExtensions.dll within the \x64\Setup\ or corresponding redistributable folder.
  • Copy the file directly into C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\.
  • Ensure the NT SERVICE\MSSQLSERVER account has Read & Execute permissions on the file (right-click > Properties > Security).

Step 4: Reset Permissions and Re-register Components

  • Run Command Prompt as Administrator and navigate to the Binn directory.
  • Execute icacls UdtExtensions.dll /reset to clear any corrupted ACL entries.
  • Restart the SQL Server service and monitor the SQL Server Error Log for Error 10240 recurrence.

Alternative or Verification Steps

  • Verify the fix by restarting the SQL Server service and checking the Application Event Viewer (Event ID 10240) to confirm the error no longer appears.
  • If the issue persists, perform a full uninstall and clean reinstall of the SQL Server Database Engine component, ensuring no leftover files remain in Program Files\Microsoft SQL Server\.

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

Troubleshooting Guide: SQL Server Error 10300 — Assembly Dependency Reference Conflict

Why This Error Happens

Error 10300 occurs when a SQL CLR assembly being created, altered, or restored has a dependency on another assembly, but that referenced assembly either does not exist in the database, has a mismatched version, or has a different permission set (SAFE, EXTERNAL_ACCESS, or UNSAFE) than what the dependency chain requires. This commonly happens after a database migration, a restore from backup, or an in-place upgrade to SQL Server 2025, where assembly metadata references break due to missing binaries or an incomplete deployment order. It can also surface on Windows Server 2025 / Windows 11 hosts when CLR strict security settings block trust for unsigned or improperly catalogued assemblies.

Step-by-Step Resolution Guide

Step 1: Identify the Broken Assembly Reference

  • Run the following query to list all assemblies and their dependency references:
  SELECT a.name AS AssemblyName, ar.referenced_assembly_id, a2.name AS ReferencedAssembly
  FROM sys.assemblies a
  LEFT JOIN sys.assembly_references ar ON a.assembly_id = ar.assembly_id
  LEFT JOIN sys.assemblies a2 ON ar.referenced_assembly_id = a2.assembly_id;
  • Note which assembly name from the error message (%.*ls) is missing or shows a NULL reference.
  • Check the SQL Server error log for the full exception text, including the specific assembly GUID or version mismatch.

Step 2: Re-register the Missing or Mismatched Assembly

  • Drop the broken assembly reference chain in the correct dependency order (drop dependents first):
  DROP ASSEMBLY [DependentAssemblyName];
  • Re-create the missing referenced assembly using the correct DLL binary and permission set:
  CREATE ASSEMBLY [ReferencedAssemblyName]
  FROM 'C:\SQLAssemblies\ReferencedAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Ensure the permission set matches across the entire dependency chain (a SAFE assembly cannot reference an UNSAFE one).

Step 3: Validate CLR Strict Security and Trust Settings

  • On SQL Server 2025 with CLR strict security enabled, confirm the assembly is signed and trusted:
  SELECT * FROM sys.trusted_assemblies;
  • If untrusted, add the assembly hash manually:
  EXEC sp_add_trusted_assembly @hash = 0x<SHA512_HASH>, @description = N'ReferencedAssembly';
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025 to refresh the CLR trust cache.

Step 4: Re-deploy Dependent Assemblies in Correct Order

  • Re-create the original dependent assembly now that its reference exists:
  CREATE ASSEMBLY [DependentAssemblyName]
  FROM 'C:\SQLAssemblies\DependentAssembly.dll'
  WITH PERMISSION_SET = SAFE;
  • Re-link any CLR stored procedures, functions, or triggers that depended on the dropped assembly.

Alternative or Verification Steps

  • Verify the fix by querying sys.assemblies and sys.assembly_files to confirm all referenced assemblies now resolve without NULL entries, then execute any CLR procedures that previously failed.
  • If the error persists, extract the DLL dependency tree using a tool like ILSpy or dumpbin /dependents on Windows 11/Server 2025 to confirm no external native dependencies are missing from the assembly manifest.

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

Troubleshooting Guide: SQL Server Error 10211 — “Cannot invoke mutator on a null CLR type value”

Why This Error Happens

This error occurs when a SQL CLR user-defined type (UDT) or user-defined aggregate attempts to call a mutator method on an instance that has not been properly initialized and is currently null at the CLR level. This is typically caused by corrupted or mismatched CLR assembly binaries (DLLs) registered in SQL Server, often resulting from an incomplete assembly deployment, a version mismatch after an in-place upgrade to SQL Server 2025, or missing null-checking logic in custom CLR type implementations. It can also surface when the .NET runtime hosted inside SQL Server (SQLCLR) fails to correctly instantiate the object before a write/update operation (mutator) is invoked against it.

Step-by-Step Resolution Guide

Step 1: Verify CLR Integration Status and Assembly Health

  • Open SSMS and run sp_configure 'clr enabled'; to confirm CLR integration is turned on (value should be 1).
  • Query SELECT * FROM sys.assemblies WHERE is_user_defined = 1; to list all custom CLR assemblies loaded in the affected database.
  • Check for assemblies marked with permission_set_desc that may be outdated due to the 2025 security model changes (UNSAFE/EXTERNAL_ACCESS assemblies require stricter trust validation now).

Step 2: Re-register the Faulty CLR Assembly

  • Drop the problematic assembly using: DROP ASSEMBLY [YourAssemblyName];
  • Re-add the assembly from a freshly compiled DLL: CREATE ASSEMBLY [YourAssemblyName] FROM 'C:\SQLCLR\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
  • Ensure the DLL was compiled against the .NET runtime version supported by SQL Server 2025 (avoid mixing .NET Framework 4.8 assemblies with newer .NET builds).
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator).

Step 3: Patch or Update the CLR Type Source Code

  • If you own the source code for the custom type/aggregate, inspect the Write(BinaryWriter w) or mutator methods for missing null checks before field assignment.
  • Add defensive coding such as if (this.IsNull) throw new SqlNullValueException(); prior to any mutator call.
  • Recompile the assembly in Visual Studio 2022/2025 targeting the correct SQL CLR integration package, then redeploy using Step 2.

Step 4: Check for Corrupted System Catalog Entries

  • Run DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out metadata corruption affecting CLR type bindings.
  • If corruption is found in CLR-related system tables, restore the database from the last known good backup rather than attempting manual repair.

Alternative or Verification Steps

  • To verify the fix, execute the specific INSERT/UPDATE statement that previously triggered Error 10211 against a test row containing the CLR type column — it should complete without exception.
  • As an alternative/workaround, disable and reinstall CLR integration entirely via EXEC sp_configure 'clr enabled', 0; RECONFIGURE; followed by re-enabling it, then re-deploy all custom assemblies from source to eliminate any residual binary corruption.

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

Troubleshooting Guide: SQL Server Error 10227

Why This Error Happens

Error 10227 occurs when a data manipulation statement (UPDATE or INSERT) attempts to modify a computed column, a column defined with a persisted rule, or a field marked as read-only within a CLR user-defined type (UDT). SQL Server 2025 enforces strict metadata validation on these field types, rejecting any direct write operation that bypasses the defined computation logic or assembly method. This typically surfaces after a schema migration, a CLR assembly update, or when application code (ORM-generated SQL) incorrectly includes read-only columns in its UPDATE/INSERT column list.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Type Definition

  • Open SQL Server Management Studio (SSMS) and run the following query to inspect the table schema:
  SELECT name, is_computed, system_type_id 
  FROM sys.columns 
  WHERE object_id = OBJECT_ID('YourSchema.YourTableName');
  • Check the is_computed flag; if it returns 1, the column is computed and cannot be targeted directly in an UPDATE statement.
  • Cross-reference the %.*ls.%.*ls type referenced in the Event ID 10227 log entry with sys.assembly_types if a CLR UDT is involved.

Step 2: Correct the Application Query Logic

  • Modify the application or stored procedure code to exclude the read-only/computed column from the explicit column list in the INSERT INTO (...) or SET clause.
  • If using an ORM (e.g., Entity Framework, Dapper), update the model/mapping configuration to mark the specific property as [DatabaseGenerated(DatabaseGeneratedOption.Computed)] or equivalent, preventing the framework from generating write operations for that field.
  • Example of a corrected query:
  -- Incorrect: UPDATE Orders SET TotalPrice = 100, OrderDate = GETDATE()
  -- Corrected: UPDATE Orders SET OrderDate = GETDATE() 
  -- (Assuming TotalPrice is a computed column)

Step 3: Validate CLR Assembly Permissions (If Applicable)

  • If the error originates from a CLR User-Defined Type method marked as IsMutator = false, verify the assembly permission set in SQL Server 2025.
  • Navigate to Object Explorer > Databases > YourDB > Programmability > Assemblies.
  • Right-click the specific assembly, select Properties, and ensure the Permission Set is correctly configured (e.g., SAFE or EXTERNAL_ACCESS) depending on the UDT’s requirements, as misconfigured permissions can sometimes trigger metadata locks that mimic this error.

Step 4: Rebuild Views or Dependent Objects

  • If the computed column definition was recently altered, stale metadata in dependent views might cause this error.
  • Run sp_refreshview on all views referencing the table in Windows Server 2025 environments to force a metadata refresh:
  EXEC sp_refreshview 'YourSchema.YourViewName';

Alternative or Verification Steps

  • Verify the Fix: Re-run the original UPDATE or INSERT statement in a test environment (Windows 11 development instance or SSMS query window) after removing the read-only column from the query; a successful execution with “Rows affected” confirms resolution.
  • Alternative Solution: If the column must programmatically receive a value, consider dropping the COMPUTED constraint and replacing the logic with an INSTEAD OF trigger that handles the calculation separately from the direct write command.

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

Troubleshooting Guide: SQL Server Error 10151 – Indexed View Creation Failure with ANTISEMI/SEMI Join

Why This Error Happens

This error occurs because SQL Server’s indexed view engine cannot materialize a view whose query plan relies on ANTISEMI or SEMI join logic, which is typically generated by NOT IN, NOT EXISTS, IN, or EXISTS subquery constructs. Indexed views require deterministic, schema-bound queries that resolve to standard INNER or OUTER join logic, so the optimizer rejects the CREATE INDEX operation on the view. This is a design limitation rather than a corruption or permissions issue—the underlying T-SQL syntax used inside the view definition is fundamentally incompatible with indexed view materialization.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Clause in the View Definition

  • Open the view definition using sp_helptext 'YourViewName' in SSMS or Azure Data Studio.
  • Look specifically for NOT IN, NOT EXISTS, IN (SELECT...), or EXISTS (SELECT...) subqueries — these are the primary triggers for ANTISEMI/SEMI joins.
  • Check the estimated execution plan (Ctrl+L) for the SELECT statement powering the view; look for “Left Anti Semi Join” or “Left Semi Join” operators.

Step 2: Rewrite the Query Using JOIN-Compatible Logic

  • Replace NOT EXISTS or NOT IN patterns with a LEFT OUTER JOIN ... WHERE RightTable.Key IS NULL construct.
  • Replace EXISTS or IN subqueries with a standard INNER JOIN against the referenced table, using DISTINCT if row duplication becomes a concern.
  • Re-validate the query logic in SSMS by running it standalone (without the view wrapper) to confirm row-count parity with the original subquery version.

Step 3: Rebuild the Schema-Bound View

  • Drop the existing view: DROP VIEW dbo.YourViewName;
  • Recreate it with SCHEMABINDING enabled, pointing to the rewritten JOIN logic:
CREATE VIEW dbo.YourViewName
WITH SCHEMABINDING
AS
SELECT ...
FROM dbo.TableA a
LEFT JOIN dbo.TableB b ON a.Key = b.Key
WHERE b.Key IS NULL;
  • Ensure all referenced tables use two-part naming (dbo.TableName) as required by SCHEMABINDING.

Step 4: Recreate the Unique Clustered Index

  • Run the original failing index creation statement again:
CREATE UNIQUE CLUSTERED INDEX IX_YourView_Index
ON dbo.YourViewName (KeyColumn);
  • Confirm no Error 10151 or related schema-binding errors (10112, 10116) are returned.

Step 5: Validate on Windows Server 2025 / Windows 11 Environment

  • Check SQL Server error logs at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for any residual schema-binding warnings.
  • Restart the SQL Server service via services.msc or Restart-Service MSSQLSERVER in PowerShell (run as Administrator) if metadata caching issues persist after the rewrite.

Alternative or Verification Steps

  • Verify success by querying sys.indexes and sys.views to confirm the clustered index now exists on the view (is_indexable = 1 should show no blocking flags).
  • If rewriting the JOIN logic isn’t feasible due to complex business rules, consider converting the object to a regular (non-indexed) view or materializing the result set into a physical staging table via a scheduled SQL Agent job instead.

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

Troubleshooting Guide: Error 10149 – SNAPSHOT_MATERIALIZATION Index Cannot Be Created on View with Memory-Optimized Tables

Why This Error Happens

This error occurs because SQL Server does not support creating an index with SNAPSHOTMATERIALIZATION on a view when that view’s definition references one or more memory-optimized (In-Memory OLTP) tables. The SNAPSHOTMATERIALIZATION property relies on a materialization mechanism that is architecturally incompatible with the Hekaton storage engine used by memory-optimized tables. This is a design limitation rather than a configuration error, meaning no amount of permission changes or server tuning will resolve it—the view definition itself must be altered.

Step-by-Step Resolution Guide

Step 1: Identify the Memory-Optimized Tables in the View Definition

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) to inspect the full view definition.
  • Cross-reference each table referenced in the view against sys.tables by checking the is_memory_optimized column:
  SELECT name, is_memory_optimized FROM sys.tables WHERE is_memory_optimized = 1;
  • Note which table(s) are causing the conflict before proceeding.

Step 2: Remove or Modify the SNAPSHOT_MATERIALIZATION Clause

  • Open the CREATE INDEX or CREATE VIEW script that is failing.
  • Remove the WITH (SNAPSHOT_MATERIALIZATION = ON) option from the index definition.
  • If the index is required for performance reasons, consider creating a standard clustered or nonclustered index instead, without the snapshot materialization property:
  CREATE UNIQUE CLUSTERED INDEX IX_YourView_Index 
  ON dbo.YourViewName (YourColumn);

Step 3: Redesign the View to Separate Memory-Optimized Logic

  • If the materialized index is critical, refactor the view so it does not directly reference memory-optimized tables.
  • Create an intermediate disk-based staging table that periodically copies data from the memory-optimized table (via a scheduled job or trigger).
  • Point the view requiring SNAPSHOT_MATERIALIZATION at the disk-based staging table instead.

Step 4: Validate Database Compatibility Level

  • Confirm the database is running on a compatibility level that supports your intended indexing strategy:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is outdated (below 160), update it using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • After applying changes, re-run the CREATE INDEX statement and confirm it completes without Error 10149 appearing in the SQL Server Error Log or SSMS output pane.
  • As an alternative, if memory-optimized tables are not strictly required for the underlying workload, consider converting them back to disk-based tables using CREATE TABLE ... WITH (MEMORY_OPTIMIZED = OFF) migration scripts, which eliminates the conflict entirely.

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

Troubleshooting Guide: Error 10150 – Cannot Create View Referencing Inlineable Scalar UDF

Why This Error Happens

This error occurs because SQL Server 2025 attempts to determine whether a scalar User-Defined Function (UDF) referenced in a view is “inlineable” (eligible for Scalar UDF Inlining optimization), but encounters a structural conflict that prevents the view from being created or bound. This typically happens when the UDF relies on features incompatible with inlining—such as certain system functions, error handling constructs, or non-deterministic operations—while the database engine still attempts to treat it as inlineable during view schema binding. The root cause is usually a mismatch between the database compatibility level and the UDF’s internal logic, or the UDF was altered after the view was originally created without a corresponding schema refresh.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting UDF and View Definition

  • Run sys.sql_expression_dependencies to locate the exact scalar UDF referenced by the failing view.
  • Use the query: SELECT * FROM sys.sql_modules WHERE object_id = OBJECT_ID('YourViewName') to inspect the view’s T-SQL definition.
  • Check sys.sql_modules.is_inlineable column for the UDF to confirm its current inlining eligibility status.

Step 2: Disable Scalar UDF Inlining for the Specific Function

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Alter the UDF definition to include the WITH INLINE = OFF clause:
  ALTER FUNCTION dbo.YourFunctionName (...)
  RETURNS ...
  WITH INLINE = OFF
  AS
  BEGIN
  ...
  END
  • Save and execute the script to force the engine to treat the UDF as non-inlineable, bypassing the conflict.

Step 3: Verify Database Compatibility Level

  • Navigate to Database Properties > Options in SSMS, or run:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the compatibility level is set to 170 (SQL Server 2025) using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;
  • Mismatched compatibility levels (e.g., a database still on level 150 or 160) can cause inconsistent inlining behavior.

Step 4: Recreate the View

  • Drop the existing broken view using DROP VIEW YourViewName;.
  • Recreate the view using CREATE VIEW with the original SELECT statement now referencing the updated UDF.
  • Confirm no syntax errors are thrown and the view binds successfully to the schema.

Step 5: Update Statistics and Refresh Metadata

  • Run EXEC sp_refreshsqlmodule 'YourViewName'; to force SQL Server to refresh the cached metadata for the view.
  • This ensures the Query Optimizer re-evaluates the UDF inlining eligibility with the corrected settings.

Alternative or Verification Steps

  • Verify the Fix: Attempt to create the view again using CREATE VIEW or ALTER VIEW; if successful, run a SELECT * FROM YourViewName to confirm data retrieval works without throwing Error 10150.
  • Alternative Solution: If disabling inlining is not desirable for performance reasons, rewrite the scalar UDF logic to avoid non-inlineable constructs (such as TRY/CATCH blocks, recursive calls, or references to non-deterministic system functions) so it natively passes the inlineability check.

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

Troubleshooting Guide: Error 10148 – Cannot Create Object on View Using OPENJSON

Why This Error Happens

Error 10148 occurs because SQL Server 2025 does not permit the creation of indexed views, schema-bound views, or certain other dependent objects (such as indexes or statistics) on a view definition that references the OPENJSON function. This restriction exists because OPENJSON is non-deterministic in how it parses and shreds JSON data, meaning SQL Server cannot guarantee consistent row-set output required for schema binding or indexing. Consequently, the query optimizer blocks the operation to prevent data integrity issues within the indexed structure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) to inspect the view’s underlying T-SQL code.
  • Locate the specific OPENJSON clause causing the conflict, usually found in the FROM or CROSS APPLY section of the query.
  • Confirm if the action was an attempt to create an index, a schema-bound view, or a full-text index on this object.

Step 2: Refactor the Logic Using a Table-Valued Function or Materialization

  • Instead of referencing OPENJSON directly inside the view, move the JSON parsing logic into a scheduled ETL (Extract, Transform, Load) process that writes results to a physical, persisted table.
  • Alternatively, create an intermediate table variable or a Table-Valued Function (TVF) that processes the JSON separately from the view logic to avoid the function being embedded in the view that requires indexing.
  • Update the application connection strings or stored procedures to query this new persisted table instead of the live view.

Step 3: Remove Schema Binding Requirements

  • If an indexed view is not strictly necessary, modify the CREATE VIEW statement to remove the WITH SCHEMABINDING option.
  • Execute the following command structure in SSMS or Azure Data Studio to update the view without binding:
  • ALTER VIEW YourViewName AS SELECT * FROM OPENJSON(@json) WITH (...)
  • Ensure no CREATE UNIQUE CLUSTERED INDEX commands are executed against this specific view afterward.

Step 4: Pre-Process JSON Data at the Source

  • Modify the application layer or the stored procedure to shred the JSON data into relational columns before inserting it into the base table.
  • Store the parsed values in standard NVARCHAR, INT, or DATETIME2 columns rather than keeping the raw JSON blob to be parsed later by the view.
  • This eliminates the need for OPENJSON within the view entirely, allowing the view to be freely indexed or schema-bound.

Alternative or Verification Steps

  • Verification: After altering the view, attempt to re-run the original CREATE INDEX or CREATE VIEW ... WITH SCHEMABINDING command; if the refactor was successful, Error 10148 will no longer appear in the SSMS “Messages” tab.
  • Alternative: If performance on JSON parsing is the primary concern rather than indexing, consider using Computed Columns marked as PERSISTED on the base table to extract specific JSON values, as persisted computed columns can be indexed independently of the view’s OPENJSON restriction.

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

Troubleshooting Guide: Error 10146 – Cannot Create View Using SEMANTICSIMILARITYTABLE

Why This Error Happens

Error 10146 occurs because SQL Server does not permit views, indexed views, or certain other database objects to be created directly on top of a query that uses SEMANTICSIMILARITYTABLE. This is a structural limitation tied to how semantic search full-text functions operate, as they are rowset functions that rely on execution-time context and cannot be persisted or bound as a static schema object like a view. Additionally, this can be triggered or masked by an improperly configured or missing Semantic Language Statistics Database, which causes SQL Server to throw inconsistent errors when the view-binding operation is attempted.

Step-by-Step Resolution Guide

Step 1: Rewrite the Query to Avoid Direct View Binding

  • Do not wrap SEMANTICSIMILARITYTABLE directly inside a CREATE VIEW statement.
  • Instead, convert the logic into an Inline Table-Valued Function (iTVF) or a standard Stored Procedure.
  • Example syntax to use instead of a view:
CREATE FUNCTION dbo.fn_GetSemanticMatches(@DocID INT)
RETURNS TABLE
AS
RETURN 
(
    SELECT *
    FROM SEMANTICSIMILARITYTABLE(YourTable, YourColumn, @DocID)
);

Step 2: Verify Semantic Search Feature Installation

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Navigate to Instance Name > Databases > System Databases and confirm the semanticsdb exists.
  • If missing, re-run the SQL Server 2025 installation media, select Modify, and ensure the Full-Text and Semantic Extractions for Search component is checked.
  • Attach the semantic database using the following path if reinstalled manually:
    C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\FTData\

Step 3: Register the Semantic Database Correctly

  • Run the following script to ensure the semantic database is correctly registered to your instance (replace semanticsdb if renamed):
EXEC sp_fulltext_semantic_register_language_statistics_db @dbname = N'semanticsdb';
  • Restart the SQL Server (MSSQLSERVER) service via services.msc on your Windows Server 2025 machine to apply the registration.

Step 4: Validate Underlying Table Permissions

  • Ensure the executing user has SELECT permissions on the base table referenced in the SEMANTICSIMILARITYTABLE argument.
  • Check permissions using:
SELECT * FROM fn_my_permissions('dbo.YourTable', 'OBJECT');

Alternative or Verification Steps

  • Verification: Execute the newly created Inline Table-Valued Function (e.g., SELECT * FROM dbo.fn_GetSemanticMatches(1)) to confirm it returns rows without throwing Error 10146.
  • Alternative: If a “view-like” object is strictly required for third-party reporting tools, create a standard view that calls the Table-Valued Function via a CROSS APPLY, rather than invoking SEMANTICSIMILARITYTABLE directly inside the view definition.

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

Troubleshooting Guide: Error 10147 – Cannot Create Object on Temporal View Using FOR SYSTEM_TIME

Why This Error Happens

This error occurs because SQL Server 2025 does not permit certain DDL operations—such as creating views, indexes, or triggers—directly on top of a query that references the FOR SYSTEM_TIME temporal clause. The engine restricts this because temporal queries rely on dynamic historical joins between the current and history tables, which cannot be reliably bound to a static object definition. Essentially, you are attempting to persist an object based on a “point-in-time” dataset rather than a standard table structure, which violates SQL Server’s schema-binding rules for temporal tables.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object Definition

  • Open SQL Server Management Studio (SSMS) and locate the script for the view mentioned in the error (%.*ls).
  • Check the view definition using sp_helptext 'ViewName'; to confirm if FOR SYSTEM_TIME ALL or BETWEEN clauses are present in the underlying SELECT statement.
  • Note that this restriction applies specifically to creating new objects (like indexed views) on top of this logic, not to the simple querying of temporal data.

Step 2: Refactor the Query Using a Table-Valued Function

  • Since you cannot schema-bind an object directly to a temporal clause, encapsulate the temporal logic inside an Inline Table-Valued Function (iTVF) instead of a View.
  • Create the function:
CREATE FUNCTION dbo.GetHistoricalData()
RETURNS TABLE
AS
RETURN
(
    SELECT * FROM dbo.YourTable FOR SYSTEM_TIME ALL
);
  • Update your application or reporting logic to call SELECT * FROM dbo.GetHistoricalData() instead of querying the restricted view.

Step 3: Remove Temporal Clauses from View Definitions

  • If a Table-Valued Function is not suitable for your architecture, modify the view to remove the FOR SYSTEM_TIME clause entirely.
  • Ensure the view only queries the current (actively versioned) table.
  • Move the temporal history logic into the application layer or a stored procedure where FOR SYSTEM_TIME is executed as part of a direct SELECT statement rather than a nested view definition.

Step 4: Verify System-Versioning Configuration

  • Navigate to the table properties in SSMS Object Explorer to confirm “System Versioning” is set to ON.
  • Check the history table path (usually under the same schema) to ensure it has not been corrupted or orphaned, as this can sometimes trigger unexpected binding errors during view creation on Windows Server 2025 configurations.

Alternative or Verification Steps

  • Verify the Fix: Run CREATE VIEW or the specific DDL command that previously failed. If using the iTVF method, execute SELECT * FROM dbo.GetHistoricalData() WHERE [DateColumn] = '2024-01-01'; to confirm historical data is still accessible without the 10147 error.
  • Alternative Workaround: If refactoring is not immediately possible, use a temporary table (#TempHistory) to store the results of a FOR SYSTEM_TIME query first, and then build subsequent logic (like indexes) on top of the temporary table rather than a persistent view.

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

Troubleshooting Guide: Error 10144 – Cannot Create Object on View Using CHANGETABLE

Why This Error Happens

This error occurs because SQL Server 2025 does not permit the creation of indexes, triggers, or statistics directly on a view that references the CHANGETABLE function. CHANGETABLE is a Change Tracking construct designed to return transient row-version metadata, and because its result set is not deterministic in the same way standard table data is, SQL Server blocks schema-binding operations like %S_MSG (typically an index or trigger) against it. Essentially, the engine treats views containing CHANGETABLE as non-indexable and non-schema-bindable by design, regardless of permissions or server configuration.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Run the following query to inspect the view causing the error:
  • sp_helptext 'YourViewName';
  • Confirm that the view body contains a call to CHANGETABLE(CHANGES ... , ...).
  • Note the object type you are trying to create (index, trigger, or statistics) as referenced by %S_MSG in the error text.

Step 2: Remove the Unsupported Operation on the View

  • Drop the index, trigger, or statistics creation statement targeting the view:
  • DROP INDEX IX_YourIndexName ON YourViewName; (if applicable)
  • Do not attempt to re-run CREATE INDEX, CREATE TRIGGER, or CREATE STATISTICS directly against views containing CHANGETABLE.

Step 3: Redesign the Query Logic Using a Staging Table

  • Instead of indexing the view, materialize the CHANGETABLE output into a physical staging table:
  • SELECT * INTO #ChangeStaging FROM CHANGETABLE(CHANGES dbo.YourTable, @last_sync_version) AS CT;
  • Apply your required index, trigger, or statistics object to #ChangeStaging or a permanent table instead of the original view.
  • Update any application logic or stored procedures to query the staging table rather than the view.

Step 4: Validate Change Tracking Configuration

  • Confirm Change Tracking is properly enabled at the database and table level:
  • SELECT * FROM sys.change_tracking_databases;
  • SELECT * FROM sys.change_tracking_tables;
  • Ensure retention settings (CHANGE_RETENTION) are sufficient for your sync window to avoid needing workarounds that reintroduce CHANGETABLE into indexed views.

Step 5: Restart Dependent Services (If Using SQL Agent Jobs)

  • If the view was referenced by a SQL Server Agent job or automated ETL process, restart the SQL Server Agent service on Windows Server 2025:
  • Open services.msc, locate SQL Server Agent (MSSQLSERVER), right-click and select Restart.
  • Re-run the job to confirm it now uses the staging table instead of the original view.

Alternative or Verification Steps

  • Verify the fix by re-executing the original CREATE INDEX / CREATE TRIGGER statement against the new staging table — it should complete without Error 10144.
  • As an alternative, if indexing isn’t strictly required, simply query the view directly in application code without wrapping it in schema-bound objects, since CHANGETABLE output can be consumed ad hoc without indexing.

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

Troubleshooting Guide: SQL Server Error 10145 — Indexed View on Sparse Column Set

Why This Error Happens

This error occurs because SQL Server does not allow indexed views to reference sparse column sets, since sparse column sets are internally represented as XML-like aggregations of sparse columns rather than a single stable column value. When you attempt to create a unique clustered index on a view that directly or indirectly selects a column set, the indexing engine rejects the operation because it cannot guarantee the deterministic, persisted binary representation required for indexing. This typically happens after a table schema was modified to include WITH (COLUMN_SET FOR ALL_SPARSE_COLUMNS) and an existing or new view built on that table is later indexed.

Step-by-Step Resolution Guide

Step 1: Identify the View and Underlying Table Definition

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Check the SELECT statement for a wildcard (SELECT *) or explicit reference to the column set name (commonly named something like AllSparseCols or similar).
  • Cross-reference the base table using sys.columns to confirm which column is flagged with is_column_set = 1:
  SELECT name, is_column_set FROM sys.columns WHERE object_id = OBJECT_ID('YourBaseTable');

Step 2: Remove the Sparse Column Set Reference from the View

  • Edit the view definition using ALTER VIEW to explicitly list only the required non-sparse columns, excluding the column set.
  • Example:
  ALTER VIEW dbo.YourViewName
  WITH SCHEMABINDING
  AS
  SELECT Col1, Col2, Col3
  FROM dbo.YourBaseTable;
  • Avoid SELECT *, as it will implicitly pull in the column set alias if it exists on the base table.

Step 3: Recreate the Index Without the Column Set Dependency

  • Once the view is schema-bound and no longer references the column set, attempt the index creation again:
  CREATE UNIQUE CLUSTERED INDEX IX_YourView_Index
  ON dbo.YourViewName (Col1);
  • Confirm the index build completes without throwing Error 10145.

Step 4: If Sparse Data Is Required, Query Individual Columns Instead

  • Rather than referencing the column set, modify the view to pull individual sparse columns by name (not the aggregated set).
  • Since individual sparse columns are permitted in indexed views as long as they are not part of a COLUMN_SET, list them explicitly:
  SELECT SparseCol1, SparseCol2 FROM dbo.YourBaseTable;

Alternative or Verification Steps

  • Verify the fix by querying sys.indexes and sys.views to confirm the index now exists and the view’s is_schema_bound flag is set to 1 with no column-set dependency.
  • If indexing is not strictly required, consider dropping the indexing attempt altogether and instead optimize read performance with a standard non-clustered index on the base table’s non-sparse columns, or use a filtered index to achieve similar performance gains without violating the sparse column set restriction.

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

Troubleshooting Guide: SQL Server Error 10143

Why This Error Happens

Error 10143 occurs because SQL Server does not allow an indexed view (or, in some cases, certain system-generated structures like statistics or replication filtered objects) to be created on a view whose definition includes a ranking function (ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE()) or an aggregate window function (SUM() OVER(), AVG() OVER(), etc.). This is a fundamental engine restriction because window functions produce a row-dependent, non-deterministic result set at the time of index materialization, which conflicts with the way SQL Server persists and incrementally maintains indexed view data. The error is not caused by permissions or corruption — it is a T-SQL design limitation enforced by the Query Optimizer during CREATE INDEX or CREATE STATISTICS operations on the view.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance to review the full view definition.
  • Look specifically for OVER (PARTITION BY ... ORDER BY ...) clauses combined with ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), or aggregate functions like SUM(), COUNT(), AVG(), MIN(), MAX() used as window functions.
  • Confirm this is the view referenced in the error message text ("%.*ls").

Step 2: Remove or Refactor the Window Function from the View

  • Edit the view using ALTER VIEW YourViewName AS ... in SSMS or Azure Data Studio.
  • Move the ranking/aggregate window logic out of the view and into the outer SELECT statement that queries the view instead.
  • Alternatively, replace the window function logic with a standard GROUP BY aggregate if the business logic allows it (note: GROUP BY aggregates are permitted in indexed views under strict conditions, unlike window functions).
  • Save and execute the ALTER VIEW script.

Step 3: Recreate the Index or Statistics Object

  • Once the view no longer contains the window function, retry the original command that failed, for example:
  • CREATE UNIQUE CLUSTERED INDEX IX_YourView ON dbo.YourView (Column1);
  • If you were attempting to create statistics manually, retry:
  • CREATE STATISTICS stat_name ON dbo.YourView (Column1);
  • Verify the command completes without raising Error 10143 again.

Step 4: Use a Table or CTE as a Workaround (If Window Function Logic is Required)

  • If the ranking/window logic is essential, materialize the result into a physical staging table using a scheduled job or stored procedure instead of an indexed view.
  • Alternatively, wrap the window function logic in a standard view (without indexing) and build the index on an underlying base table instead.
  • Use OPTION (RECOMPILE) or query hints on the consuming query to maintain performance without relying on an indexed view.

Alternative or Verification Steps

  • Run SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.YourView') to confirm the index was successfully created on the view after refactoring.
  • If refactoring the view is not feasible, consider using a Temporary Table or an Indexed Table-Valued Function as an alternative, since neither is subject to the same indexed view restrictions on window functions.

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

Troubleshooting Guide: SQL Server Error 10141

Why This Error Happens

This error occurs when you attempt to create an indexed view (a view with a unique clustered index) that references a CLR (Common Language Runtime) function or method anywhere other than a non-key column of the SELECT list. SQL Server’s indexed view engine requires deterministic, schema-bound data for the key columns used in the index, and CLR routines—even those marked deterministic—cannot be guaranteed to be safely indexable in that position. This restriction exists to prevent index corruption or incorrect query results caused by CLR functions that may behave non-deterministically or rely on external state.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Reference

  • Open the view definition using sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS).
  • Locate the CLR function or method named in the error message (replaces %.*ls in the actual error text).
  • Confirm whether this CLR routine is used in the SELECT list, WHERE clause, JOIN condition, or GROUP BY clause.

Step 2: Restructure the View Definition

  • Move the CLR function call so it only appears as a non-key column in the SELECT list (i.e., not part of the columns used to build the unique clustered index).
  • If the CLR function is used in a WHERE clause or JOIN, refactor the logic to pre-filter or pre-join using standard T-SQL expressions instead.
  • Example fix:
  -- Problematic: CLR function in WHERE clause
  CREATE VIEW dbo.MyView WITH SCHEMABINDING AS
  SELECT ID, Amount
  FROM dbo.Orders
  WHERE dbo.MyCLRFunction(Amount) = 1;

  -- Fixed: Move CLR logic out of filtering, use only in SELECT
  CREATE VIEW dbo.MyView WITH SCHEMABINDING AS
  SELECT ID, Amount, dbo.MyCLRFunction(Amount) AS CLRResult
  FROM dbo.Orders;

Step 3: Drop and Recreate the Index

  • Run DROP INDEX on the existing unique clustered index if a prior version was partially created.
  • Recreate the view using CREATE VIEW ... WITH SCHEMABINDING with the corrected definition from Step 2.
  • Re-issue the CREATE UNIQUE CLUSTERED INDEX statement on the non-CLR key columns only.

Step 4: Validate CLR Assembly Permissions (Windows Server 2025 / Windows 11)

  • Ensure the CLR assembly is registered with PERMISSION_SET = SAFE using sp_configure 'clr strict security', 0; if using legacy trust models, or sign the assembly properly for SQL Server 2025’s enhanced CLR security.
  • Check assembly status via:
  SELECT name, permission_set_desc, is_user_defined
  FROM sys.assemblies;

Alternative or Verification Steps

  • Verify the fix: Run CREATE UNIQUE CLUSTERED INDEX again on the modified view — it should complete without Error 10141. Query the view with SELECT * FROM YourView to confirm data returns correctly.
  • Alternative approach: If the CLR logic is essential to filtering/joining, consider computing the CLR result in a persisted computed column on the base table first, then reference that computed column (not the CLR function directly) in the indexed view.

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

Troubleshooting Guide: Error 10142 – Cannot Create Index on View Containing APPLY

Why This Error Happens

This error occurs because SQL Server’s indexed view engine does not support the APPLY operator (CROSS APPLY or OUTER APPLY) within the view definition. Indexed views require deterministic, schema-bound logic that produces a result set without row-by-row correlated execution, and APPLY inherently relies on evaluating a table-valued expression for each row of the outer table, which violates this requirement. As a result, the SQL Server engine blocks the creation of a unique clustered index on any view that references this construct.

Step-by-Step Resolution Guide

Step 1: Identify the Offending APPLY Clause

  • Open the view definition using sp_helptext 'YourViewName'; in SQL Server Management Studio (SSMS).
  • Scan the FROM clause for CROSS APPLY or OUTER APPLY keywords.
  • Note the specific table-valued function (TVF) or subquery being invoked by the APPLY.

Step 2: Rewrite the View Logic Without APPLY

  • Replace CROSS APPLY with a standard INNER JOIN if the logic allows for a simple set-based join instead of row-by-row correlation.
  • If a Table-Valued Function (TVF) is being called via APPLY, try inlining the TVF’s logic directly into the view as a subquery or joined derived table.
  • Example fix: Convert SELECT a.*, b.val FROM TableA a CROSS APPLY dbo.GetVal(a.ID) b into SELECT a.*, b.val FROM TableA a JOIN dbo.ValuesTable b ON a.ID = b.ID.

Step 3: Alter the View with Schema Binding

  • Once the APPLY is removed, ensure the view is created WITH SCHEMABINDING to meet indexing prerequisites.
  • Run the following command to update the object: ALTER VIEW YourViewName WITH SCHEMABINDING AS SELECT...
  • Verify that two-part naming (e.g., dbo.TableName) is used for all referenced tables within the view definition.

Step 4: Re-create the Unique Clustered Index

  • Attempt to create the index again using: CREATE UNIQUE CLUSTERED INDEX IX_View_Name ON YourViewName (Column1);
  • Confirm the command executes without triggering Error 10142.

Alternative or Verification Steps

  • Verification: Query sys.indexes joined with sys.objects to confirm the clustered index now exists on the view (is_unique = 1).
  • Alternative: If the APPLY logic is too complex to refactor (e.g., requires row-by-row recursive logic), abandon the indexed view approach and instead materialize the data into a physical “summary” table using a scheduled SQL Agent Job or a trigger-based update strategy.

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

Troubleshooting Guide: SQL Server Error 10139

Why This Error Happens

This error occurs when SQL Server attempts to create an index, statistics, or schema-bound object on a view that contains an implicit conversion from a string (char/varchar/nchar/nvarchar) data type to datetime or smalldatetime. Indexed views and schema-bound views require deterministic expressions, and implicit string-to-date conversions are considered non-deterministic because their result can vary based on session settings like DATEFORMAT, LANGUAGE, or regional configuration. SQL Server 2025 enforces this strictly to guarantee that indexed view results remain consistent regardless of the client session context.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column or Expression

  • Open the view definition using SSMS: right-click the view → Script View as → CREATE To → New Query Editor Window.
  • Look for any WHERE, JOIN, or SELECT clause comparing a VARCHAR/NVARCHAR/CHAR column directly against a DATETIME or SMALLDATETIME column or literal.
  • Run the following diagnostic query to confirm the view’s dependency chain and column types:
  SELECT c.name, t.name AS data_type
  FROM sys.columns c
  JOIN sys.types t ON c.user_type_id = t.user_type_id
  WHERE c.object_id = OBJECT_ID('YourSchema.YourView');

Step 2: Rewrite the Query with an Explicit Deterministic CONVERT

  • Replace any implicit comparisons like WHERE SomeStringCol = SomeDateCol with an explicit, deterministic CONVERT statement.
  • Use a fixed style code (e.g., 120 for ODBC canonical format, 112 for ISO YYYYMMDD) since these are guaranteed deterministic:
  WHERE CONVERT(datetime, SomeStringCol, 112) = SomeDateCol
  • Avoid style codes that depend on language or regional settings (e.g., avoid style 100 or 107), as these remain non-deterministic even when explicitly converted.

Step 3: Drop and Recreate the View with WITH SCHEMABINDING

  • Alter the view definition to include WITH SCHEMABINDING if you intend to index it, ensuring all base tables are referenced using two-part names (dbo.TableName):
  ALTER VIEW dbo.YourView
  WITH SCHEMABINDING
  AS
  SELECT ... 
  WHERE CONVERT(datetime, OrderDateString, 112) = ShipDate;
  • Save and execute the script in SSMS or via sqlcmd to apply the corrected definition.

Step 4: Recreate the Index or Statistics Object

  • Re-run the original CREATE UNIQUE CLUSTERED INDEX or CREATE STATISTICS statement that originally triggered Error 10139.
  • Confirm the operation completes without warnings:
  CREATE UNIQUE CLUSTERED INDEX IX_YourView_Key
  ON dbo.YourView (KeyColumn);

Alternative or Verification Steps

  • Verify the fix by querying sys.indexes and sys.views to confirm the index was created successfully and the view shows is_date_correlation_view = 0 or expected schema-bound status.
  • If rewriting the CONVERT logic is not feasible, consider removing the schema-binding/indexing requirement and instead create a standard non-indexed view, or pre-stage the string-to-date conversion in an underlying table/computed column with a persisted deterministic value.

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

Troubleshooting Guide: Error 10140 – View Contains a Table Hint

Why This Error Happens

This error occurs because SQL Server does not allow indexed views, schema-bound views, or certain view-based constructs (such as creating an index or materializing a view) to be built on top of a SELECT statement that includes a table hint (e.g., NOLOCK, FORCESEEK, INDEX, READPAST). Table hints force a specific locking or access path behavior, which conflicts with the deterministic, hint-free execution plan required for indexed/schema-bound views. SQL Server 2025 enforces this restriction strictly during CREATE VIEW or CREATE INDEX operations to guarantee consistent query optimization behavior.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Review the output and locate any table hints such as WITH (NOLOCK), WITH (INDEX(...)), or WITH (FORCESEEK) inside the FROM clause.
  • Note the exact line number and table alias where the hint appears.

Step 2: Remove or Replace the Table Hint

  • Edit the view script and delete the hint clause entirely, e.g., change FROM dbo.Orders WITH (NOLOCK) to FROM dbo.Orders.
  • If isolation-level behavior is still required, set it at the session or query level using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; outside the view definition instead.
  • Save the corrected script to a .sql file for version control before redeploying.

Step 3: Recreate the View and Index

  • Drop the existing view using DROP VIEW dbo.YourViewName; in SSMS or via a T-SQL script.
  • Re-run the corrected CREATE VIEW statement without the hint, ensuring WITH SCHEMABINDING is included if you plan to index it.
  • Re-issue the CREATE UNIQUE CLUSTERED INDEX statement on the view to confirm it now succeeds.

Step 4: Check Dependent Objects

  • Use sp_depends 'YourViewName' or query sys.sql_expression_dependencies to find stored procedures or other views referencing the original hinted view.
  • Update any dependent code that relied on the old hint-based behavior to avoid downstream performance regressions.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE INDEX or CREATE VIEW statement in SSMS; it should complete without Error 10140.
  • As an alternative, if locking behavior is essential, move the hint to the calling query (SELECT * FROM dbo.YourView WITH (NOLOCK)) rather than embedding it inside the view definition itself.

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

Troubleshooting Guide: SQL Server Error 10138 – Indexed View Creation Failure

Why This Error Happens

This error occurs because SQL Server requires any indexed view containing aggregate functions, GROUP BY clauses, or certain joins to include a COUNT_BIG(*) expression in its SELECT list. This requirement exists so the query optimizer can correctly maintain and validate row counts within the unique clustered index on the view. Without this element, SQL Server 2025 cannot guarantee deterministic row tracking, so it blocks the index creation to prevent data integrity issues.

Step-by-Step Resolution Guide

Step 1: Identify the Problematic View Definition

  • Open SQL Server Management Studio (SSMS) and locate the view referenced in the error message ('%.*ls').
  • Run sp_helptext 'YourViewName' to review the current SELECT statement.
  • Check whether the view uses GROUP BY, COUNT(*), SUM, AVG, or other aggregates without COUNT_BIG(*).

Step 2: Modify the View to Include COUNT_BIG(*)

  • Alter the view definition to explicitly add COUNT_BIG(*) AS RowCount in the SELECT list.
  • Example syntax:
  ALTER VIEW dbo.YourViewName
  WITH SCHEMABINDING
  AS
  SELECT ColumnA, ColumnB, COUNT_BIG(*) AS RowCount
  FROM dbo.YourTable
  GROUP BY ColumnA, ColumnB;
  • Ensure WITH SCHEMABINDING is present, as indexed views in SQL Server 2025 strictly require this option.

Step 3: Recreate the Unique Clustered Index

  • Drop any failed index attempts using DROP INDEX IF EXISTS IX_YourIndexName ON dbo.YourViewName.
  • Create the unique clustered index again:
  CREATE UNIQUE CLUSTERED INDEX IX_YourIndexName
  ON dbo.YourViewName (ColumnA, ColumnB);
  • Confirm the index creation completes without triggering Error 10138.

Step 4: Validate Schema Binding Dependencies

  • Check if underlying base tables were altered after the view was schema-bound, using sys.sql_expression_dependencies.
  • Re-bind the view if dependent objects were modified, since Windows Server 2025 environments with frequent automated deployments can desync schema bindings.

Alternative or Verification Steps

  • Run SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.YourViewName') to confirm the unique clustered index now exists and is healthy.
  • If the error persists, drop the view entirely and recreate it from scratch with COUNT_BIG(*) included from the start, rather than altering an existing schema-bound definition.

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

Troubleshooting Guide: Error 10136 – Cannot Create Indexed View Using COUNT Aggregate

Why This Error Happens

This error occurs because SQL Server does not permit the standard COUNT(*) or COUNT(column) aggregate function when creating an indexed view (a view with a unique clustered index). SQL Server requires COUNT_BIG instead because the indexed view mechanism needs a bigint return type to accurately track row counts for large result sets during index maintenance. This is a design restriction in the Database Engine, not a permissions or configuration issue, meaning the T-SQL syntax itself must be rewritten to comply with indexed view requirements.

Step-by-Step Resolution Guide

Step 1: Locate the Offending View Definition

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to retrieve the view’s current definition:
  • SELECT OBJECT_DEFINITION(OBJECT_ID('YourSchema.YourViewName'));
  • Identify every instance of COUNT(*) or COUNT(expression) within the SELECT clause.

Step 2: Modify the Aggregate Function to COUNT_BIG

  • Replace every occurrence of COUNT(*) with COUNT_BIG(*).
  • If using COUNT(column_name), change it to COUNT_BIG(column_name).
  • Ensure the alias for the column remains consistent so downstream queries referencing the view do not break (e.g., COUNT_BIG(*) AS TotalRows).

Step 3: Drop and Recreate the View

  • Since ALTER VIEW can sometimes conflict with existing indexes, it is safer to drop the view and existing indexes first if they exist.
  • Execute: DROP VIEW YourSchema.YourViewName;
  • Recreate the view using the CREATE VIEW statement with SCHEMABINDING enabled (required for indexed views) and the updated COUNT_BIG syntax.
  • Example path for verification: Open the query in C:\Scripts\SQL\ViewDefinitions.sql if you are maintaining version-controlled schema files.

Step 4: Rebuild the Unique Clustered Index

  • Once the view compiles successfully, recreate the unique clustered index that failed previously.
  • Execute: CREATE UNIQUE CLUSTERED INDEX IX_YourIndexName ON YourSchema.YourViewName (YourColumn);
  • Monitor the Messages tab in SSMS to confirm the index builds without further aggregate-related errors.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('YourSchema.YourViewName'); to confirm the index now exists and is listed as unique and clustered.
  • Alternative: If application code relies heavily on the exact output of COUNT, wrap the view in a secondary standard (non-indexed) view that casts COUNT_BIG back to INT using CAST(COUNT_BIG(*) AS INT) AS RowCount to maintain backward compatibility with legacy queries.

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

Troubleshooting Guide: SQL Server Error 10137

Why This Error Happens

This error occurs because SQL Server’s indexed view engine does not support Common Table Expressions (CTEs) within the view definition. When you attempt to create a unique clustered index on a view that references a WITH clause (CTE), the query optimizer cannot deterministically bind and materialize the result set, as the CTE is treated as a temporary, non-persistent logical construct rather than a physical object. Consequently, the schema binding validation fails because the underlying logic required for incremental view maintenance cannot resolve the CTE’s dependency tree.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Open SQL Server Management Studio (SSMS) and navigate to the specific view mentioned in the error message (the “%.*ls” placeholder).
  • Run sp_helptext 'YourViewName'; to export the full T-SQL definition of the view to a query window for editing.
  • Look specifically for the WITH CTE_Name AS (...) syntax located immediately before the main SELECT statement.

Step 2: Refactor the CTE into a Derived Table or Subquery

  • Since CTEs are not supported, you must rewrite the logic using a standard subquery (derived table) instead. This performs the same logical function but is compatible with the SCHEMABINDING requirement.
  • Convert the syntax from WITH CTE AS (SELECT...) SELECT * FROM CTE to SELECT * FROM (SELECT...) AS DerivedTableAlias.
  • Ensure the SCHEMABINDING option is included in the ALTER VIEW or CREATE VIEW statement, as this is mandatory for indexing regardless of the CTE issue.

Step 3: Alter the View with Full Qualification

  • Execute the modified script using ALTER VIEW dbo.YourViewName WITH SCHEMABINDING AS... to update the object in the database engine.
  • Verify that all table names within the derived table logic are two-part qualified (e.g., dbo.TableName rather than just TableName), as SCHEMABINDING rejects unqualified object names.
  • Re-attempt the original CREATE UNIQUE CLUSTERED INDEX command on the newly altered view.

Step 4: Check for Nested CTE Dependencies

  • If the view calls other views or functions, open those dependent objects using sp_depends 'YourViewName'; to ensure a nested object isn’t secretly injecting a CTE into the execution plan.
  • Repeat the derived table conversion process (Step 2) for any nested objects found to be using the WITH clause syntax.

Alternative or Verification Steps

  • Verification: After altering the view, run SELECT OBJECTPROPERTY(OBJECT_ID('dbo.YourViewName'), 'IsIndexable'); in a query window; a return value of 1 confirms the schema is now valid for indexing.
  • Alternative: If refactoring the CTE is too complex for the business logic required, consider dropping the indexing requirement altogether and instead create a standard non-clustered index on the underlying base tables to improve the query performance of the view indirectly.

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

Troubleshooting Guide: Error 10134 – Cannot Create Index on View with Multiple APPLY Operators

Why This Error Happens

This error occurs because SQL Server’s indexed view engine enforces a strict limitation: a view can be indexed only if it contains, at most, one APPLY operator (CROSS APPLY or OUTER APPLY) in its definition. When a view’s SELECT statement joins multiple derived tables or table-valued functions using more than one APPLY clause, the query optimizer cannot deterministically materialize the result set into a unique clustered index. This is not a bug but a design constraint in SQL Server 2025, as multiple APPLY operations introduce row-by-row correlation logic that conflicts with the deterministic, set-based requirements of indexed views.

Step-by-Step Resolution Guide

Step 1: Identify the Offending View Definition

  • Open SQL Server Management Studio (SSMS) and run sp_helptext 'YourViewName' to inspect the full view definition.
  • Look specifically for multiple instances of CROSS APPLY or OUTER APPLY within the same SELECT statement.
  • Note the %.*ls placeholder in the error message — replace this with your actual view name to confirm which object is triggering the failure.

Step 2: Refactor the View to Use a Single APPLY

  • Rewrite the view logic to consolidate multiple APPLY operations into one, using a single Common Table Expression (CTE) or a nested subquery to pre-aggregate data before the APPLY.
  • Example restructure:
  WITH CombinedData AS (
      SELECT a.ID, a.Value1, b.Value2
      FROM TableA a
      CROSS APPLY dbo.fn_GetValue1(a.ID) AS v1
  )
  SELECT cd.ID, cd.Value1, cd.Value2
  FROM CombinedData cd
  CROSS APPLY dbo.fn_GetValue2(cd.ID) AS v2
  • If a true second APPLY is unavoidable, move the second one into a separate non-indexed view and JOIN against it instead.

Step 3: Remove Indexing Requirement or Split the View

  • If refactoring isn’t feasible, abandon the CREATE UNIQUE CLUSTERED INDEX attempt on this specific view and instead create standard non-clustered indexes on the underlying base tables to improve query performance.
  • Alternatively, split the single complex view into two simpler views — each containing only one APPLY — and index each one separately, then JOIN them in your queries or a third non-indexed view.

Step 4: Validate Schema Binding and Dependencies

  • Ensure the view is created WITH SCHEMABINDING before attempting the CREATE INDEX command again, as this is a prerequisite separate from the APPLY restriction.
  • Run sys.sql_expression_dependencies to check that no downstream objects break when you alter the view structure.

Alternative or Verification Steps

  • Verify the fix: After refactoring, re-run CREATE UNIQUE CLUSTERED INDEX IX_ViewName ON dbo.YourViewName (Column1) in SSMS; if it completes without Error 10134, the structural issue is resolved.
  • Alternative workaround: If indexing is not strictly required for performance, consider using a Memory-Optimized Table or a Materialized Table via Scheduled Job (using SELECT INTO) to pre-compute the APPLY results instead of relying on an indexed view.

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

Troubleshooting Guide: SQL Server Error 10132 – Indexed View Referencing CLR Table-Valued Function

Why This Error Happens

SQL Server Error 10132 occurs because indexed views (views with a unique clustered index) require strict determinism guarantees for every object they reference, and table-valued CLR functions are treated as non-deterministic or “black box” operations by the query optimizer. Since SQL Server cannot guarantee that the CLR function will return consistent, repeatable results on every execution, it cannot safely materialize and maintain the indexed view’s data. This is a hard architectural limitation in SQL Server 2025, not a bug or configuration error, meaning the engine will reject the CREATE INDEX statement outright rather than risk index corruption or stale data.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Function Reference

  • Run sp_helptext 'YourViewName' in SQL Server Management Studio (SSMS) to view the full view definition.
  • Locate the specific table-valued CLR function call (often listed in the error message itself between the quotes).
  • Confirm the function’s type using SELECT * FROM sys.objects WHERE type = 'FT' to verify it is indeed a CLR table-valued function.

Step 2: Remove the Direct Function Reference from the View

  • Edit the view definition using ALTER VIEW and remove the direct call to the CLR table-valued function.
  • If the data from the CLR function is required, pre-compute the results into a persisted physical table using a scheduled SQL Agent Job or ETL process instead of calling it live inside the view.
  • Join the indexed view against this new persisted staging table rather than the live function.

Step 3: Rebuild the View Without the Unique Clustered Index Requirement

  • If the CLR logic is essential and cannot be removed, convert the object from an “indexed view” to a standard (non-indexed) view.
  • Drop the existing unique clustered index attempt using DROP INDEX IX_Name ON ViewName if a partial index was created.
  • Re-create the view using CREATE VIEW without the WITH SCHEMABINDING and indexing requirement, accepting that this view will not benefit from materialized storage.

Step 4: Validate CLR Function Determinism Settings (If Applicable)

  • Check if the CLR function was registered with IsDeterministic = true in its SqlFunction attribute in Visual Studio.
  • Even if marked deterministic, SQL Server 2025 often does not trust TVF (Table-Valued Function) determinism for indexing purposes; verify this limitation persists by checking sys.objects.is_deterministic for the specific OBJECT_ID.
  • If the function is genuinely deterministic and simple, consider rewriting it as a native T-SQL inline table-valued function (iTVF) instead of a CLR assembly, as T-SQL functions are more likely to be indexable.

Alternative or Verification Steps

  • Verify the Fix: Attempt to re-run the CREATE UNIQUE CLUSTERED INDEX statement on the view after removing the CLR reference; a successful execution with “Command(s) completed successfully” confirms the fix.
  • Alternative Workaround: If performance is the primary concern (rather than strict indexing), consider using an Indexed Materialized Table maintained by a Trigger or Scheduled Task to mimic the performance benefits of an indexed view without triggering the schema-binding restrictions on CLR objects.

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

Troubleshooting Guide: SQL Server Error 10133

Why This Error Happens

This error occurs because SQL Server does not allow the creation of indexed (schema-bound) views when the view references a function that performs data access, either to user tables or system catalogs. Indexed views require strict determinism and schema-binding guarantees, and any function marked with READS SQL DATA or EXTERNAL ACCESS violates this requirement because its output cannot be guaranteed to be deterministic across executions. This is commonly seen when a user-defined function (UDF) queries another table internally rather than relying solely on its input parameters.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function

  • Locate the specific function named in the error message (the %.*ls placeholder in the actual error text).
  • Run the following query to inspect the function’s definition and data access property:
  SELECT OBJECT_DEFINITION(OBJECT_ID('YourFunctionName'));
  SELECT is_schema_bound, data_access FROM sys.sql_modules WHERE object_id = OBJECT_ID('YourFunctionName');
  • Confirm if data_access is set to 1 (indicating data access), which is incompatible with indexed views.

Step 2: Refactor the Function to Remove Data Access

  • Modify the function to eliminate internal SELECT statements against user tables or system views.
  • If the function requires external data, pass the required values as input parameters instead of querying them internally.
  • Alternatively, convert the logic into a computed column on the base table (using a deterministic expression) rather than wrapping it in a view-dependent function.

Step 3: Remove Schema Binding Requirement (If Refactoring Isn’t Feasible)

  • If you only need a standard view (not an indexed/materialized view), remove the WITH SCHEMABINDING clause from the CREATE VIEW statement.
  • Navigate to SQL Server Management Studio (SSMS) 21, right-click the view under Databases > [YourDB] > Views, select Modify, and delete the SCHEMABINDING keyword from the script.
  • Execute the ALTER VIEW script to apply the change via SSMS or sqlcmd.

Step 4: Rebuild the Index (If Required)

  • If the view absolutely requires an index for performance reasons, ensure the function is replaced with inline logic directly within the view definition rather than a separate UDF call.
  • Re-run the CREATE UNIQUE CLUSTERED INDEX command on the view once the function dependency is removed.

Alternative or Verification Steps

  • Verify the fix by attempting to re-run the CREATE INDEX statement on the view; if it completes without Error 10133, the schema-binding conflict is resolved.
  • If modifying the function is not possible due to business logic constraints, consider using an Indexed View alternative such as a standard view combined with a scheduled job that populates a physical summary table (manual materialization) instead.

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

Troubleshooting Guide: SQL Server Error 10131 — Indexed View on Imprecise CLR Table-Valued Function

Why This Error Happens

This error occurs because SQL Server requires all functions and columns referenced in an indexed (materialized) view to be deterministic and precise, but CLR table-valued functions (TVFs) marked as “imprecise” do not guarantee consistent output for identical inputs. Since the SQL Server query optimizer cannot verify that the CLR TVF will return the same result set on every invocation, it cannot safely maintain a unique clustered index on the view. This typically happens when a developer creates a CLR TVF without explicitly setting the IsPrecise property to true in the SqlFunctionAttribute, or when the function inherently relies on floating-point operations or external state.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR Function

  • Run the following query to locate the view and its dependent CLR function:
  SELECT referenced_entity_name 
  FROM sys.dm_sql_referenced_entities('dbo.YourViewName', 'OBJECT');
  • Confirm the function type is a CLR TVF by checking sys.objects where type = 'FT'.
  • Note the assembly name associated with this function via sys.assembly_modules.

Step 2: Modify the CLR Assembly Source Code

  • Open the original Visual Studio/.NET project source for the CLR assembly (commonly found in a .sln or .csproj file on the development machine, not the server).
  • Locate the SqlFunction attribute decorating the table-valued function method.
  • Explicitly set the IsPrecise property to true:
  [SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "...", IsPrecise = true)]
  • Important: Only set this flag if the function logic is truly deterministic (e.g., it does not use float, double, random number generators, or system time). Marking a non-deterministic function as precise will cause data corruption in the index.

Step 3: Recompile and Redeploy the Assembly

  • Rebuild the .dll in Visual Studio.
  • On the SQL Server instance, drop the existing assembly and function references:
  DROP VIEW dbo.YourViewName;
  DROP FUNCTION dbo.YourCLRFunction;
  DROP ASSEMBLY YourAssemblyName;
  • Re-register the updated assembly using CREATE ASSEMBLY ... FROM 'C:\Path\To\Updated.dll' and recreate the function definition.

Step 4: Recreate the View and Index

  • Recreate the view using CREATE VIEW ... WITH SCHEMABINDING.
  • Attempt to create the unique clustered index again:
  CREATE UNIQUE CLUSTERED INDEX IX_YourView ON dbo.YourViewName (YourKeyColumn);
  • Verify no errors (specifically 10131) are returned during execution.

Alternative or Verification Steps

  • Verification: Query sys.indexes and join with sys.objects to confirm the clustered index on the view now shows a status of is_disabled = 0 and is utilized correctly in execution plans.
  • Alternative: If the function cannot be made precise due to its logic (e.g., it relies on DateTime.Now or floating-point math), do not index the view. Instead, use a standard (non-indexed) view or materialize the data manually into a physical staging table using a scheduled SQL Agent job.