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

Troubleshooting Guide: Error 5515 – Cannot Open FILESTREAM Container Directory

Why This Error Happens

Error 5515 occurs when the SQL Server service account lacks the necessary NTFS permissions to access the FILESTREAM container directory, or when the directory itself has been moved, deleted, or corrupted outside of SQL Server’s control. This can also happen if the FILESTREAM feature was disabled at the instance level after the database was created, or if the underlying volume has disk-level errors preventing the operating system from returning a valid handle to the folder. Additionally, antivirus software or Windows Server 2025’s enhanced file-locking policies may intermittently block access to the container.

Step-by-Step Resolution Guide

Step 1: Verify FILESTREAM is Enabled at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025/Windows 11.
  • Navigate to SQL Server Services > right-click your instance > Properties > FILESTREAM tab.
  • Ensure “Enable FILESTREAM for Transact-SQL access” is checked.
  • Run the following query to confirm at the engine level:
EXEC sp_configure filestream_access_level, 2;
RECONFIGURE;

Step 2: Check and Repair NTFS Permissions on the Container Directory

  • Locate the physical path of the FILESTREAM container (e.g., D:\SQLData\FileStreamContainer).
  • Right-click the folder > Properties > Security tab.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • Apply permissions via command line if GUI access is restricted:
icacls "D:\SQLData\FileStreamContainer" /grant "NT SERVICE\MSSQLSERVER":(OI)(CI)F /T

Step 3: Validate the Directory Path and Volume Integrity

  • Confirm the directory has not been manually renamed, deleted, or relocated.
  • Run chkdsk D: /f to scan for and repair file system errors on the hosting volume.
  • If the directory is missing entirely, restore it from a recent backup rather than recreating an empty folder, as SQL Server requires specific internal GUID-based subfolder structures.

Step 4: Exclude the Directory from Antivirus/Windows Defender Scanning

  • Open Windows Security > Virus & threat protection > Manage settings > Exclusions.
  • Add the FILESTREAM container’s root path and the MSSQL data directory as exclusions.
  • Restart the SQL Server service to clear any residual file locks:
Restart-Service -Name "MSSQLSERVER" -Force

Step 5: Review SQL Server Error Log for OS Status Code Details

  • Open the SQL Server error log via SSMS or Notepad (path typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log).
  • Cross-reference the specific 0x%x status code returned with Windows system error codes (e.g., 0x5 = Access Denied, 0x3 = Path Not Found) using net helpmsg <code> in Command Prompt.
  • Use this code to pinpoint whether the issue is permissions-based or path-based before proceeding further.

Alternative or Verification Steps

  • To verify the fix, run a test query against a table containing a FILESTREAM column (e.g., SELECT * FROM dbo.YourTable WHERE FileStreamColumn IS NOT NULL;) and confirm no 5515 error is thrown.
  • If the error persists, use sp_helpfile to check the logical path registered in SQL Server against the physical path on disk; a mismatch here often requires detaching and reattaching the database with ALTER DATABASE... MODIFY FILE to correct the stored path.

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

Troubleshooting Guide: SQL Server Error 5511 – FILESTREAM File System Log Record Corrupted

Why This Error Happens

This error occurs when the FILESTREAM file system log record on disk has become corrupted, typically due to an unexpected shutdown, storage-level failure, or disk I/O error that interrupted a write operation to the log folder. It can also result from antivirus software or backup tools locking or modifying files within the FILESTREAM container while SQL Server was writing metadata. In some cases, this is triggered by underlying NTFS volume corruption or a mismatch between the FILESTREAM data container and its transaction log tracking records.

Step-by-Step Resolution Guide

Step 1: Verify the Scope of Corruption

  • Check SQL Server Error Log and Windows Event Viewer (Application log) for the exact FILESTREAM container path referenced alongside Error 5511.
  • Note the database name and the associated FILESTREAM filegroup logical path (query sys.database_files where type_desc = 'FILESTREAM').
  • Attempt to take the database offline cleanly: ALTER DATABASE [YourDB] SET OFFLINE WITH ROLLBACK IMMEDIATE;

Step 2: Run Disk and File System Diagnostics

  • Open an elevated PowerShell/Command Prompt and run chkdsk X: /f /r (replace X: with the volume hosting the FILESTREAM container) to repair NTFS-level corruption.
  • Confirm the disk subsystem health using Get-PhysicalDisk | Get-StorageReliabilityCounter to rule out hardware degradation.
  • If using a SAN or virtualized disk, verify no underlying storage replication or snapshot conflicts occurred recently.

Step 3: Exclude FILESTREAM Paths from Antivirus and Backup Agents

  • Navigate to your antivirus console and add an exclusion for the full FILESTREAM data container path (e.g., D:\SQLData\FileStreamContainer\).
  • Exclude the same path from third-party backup agents or file-indexing services (e.g., Windows Search Indexer).
  • Restart the SQL Server service (services.msc → SQL Server (MSSQLSERVER) → Restart) after applying exclusions.

Step 4: Restore from a Known-Good Backup

  • If corruption persists, perform a restore using the most recent full backup that includes the FILESTREAM filegroup: RESTORE DATABASE [YourDB] FROM DISK = 'E:\Backups\YourDB.bak' WITH REPLACE;
  • Apply any available transaction log backups to minimize data loss.
  • Validate the FILESTREAM container rebuilds correctly by checking the folder structure matches the $FSLOG and $FSDATA markers under the container root.

Step 5: Rebuild the FILESTREAM Filegroup (If Restore Is Not Viable)

  • Remove the corrupted FILESTREAM file reference: ALTER DATABASE [YourDB] REMOVE FILE [FileStreamLogicalName];
  • Re-add a new FILESTREAM container: ALTER DATABASE [YourDB] ADD FILE (NAME = 'NewFSContainer', FILENAME = 'D:\SQLData\NewFileStreamContainer') TO FILEGROUP [FileStreamGroup];
  • Migrate any recoverable BLOB data manually from the old container before deleting it.

Alternative or Verification Steps

  • Run DBCC CHECKDB('YourDB') WITH ALL_ERRORMSGS, NO_INFOMSGS; after remediation to confirm no further corruption is reported, and bring the database back ONLINE.
  • If Error 5511 recurs immediately after remediation, treat it as a hardware-level storage issue — run full chkdsk with bad sector scanning and consider relocating the FILESTREAM container to a different physical volume.

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

Troubleshooting Guide: SQL Server Error 5512 – Directory Truncation Failure

Why This Error Happens

Error 5512 occurs when SQL Server 2025 attempts to truncate a directory used by a Memory-Optimized Filegroup (used for In-Memory OLTP checkpoint files) but encounters an underlying file system restriction. This is typically caused by the SQL Server service account lacking sufficient NTFS permissions on the data folder, antivirus or backup software locking the checkpoint files during the operation, or file system corruption on the volume hosting the filegroup. In rarer cases, this happens because the directory contains residual files from an improperly shut down instance, preventing Windows from fully clearing the folder.

Step-by-Step Resolution Guide

Step 1: Verify NTFS Permissions on the Data Directory

  • Navigate to the Memory-Optimized Filegroup directory, typically located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\XTP\.
  • Right-click the folder, select Properties > Security, and confirm the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • If permissions are missing, click Edit, add the service account, and grant Full Control recursively to all subfolders.

Step 2: Check for File Locks from Antivirus or Backup Agents

  • Open Task Manager or Resource Monitor and search for processes holding handles on the XTP directory.
  • Temporarily disable real-time antivirus scanning on the SQL data directories, or add an exclusion rule:
  • Add-MpPreference -ExclusionPath "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\XTP\"
  • Restart the SQL Server service and retry the operation that triggered the truncation.

Step 3: Run a Consistency Check and Clear Orphaned Checkpoint Files

  • Execute DBCC CHECKDB on the affected database to rule out internal corruption:
  • DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;
  • If orphaned .bin/.chk files remain from a crashed session, stop the SQL Server service, manually archive the orphaned files to a backup location, and restart the service to let SQL Server rebuild the checkpoint structure.

Step 4: Validate the Underlying Disk/Volume Health

  • Run chkdsk C: /f /r (replace C: with the actual volume) during a maintenance window to repair file system-level errors.
  • Reboot Windows Server 2025 if prompted, and monitor the SQL Server error log for recurrence of Error 5512 after restart.

Alternative or Verification Steps

  • After applying fixes, run ALTER DATABASE YourDatabaseName SET FILESTREAM (DIRECTORY_NAME = '') or trigger a manual checkpoint via CHECKPOINT; to confirm the truncation completes without error.
  • If the issue persists, drop and recreate the Memory-Optimized Filegroup on a different volume with verified NTFS permissions, then restore data from the last known good backup.

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

Troubleshooting Guide: SQL Server Error 5513 – Invalid FILESTREAM Filegroup Name

Why This Error Happens

Error 5513 occurs when SQL Server cannot validate the name supplied for the log filegroup associated with a FILESTREAM filegroup, typically because the name contains invalid characters, exceeds identifier length limits, or conflicts with an existing filegroup/object name in the database. This can also happen if the CREATE DATABASE or ALTER DATABASE statement references a filegroup name that was never properly created due to a syntax error or a failed prior transaction. In some cases, corrupted system catalog metadata (sys.filegroups) from an interrupted database creation process can also trigger this validation failure.

Step-by-Step Resolution Guide

Step 1: Review and Correct the Filegroup Naming Syntax

  • Open the T-SQL script used to create or alter the FILESTREAM-enabled database.
  • Ensure the filegroup name follows SQL Server identifier rules (no special characters like \, /, :, *, ?, ", <, >, |).
  • Confirm the name does not exceed 128 characters and is not a reserved keyword.
  • Example of a valid statement:
ALTER DATABASE MyDB
ADD FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM;

Step 2: Check for Duplicate or Conflicting Filegroup Names

  • Run the following query to list existing filegroups and verify no naming collision exists:
SELECT name, type_desc FROM sys.filegroups;
  • If a filegroup with the same name already exists, rename your new filegroup reference in the script.
  • Drop any orphaned or incomplete filegroup entries using:
ALTER DATABASE MyDB REMOVE FILEGROUP FileStreamGroup1;

Step 3: Validate FILESTREAM Configuration at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services > right-click your instance > Properties > FILESTREAM tab.
  • Ensure “Enable FILESTREAM for Transact-SQL access” is checked.
  • Restart the SQL Server service (net stop MSSQLSERVER then net start MSSQLSERVER) to apply changes.

Step 4: Recreate the Database Structure Cleanly

  • If metadata corruption is suspected, script out the full database definition using SSMS (Right-click DB > Tasks > Generate Scripts).
  • Drop the problematic database and recreate it using the corrected script with a properly named FILESTREAM filegroup.
  • Re-attach or restore data files only after confirming the new filegroup structure compiles without errors.

Alternative or Verification Steps

  • Run DBCC CHECKDB('MyDB') WITH NO_INFOMSGS; to confirm no further corruption exists in the filegroup metadata after recreation.
  • If the issue persists, use sp_helpfilegroup to cross-reference filegroup IDs and names, ensuring the FILESTREAM filegroup is correctly linked to its associated log filegroup.

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

Troubleshooting Guide: SQL Server Error 5508 — FILESTREAM Column Type Mismatch

Why This Error Happens

This error occurs when a CREATE TABLE or ALTER TABLE statement attempts to apply the FILESTREAM attribute to a column whose data type is not VARBINARY(MAX). SQL Server 2025 enforces strict type validation for FILESTREAM-enabled columns because the underlying data must be stored as an unstructured binary large object (BLOB) on the NTFS filesystem rather than in-row. Common root causes include copy-pasted DDL scripts with incorrect column definitions, schema migration scripts generated for a different table structure, or developers mistakenly applying FILESTREAM to VARCHAR(MAX), IMAGE, or NVARCHAR(MAX) columns.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Definition

  • Open the DDL script or run sp_help 'YourTableName' in SQL Server Management Studio (SSMS) to inspect the column list.
  • Look specifically for any column with the FILESTREAM keyword that is not explicitly typed as VARBINARY(MAX).
  • Check system catalog views for confirmation:
SELECT name, system_type_id, is_filestream
FROM sys.columns
WHERE object_id = OBJECT_ID('YourTableName');

Step 2: Correct the Column Data Type

  • Modify the script so the target column uses the correct type syntax.
  • Example of the corrected definition:
CREATE TABLE dbo.Documents
(
    DocID INT PRIMARY KEY,
    DocGUID UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWID(),
    DocData VARBINARY(MAX) FILESTREAM NULL
);
  • Ensure the table also includes a UNIQUEIDENTIFIER column with ROWGUIDCOL set, as this is a mandatory requirement for FILESTREAM tables in SQL Server 2025.

Step 3: Verify FILESTREAM is Enabled at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Services > right-click your instance > Properties > FILESTREAM tab.
  • Confirm “Enable FILESTREAM for Transact-SQL access” is checked.
  • Run the following T-SQL to confirm instance-level configuration:
EXEC sp_configure 'filestream access level';
  • If the value returned is 0, set it to 2 (full access) using sp_configure 'filestream access level', 2; followed by RECONFIGURE;.

Step 4: Re-run the Corrected Script

  • Execute the updated CREATE TABLE or ALTER TABLE statement in SSMS.
  • Confirm no syntax errors are returned and the table/column is created successfully.
  • Check sys.tables and sys.columns to validate the is_filestream flag is now set to 1 on the correct column.

Alternative or Verification Steps

  • Run SELECT * FROM sys.filestream_tombstone_2005_view; or query sys.database_filestream_options to confirm the database is FILESTREAM-enabled and the column mapping is correct.
  • If the error persists despite correct typing, drop and recreate the table from scratch rather than altering it, since ALTER TABLE operations adding FILESTREAM to existing VARBINARY columns sometimes fail silently on metadata caching in SQL Server 2025 — a fresh CREATE TABLE avoids this edge case.

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

Why This Error Happens

Error 5509 occurs because SQL Server’s FILESTREAM filegroup treats its data file as a container directory rather than a traditional binary data file, meaning SIZE and FILEGROWTH properties are structurally incompatible with it. This typically happens when a DBA copies syntax from a standard ROWS filegroup ADD FILE statement and forgets to strip these properties out when defining the FILESTREAM container. Since FILESTREAM data is stored directly on the NTFS volume rather than inside the managed .mdf/.ndf file structure, SQL Server has no mechanism to pre-allocate size or manage growth increments for it.

Step-by-Step Resolution Guide

Step 1: Review the Current T-SQL Syntax

  • Open the script that triggered the error in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Locate the ADD FILE clause associated with the FILESTREAM_ON filegroup definition.
  • Identify instances of SIZE =, MAXSIZE =, or FILEGROWTH = within that specific file block.

Step 2: Strip Invalid Properties from the File Definition

  • Remove the SIZE, MAXSIZE, and FILEGROWTH arguments entirely from the FILESTREAM file entry.
  • Ensure the syntax only retains NAME and FILENAME (which should point to a folder path, not a file extension like .ndf).
  • Example of corrected syntax:
  ALTER DATABASE MyDB
  ADD FILE (NAME = FileStreamData, FILENAME = 'C:\SQLData\FileStreamContainer')
  TO FILEGROUP FileStreamGroup1;

Step 3: Verify the Target Directory Permissions

  • Confirm the path specified in FILENAME does not already exist as a folder prior to execution; SQL Server must create this directory itself.
  • Check that the SQL Server service account has “Full Control” NTFS permissions on the parent directory (e.g., C:\SQLData\) via Windows Security > Advanced Sharing Permissions.
  • Re-run the corrected ALTER DATABASE or CREATE DATABASE script.

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

  • If changes were made to the FILESTREAM configuration level (Instance level) rather than just the script, restart the SQL Server (MSSQLSERVER) service via services.msc.
  • Alternatively, run net stop MSSQLSERVER followed by net start MSSQLSERVER in an elevated Command Prompt.

Alternative or Verification Steps

  • Verify the fix by querying sys.database_files in SSMS; the size and growth columns for the FILESTREAM row should display as 0, confirming the properties were successfully omitted.
  • If the container folder was partially created during a failed attempt, manually delete the specific sub-folder (not the parent drive) via File Explorer before re-attempting the ALTER DATABASE command, as a pre-existing empty folder can sometimes cause secondary conflicts.

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

Troubleshooting Guide: Error 5510 – “LOG ON cannot be used for non-FILESTREAM file group”

Why This Error Happens

This error occurs when a CREATE DATABASE or ALTER DATABASE statement includes a LOG ON clause referencing a file group that was not explicitly declared as CONTAINS FILESTREAM. SQL Server 2025 strictly validates that the LOG ON syntax is only paired with FILESTREAM-enabled file groups, since standard transaction log files use a separate LOG ON definition outside of file group syntax. This typically results from a scripting error, a migrated T-SQL script from an older template, or confusion between regular row-data file groups and FILESTREAM file groups.

Step-by-Step Resolution Guide

Step 1: Review the Database Creation Script

  • Open the T-SQL script that generated the error and locate the CREATE DATABASE or ALTER DATABASE statement.
  • Identify which file group is being referenced in the LOG ON clause.
  • Check whether that file group was declared with CONTAINS FILESTREAM or as a standard PRIMARY/secondary file group.

Step 2: Correct the File Group Declaration

  • If the file group is intended to store FILESTREAM data, add the CONTAINS FILESTREAM keyword explicitly:
  FILEGROUP [FileStreamGroup1] CONTAINS FILESTREAM
  • If the file group is meant for regular transaction log storage, remove it entirely from the LOG ON clause and instead define it using the standard log file syntax:
  LOG ON
  ( NAME = N'MyDB_log', FILENAME = N'C:\SQLData\MyDB_log.ldf' )

Step 3: Separate FILESTREAM and Log Definitions

  • Ensure FILESTREAM groups are only referenced under FILEGROUP ... CONTAINS FILESTREAM, never inside LOG ON.
  • Ensure transaction log files are defined strictly under LOG ON, with no file group association.
  • Example corrected structure:
  CREATE DATABASE MyDB
  ON PRIMARY
  ( NAME = N'MyDB', FILENAME = N'C:\SQLData\MyDB.mdf' ),
  FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM
  ( NAME = N'FSGroup1', FILENAME = N'C:\SQLData\FSFolder' )
  LOG ON
  ( NAME = N'MyDB_log', FILENAME = N'C:\SQLData\MyDB_log.ldf' );

Step 4: Re-run and Validate the Script

  • Execute the corrected script in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Confirm the database is created without triggering Error 5510.
  • Check the SQL Server Error Log (Management > SQL Server Logs in SSMS) to confirm no related warnings appear.

Alternative or Verification Steps

  • Run sp_helpfilegroup or query sys.filegroups and sys.database_files to confirm the FILESTREAM file group is correctly flagged (type = 'FD') and that log files are associated with type = 'L'.
  • If the issue persists, drop and recreate the database using the Database Properties GUI in SSMS, manually assigning file groups and log files through the Files page to avoid scripting syntax errors.

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

Troubleshooting Guide: SQL Server Error 5505

Why This Error Happens

This error occurs when you attempt to create or alter a table containing FILESTREAM columns without defining a proper unique row identifier. SQL Server requires every FILESTREAM-enabled table to have a column with the ROWGUIDCOL property that is both UNIQUE and NOT NULL, because this GUID is used internally to map table rows to the corresponding files on the filesystem. Without this constraint, SQL Server has no reliable way to track which filesystem object belongs to which row, so the DDL operation is rejected.

Step-by-Step Resolution Guide

Step 1: Verify the Table Definition

  • Open SQL Server Management Studio (SSMS) and script out the existing CREATE TABLE statement.
  • Check whether a uniqueidentifier column exists in the table.
  • Confirm whether that column currently has the ROWGUIDCOL property and a UNIQUE constraint applied.

Step 2: Add the Required ROWGUIDCOL Column

  • If the column is missing, add it using the following syntax:
  • ALTER TABLE YourTable ADD RowGuidCol UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWID();
  • If the column already exists but lacks the property, drop and recreate the column, or create a new table with the corrected schema and migrate data using INSERT INTO ... SELECT.

Step 3: Apply the Correct Constraints

  • Ensure the column enforces uniqueness via a UNIQUE or PRIMARY KEY constraint:
  • ALTER TABLE YourTable ADD CONSTRAINT UQ_RowGuidCol UNIQUE (RowGuidCol);
  • Make sure the column is explicitly set to NOT NULL (FILESTREAM will reject nullable GUID columns).

Step 4: Re-run the FILESTREAM Table Creation

  • Re-execute your original CREATE TABLE or ALTER TABLE statement that adds the FILESTREAM column.
  • Confirm the FILESTREAM filegroup is correctly referenced in the TEXTIMAGE_ON clause.
  • Example: CREATE TABLE Docs (Id INT PRIMARY KEY, RowGuidCol UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWID(), FileData VARBINARY(MAX) FILESTREAM) FILESTREAM_ON FilestreamGroup1;

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

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Restart the service to ensure FILESTREAM filegroup settings are fully reloaded.

Alternative or Verification Steps

  • Run sp_help 'YourTable' in SSMS to confirm the ROWGUIDCOL property and constraints are correctly applied before retrying FILESTREAM operations.
  • If the error persists, verify FILESTREAM is enabled at the instance level via SQL Server Configuration Manager > SQL Server Services > Properties > FILESTREAM tab, and ensure the Windows service account has read/write access to the FILESTREAM data directory.

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

Troubleshooting Guide: SQL Server Error 5506 – FILESTREAM File Named ‘DEFAULT’

Why This Error Happens

This error occurs because DEFAULT is a reserved keyword used internally by SQL Server’s FILESTREAM filegroup logic to designate the active container for BLOB storage. When a script or GUI operation explicitly attempts to name a FILESTREAM data or log file “DEFAULT,” SQL Server 2025 rejects the DDL statement to avoid a naming collision with the engine’s internal pointer system. This typically happens during manual database creation scripts or when migrating legacy T-SQL code to a Windows Server 2025 environment without updating file naming conventions.

Step-by-Step Resolution Guide

Step 1: Review the T-SQL Creation Script

  • Open SQL Server Management Studio (SSMS) and locate the CREATE DATABASE or ALTER DATABASE script causing the failure.
  • Search specifically for the ADD FILE clause within the FILESTREAM filegroup definition.
  • Identify the exact line where NAME = 'DEFAULT' is being declared.

Step 2: Rename the Logical File Identifier

  • Change the logical name parameter from DEFAULT to a unique, descriptive identifier (e.g., FileStreamGroup1 or DB_FS_Data).
  • Ensure the physical path points to a valid, empty directory on the NTFS volume, such as C:\SQLData\FileStreamContainer.
  • Verify the syntax matches the following corrected format:
  ALTER DATABASE [YourDB] 
  ADD FILE (NAME = 'FileStreamGroup1', FILENAME = 'C:\SQLData\FileStreamContainer') 
  TO FILEGROUP [FileStreamGroup]

Step 3: Validate Windows Server 2025 Permissions

  • Confirm that the SQL Server service account has “Full Control” permissions on the parent folder via the Windows 11/Server 2025 Security tab.
  • Check that the FILESTREAM feature is enabled in SQL Server Configuration Manager under the service properties.
  • Restart the SQL Server (MSSQLSERVER) service to apply any configuration changes.

Step 4: Re-execute the Database Script

  • Run the corrected script in a new query window in SSMS.
  • Monitor the “Messages” tab for the “Command(s) completed successfully” confirmation, ensuring Error 5506 no longer triggers.

Alternative or Verification Steps

  • Verification: Query the sys.database_files catalog view (SELECT name, physical_name FROM sys.database_files;) to confirm the new file name appears correctly without the reserved “DEFAULT” keyword.
  • Alternative: If the error persists due to cached metadata, drop the specific filegroup (if empty) and recreate it entirely using the ALTER DATABASE... REMOVE FILEGROUP command before re-adding the file with the corrected name.

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

Troubleshooting Guide: Error 5507 – DEFAULT Cannot Be Specified for FILESTREAM Log Filegroup

Why This Error Happens

This error occurs because SQL Server 2025 does not allow a FILESTREAM filegroup to be marked as the DEFAULT filegroup when it is intended to store transaction log data or is incorrectly flagged during a CREATE DATABASE or ALTER DATABASE statement. FILESTREAM filegroups are designed exclusively to hold unstructured BLOB data on the file system, so SQL Server’s engine blocks the DEFAULT keyword to prevent regular table data from being accidentally routed into a FILESTREAM container. This is typically caused by a syntax error in the T-SQL script or a misunderstanding of filegroup types during database provisioning.

Step-by-Step Resolution Guide

Step 1: Review the T-SQL Script Syntax

  • Open the CREATE DATABASE or ALTER DATABASE script that triggered the error.
  • Locate the FILEGROUP clause associated with CONTAINS FILESTREAM.
  • Ensure the word DEFAULT is not appended immediately after the FILESTREAM filegroup name.
  • Example of incorrect syntax: FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM DEFAULT.

Step 2: Separate the Row Data Filegroup from the FILESTREAM Filegroup

  • Ensure you have two distinct filegroup declarations: one standard PRIMARY or ROWS filegroup (which can be DEFAULT) and one CONTAINS FILESTREAM filegroup (which cannot).
  • Modify the script so the DEFAULT keyword is applied only to the standard filegroup intended for relational row data.
  • Save the corrected script to C:\Scripts\DB_Create_Fixed.sql on your Windows Server 2025 instance.

Step 3: Re-execute the Database Creation Command

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your instance.
  • Run the corrected script using sqlcmd -S localhost -i "C:\Scripts\DB_Create_Fixed.sql".
  • Check the Messages tab in SSMS to confirm the command completed successfully without Error 5507.

Step 4: Verify Filegroup Properties via SSMS GUI

  • Navigate to Object Explorer > Databases > [Your Database] > Properties > Filegroups.
  • Confirm the FILESTREAM filegroup does not have the “Default” checkbox selected.
  • Apply changes and restart the SQL Server service via services.msc if the properties remain locked.

Alternative or Verification Steps

  • Run the query SELECT name, type_desc, is_default FROM sys.filegroups; against your database to confirm the FILESTREAM filegroup shows is_default = 0.
  • If the error persists after fixing the syntax, drop the problematic filegroup using ALTER DATABASE [YourDB] REMOVE FILEGROUP FileStreamGroup1; and recreate it from scratch using the corrected two-filegroup approach.

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

Troubleshooting Guide: Error 5502 – FILESTREAM Container Inaccessible

Why This Error Happens

Error 5502 typically occurs when SQL Server 2025 cannot access the underlying NTFS directory associated with a FILESTREAM filegroup. This is usually caused by the SQL Server service account lacking proper NTFS permissions on the container folder, the FILESTREAM feature being disabled at the instance level, or the physical files/folder structure being moved, renamed, or corrupted outside of SQL Server’s control. Additionally, Windows Server 2025 security policy changes or antivirus/EDR software may lock the directory, preventing the Database Engine from establishing a handle to the container.

Step-by-Step Resolution Guide

Step 1: Verify FILESTREAM is Enabled at the OS and Instance Level

  • Open SQL Server Configuration Manager → right-click your instance (e.g., MSSQLSERVER) → Properties → FILESTREAM tab.
  • Ensure “Enable FILESTREAM for Transact-SQL access” and “Enable FILESTREAM for file I/O streaming access” are both checked.
  • Run the following T-SQL to confirm instance-level configuration matches:
  EXEC sp_configure 'filestream access level', 2;
  RECONFIGURE;

Step 2: Check and Repair NTFS Permissions on the Container Path

  • Navigate to the container directory, typically located at a path like C:\SQLData\FileStreamContainer.
  • Right-click the folder → Properties → Security → ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Full Control.
  • Use PowerShell to reset permissions if inheritance was broken:
  icacls "C:\SQLData\FileStreamContainer" /grant "NT Service\MSSQLSERVER:(OI)(CI)F" /T
  • Confirm no Windows Server 2025 Controlled Folder Access (Windows Defender) policy is blocking the SQL service account.

Step 3: Validate the Filegroup and Container Path in SQL Server

  • Query the current filegroup mapping to ensure the path SQL Server expects matches the actual directory on disk:
  SELECT name, physical_name FROM sys.database_files WHERE type_desc = 'FILESTREAM';
  • If the folder was renamed or moved, take the database offline and restore the correct path, or use ALTER DATABASE to repoint the filegroup if supported.

Step 4: Restart the SQL Server Service and Dependent Services

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Restart SQL Server (MSSQLSERVER) and SQL Server VSS Writer services to release any stale file handles.
  • Check the SQL Server Error Log immediately after restart for confirmation that FILESTREAM initialized without errors.

Alternative or Verification Steps

  • Run DBCC CHECKFILEGROUP against the affected filegroup to confirm the container is now readable and consistent.
  • If the issue persists, restore the FILESTREAM filegroup from a verified backup using RESTORE DATABASE ... WITH FILE targeting a new, clean container path.

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

Troubleshooting Guide: Error 5503 – FILESTREAM File Entry Not Found in sys.database_files

Why This Error Happens

This error occurs when SQL Server’s internal metadata catalog (sys.database_files) does not contain a corresponding record for a FILESTREAM data container that the Database Engine is attempting to access. This mismatch is typically caused by an inconsistent or corrupted FILESTREAM filegroup directory structure, a database that was restored or attached without properly migrating the underlying FILESTREAM data folders, or manual deletion/modification of files within the FILESTREAM data container outside of SQL Server. In Windows Server 2025 environments, this can also surface after an abrupt failover or improper VSS-based snapshot restore that leaves the NTFS/ReFS folder GUIDs out of sync with the database metadata.

Step-by-Step Resolution Guide

Step 1: Verify FILESTREAM Configuration at the Instance Level

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm FILESTREAM is enabled for the instance (SQL Server Services > right-click instance > Properties > FILESTREAM tab).
  • Ensure “Enable FILESTREAM for Transact-SQL access” and “Allow remote clients access to FILESTREAM data” are checked if remote access is required.
  • Run the following query to confirm the instance-level setting is active:
EXEC sp_configure 'filestream access level';

Step 2: Inspect the sys.database_files Metadata

  • Query the catalog view to identify the missing or mismatched entry:
SELECT file_id, type_desc, name, physical_name 
FROM sys.database_files 
WHERE type_desc = 'FILESTREAM';
  • Cross-reference the physical_name path with the actual folder structure on disk (e.g., D:\SQLData\FileStreamContainer\).
  • If the folder exists on disk but is missing from this view, the metadata is desynchronized and requires a filegroup repair.

Step 3: Repair or Re-add the FILESTREAM Filegroup

  • If the physical folder is missing or corrupted, remove the orphaned reference and re-add the file:
ALTER DATABASE YourDB 
REMOVE FILE FileStreamLogicalName;

ALTER DATABASE YourDB 
ADD FILE (NAME = FileStreamLogicalName, FILENAME = 'D:\SQLData\FileStreamContainer_New') 
TO FILEGROUP FileStreamGroup;
  • If the folder exists but Windows NTFS permissions are blocking access, grant the SQL Server service account full control via File Explorer > Properties > Security or via PowerShell:
icacls "D:\SQLData\FileStreamContainer" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)F"

Step 4: Restart the SQL Server Service and Validate Database State

  • Restart the SQL Server (MSSQLSERVER) service via Services.msc or PowerShell:
Restart-Service -Name 'MSSQLSERVER' -Force
  • Run DBCC CHECKDB (YourDB) WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no further structural corruption exists in the FILESTREAM filegroup.

Alternative or Verification Steps

  • Confirm the fix by inserting/retrieving a test FILESTREAM record using a client application or OPENROWSET(BULK...) to ensure the file handle resolves correctly.
  • If the error persists, restore the database from the last known good backup (full + log chain) taken prior to the FILESTREAM corruption event, ensuring the FILESTREAM container path is restored to its original location.

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

Troubleshooting Guide: SQL Server Error 5504

Why This Error Happens

Error 5504 occurs when a CREATE TABLE or ALTER TABLE statement attempts to use a CONTAINS clause that references the PRIMARY filegroup for FILESTREAM data, rather than a dedicated FILESTREAM filegroup. SQL Server 2025 strictly enforces that FILESTREAM data columns must be bound to a filegroup explicitly created with the CONTAINS FILESTREAM option, since the PRIMARY filegroup is reserved for standard row and page data. This typically happens due to a misconfigured table definition script, a database migration that didn’t properly map filegroups, or a developer copying DDL syntax without updating the filegroup reference.

Step-by-Step Resolution Guide

Step 1: Verify Existing Filegroup Configuration

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to check current filegroups:
SELECT name, type_desc, is_default 
FROM sys.filegroups;
  • Confirm whether a FILESTREAM-type filegroup (type_desc = 'FD') already exists in the target database.

Step 2: Create a Dedicated FILESTREAM Filegroup

  • If no FILESTREAM filegroup exists, create one using ALTER DATABASE:
ALTER DATABASE [YourDatabase] 
ADD FILEGROUP FileStreamGroup CONTAINS FILESTREAM;
  • Associate a physical path with the new filegroup:
ALTER DATABASE [YourDatabase] 
ADD FILE (NAME = FileStreamData, FILENAME = 'C:\SQLData\FileStreamData') 
TO FILEGROUP FileStreamGroup;
  • Ensure the path (e.g., C:\SQLData\FileStreamData) exists and the SQL Server service account has write permissions.

Step 3: Correct the Table Definition

  • Modify your CREATE TABLE or ALTER TABLE script to reference the new FILESTREAM filegroup instead of PRIMARY.
  • Example corrected syntax:
CREATE TABLE dbo.Documents (
    DocID UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE,
    DocContent VARBINARY(MAX) FILESTREAM NULL
) FILESTREAM_ON FileStreamGroup;
  • Re-run the script and confirm Error 5504 no longer appears.

Step 4: Enable FILESTREAM at the Instance Level (If Not Already Enabled)

  • Open SQL Server Configuration Manager on Windows Server 2025.
  • Navigate to SQL Server Services, right-click your instance, and select Properties.
  • Go to the FILESTREAM tab and enable “FILESTREAM for Transact-SQL access.”
  • Restart the SQL Server service for changes to take effect.

Alternative or Verification Steps

  • Run sp_configure 'filestream access level' to confirm the value is set to 1 or 2, verifying FILESTREAM is active at the instance level.
  • If the error persists, drop and recreate the table using the corrected FILESTREAM_ON clause pointing explicitly to the FILESTREAM filegroup rather than relying on database defaults.

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

Troubleshooting Guide: Error 5382 – Index on Expression Feature Disabled

Why This Error Happens

This error occurs because SQL Server 2025 introduces a new feature called “Index on Expression,” which allows indexes to be created on computed expressions rather than just physical columns. When this feature flag is turned OFF at the instance or database level, SQL Server blocks any operation—including DROP INDEX—on indexes that were built using expression-based columns, since the engine cannot safely parse or validate the expression metadata while the feature is disabled. This typically happens after a server migration, a configuration rollback, or when a database is restored onto an instance with a different feature configuration than the source.

Step-by-Step Resolution Guide

Step 1: Verify the Current Feature Configuration Status

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to the target instance.
  • Run the following query to check the current state of the feature:
  SELECT name, value, value_in_use 
  FROM sys.configurations 
  WHERE name = 'index on expression feature';
  • Confirm that value_in_use returns 0, which indicates the feature is currently disabled.

Step 2: Enable the ‘Index on Expression’ Feature

  • Execute the following T-SQL commands to turn the feature back on at the instance level:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'index on expression feature', 1;
  RECONFIGURE;
  • Restart the SQL Server service via Windows Services (services.msc) or SQL Server Configuration Manager to ensure the change propagates correctly on Windows Server 2025/Windows 11.

Step 3: Retry the DROP INDEX Operation

  • Reconnect to the database and attempt the original command again:
  DROP INDEX [YourIndexName] ON [dbo].[YourTableName];
  • If the command succeeds without Error 5382, the feature toggle was the root cause.

Step 4: Check Database-Level Compatibility Settings

  • If the error persists, verify the database compatibility level, as expression indexes require compatibility level 170 or higher:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is lower, update it using:
  ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verification: Query sys.indexes and sys.index_columns joined with sys.computed_columns to confirm the index no longer appears in the system catalog after the drop.
  • Alternative Fix: If enabling the feature is not permitted by your organization’s security policy, export the table schema, manually migrate data to a new table without the expression-based index, and rename the tables to swap them into production.

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

Troubleshooting Guide: SQL Server Error 5383 – Cannot Reference Index on Expression Column

Why This Error Happens

Error 5383 occurs because SQL Server does not allow indexes to be created directly on computed columns that reference expressions in certain unsupported configurations, such as non-deterministic functions, columns lacking the PERSISTED attribute, or expressions that rely on CLR functions without the correct determinism attributes. This typically happens when a developer attempts to build an index on a computed column whose underlying expression cannot be guaranteed to return the same result for the same inputs. Without this guarantee, SQL Server’s query optimizer cannot reliably store or maintain the index, triggering a schema validation failure during the CREATE INDEX operation.

Step-by-Step Resolution Guide

Step 1: Verify the Computed Column Definition

  • Run sp_helpcolumns 'YourTableName' or query sys.computed_columns to inspect the exact expression used.
  • Check if the column uses non-deterministic functions (e.g., GETDATE(), NEWID(), or certain CLR methods) which inherently block indexing.
  • Identify if the PERSISTED keyword is missing from the computed column definition.

Step 2: Mark the Column as PERSISTED

  • Alter the table to add the PERSISTED keyword to the computed column definition:
  • ALTER TABLE YourTable ADD COMPUTED_COL AS (Expression) PERSISTED;
  • Note that PERSISTED only works if the expression is deterministic; non-deterministic expressions must be refactored before this step will succeed.

Step 3: Validate CLR Function Determinism (If Applicable)

  • If the expression calls a CLR user-defined function, open SQL Server Management Studio (SSMS) and check the function’s attributes.
  • Ensure the function is decorated with [SqlFunction(IsDeterministic = true, IsPrecise = true)] in the original C# source code.
  • Redeploy the assembly to the instance using ALTER ASSEMBLY if changes were made to the attribute.

Step 4: Recreate the Index

  • Drop any failed index attempts using DROP INDEX IF EXISTS IX_YourIndex ON YourTable;.
  • Re-run the CREATE INDEX IX_YourIndex ON YourTable (ComputedColumnName); command.
  • Confirm the SQL Server 2025 instance service is running under the correct service account in services.msc on Windows Server 2025, as permission mismatches can sometimes mask as schema errors during DDL operations.

Alternative or Verification Steps

  • To verify the fix, query sys.indexes joined with sys.columns to confirm the new index is listed as is_disabled = 0 and active against the computed column.
  • If the expression absolutely cannot be made deterministic (e.g., it relies on external system calls), create a standard non-computed column, populate it via a trigger or scheduled job, and index that physical column instead.

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

Troubleshooting Guide: Error 5501 – FILESTREAM Filegroup Dropped Before Table Creation

Why This Error Happens

This error occurs when a CREATE TABLE statement referencing a FILESTREAM column attempts to bind to a filegroup that no longer exists at execution time, typically due to a race condition between a DROP FILEGROUP command and the table creation script running in a separate session or transaction. It can also happen when automated deployment scripts or migration tools execute out of order, dropping the FILESTREAM filegroup as part of a cleanup routine before the dependent table object is committed. Additionally, corrupted metadata in the system catalog views (sys.filegroups) following an improper database restore can cause SQL Server to falsely report the filegroup as missing.

Step-by-Step Resolution Guide

Step 1: Verify Filegroup Existence and State

  • Open SQL Server Management Studio (SSMS) and connect to the instance via Windows 11 or Windows Server 2025.
  • Run the following query to check current filegroups: SELECT name, type_desc, is_default FROM sys.filegroups;
  • Confirm if the specific FILESTREAM filegroup (e.g., FileStreamGroup1) is present in the result set.

Step 2: Recreate the Missing Filegroup

  • If the filegroup is confirmed missing, you must add it back to the database before attempting the table creation again.
  • Execute: ALTER DATABASE [YourDB] ADD FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM;
  • Associate a physical path to the filegroup using: ALTER DATABASE [YourDB] ADD FILE (NAME = FS_Data, FILENAME = 'C:\SQLData\FileStreamFiles') TO FILEGROUP FileStreamGroup1;
  • Ensure the target directory (e.g., C:\SQLData\) exists and the SQL Server service account has Modify permissions on this folder.

Step 3: Audit and Serialize Deployment Scripts

  • Review any DevOps pipelines, PowerShell scripts, or SSDT (SQL Server Data Tools) publish profiles that manage schema changes.
  • Ensure DROP FILEGROUP commands are explicitly sequenced to run after all dependent CREATE TABLE statements, rather than relying on asynchronous execution.
  • Add a WAITFOR DELAY or explicit transaction locking mechanism in T-SQL scripts if multiple sessions are modifying the schema simultaneously.

Step 4: Check FILESTREAM Instance Configuration

  • Open SQL Server Configuration Manager on Windows Server 2025.
  • Navigate to SQL Server Services, right-click your instance, and select Properties.
  • Go to the FILESTREAM tab and ensure “Enable FILESTREAM for Transact-SQL access” is checked; restart the SQL Server service if changes were made.

Alternative or Verification Steps

  • Verification: Re-run the original CREATE TABLE script with the FILESTREAM column; if successful, query sys.database_files to confirm the new file path is correctly mapped to the filegroup ID.
  • Alternative: If the filegroup cannot be recovered due to corruption, restore the database from the last known good backup taken prior to the erroneous DROP FILEGROUP execution, then manually re-apply only the schema changes that occurred after that backup point.

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

Troubleshooting Guide: Error 5379 in Microsoft SQL Server 2025

Why This Error Happens

Error 5379 occurs when a column definition in a CREATE EXTERNAL TABLE or bulk operation statement explicitly specifies a column ordinal value for a file format that does not support ordinal-based column mapping (such as JSON or Parquet). This typically happens when scripts generated for one file format (like CSV with DATA_SOURCE ordinal positioning) are reused or copy-pasted for an incompatible format without removing the COLUMN_ORDINAL property. It can also arise due to corrupted or outdated external table metadata that retains legacy ordinal attributes after a file format migration.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column Definition

  • Open the T-SQL script that generated the external table or bulk insert operation.
  • Locate the specific column named in the error message (%ls).
  • Check if a COLUMN_ORDINAL = n property is explicitly declared within the WITH clause for that column.

Step 2: Remove or Correct the Ordinal Property

  • If the file format is Parquet, ORC, or JSON, delete the COLUMN_ORDINAL attribute entirely, as these formats use schema-on-read column name matching rather than positional indexing.
  • If the file format is Delimited Text (CSV), verify that COLUMN_ORDINAL values are sequential integers starting from 1 with no gaps or duplicates.
  • Save the corrected script to a local path, e.g., C:\Scripts\Fix_ExternalTable.sql.

Step 3: Drop and Recreate the External Table

  • Execute DROP EXTERNAL TABLE [SchemaName].[TableName]; to clear the corrupted metadata.
  • Re-run the corrected CREATE EXTERNAL TABLE statement from your fixed script.
  • Confirm the associated External File Format object matches the data source type using sp_helpexternalfileformat.

Step 4: Restart SQL Server Services (If Cached Metadata Persists)

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or the named instance.
  • Right-click and select Restart to clear any cached schema definitions in the Polybase/External Data engine.

Alternative or Verification Steps

  • Run SELECT * FROM sys.external_columns WHERE object_id = OBJECT_ID('TableName'); to verify no residual ordinal values remain in the system metadata.
  • If the error persists, bypass the issue entirely by querying the data source using OPENROWSET with explicit WITH schema declarations instead of a persistent CREATE EXTERNAL TABLE object.

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

Troubleshooting Guide: SQL Server Error 5380 – Unsupported Column Character

Why This Error Happens

Error 5380 occurs when SQL Server encounters a column name containing square brackets ([ or ]) during metadata operations such as replication, Change Data Capture (CDC), or schema synchronization tasks. These characters are reserved as delimiter identifiers in T-SQL syntax, so when they appear literally within a column name, SQL Server’s internal parsing engine cannot distinguish between the delimiter and the actual column name. This typically stems from data migrated from another system, poorly sanitized dynamic SQL scripts, or applications that allow unrestricted naming conventions during table creation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Review the full error message text, which includes the column name in question (replacing %ls with the actual value).
  • Run the following query to scan for bracket characters across your database schema:
SELECT t.name AS TableName, c.name AS ColumnName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%[[]%' OR c.name LIKE '%]%';
  • Note the exact table and column combination returned.

Step 2: Rename the Column Using Proper Escaping

  • Use sp_rename to safely rename the column, ensuring you wrap the old name in brackets twice to escape it correctly:
EXEC sp_rename 'dbo.YourTable.[Bad]Column]]', 'GoodColumn', 'COLUMN';
  • If the column is referenced in views, stored procedures, or CDC-enabled tables, update those references manually afterward.
  • For CDC or replication scenarios, disable capture on the table first:
EXEC sys.sp_cdc_disable_table @source_schema = 'dbo', @source_name = 'YourTable', @capture_instance = 'all';

Step 3: Re-enable Dependent Features and Validate Scripts

  • If CDC or Replication was disabled in Step 2, re-enable it using sp_cdc_enable_table once the rename is complete.
  • Check any ETL packages (SSIS), linked server queries, or ORM mappings (Entity Framework, Dapper) that reference the old column name and update them accordingly.
  • Re-deploy any affected stored procedures or views using sp_refreshsqlmodule 'YourView' to refresh cached metadata.

Step 4: Restart Associated Services (If Applicable)

  • If the error persists in Windows Server 2025 due to cached execution plans, restart the SQL Server service via services.msc or run:
Restart-Service -Name 'MSSQLSERVER' -Force
  • Clear the procedure cache to ensure no stale references remain:
DBCC FREEPROCCACHE;

Alternative or Verification Steps

  • Verify the fix by re-running the original operation (replication snapshot, CDC capture job, or schema sync) and confirming Error 5380 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS).
  • As an alternative if renaming is not feasible immediately, wrap all references to the column in properly escaped bracket syntax (e.g., [ColumnName]]]) within affected queries, though this is only a temporary workaround and renaming remains the permanent fix.

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

Troubleshooting Guide: Error 5381 – Internal Error During Index On Expression Creation (SQL Server 2025)

Why This Error Happens

Error 5381 typically occurs when SQL Server 2025’s query processor encounters an internal failure while computing or persisting metadata for an Index On Expression (computed/expression-based index), often due to a corrupted plan cache, an incompatible database compatibility level, or a malformed expression that the optimizer cannot resolve during index build. This can also surface if the underlying table schema was altered mid-transaction or if system catalog views (sys.index_columns, sys.computed_columns) contain stale or orphaned metadata. In rarer cases, insufficient ALTER permissions on the schema combined with a corrupted tempdb system database can trigger this internal fault.

Step-by-Step Resolution Guide

Step 1: Verify Database Compatibility Level and Expression Syntax

  • Open SQL Server Management Studio (SSMS) and run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDBName';
  • Ensure compatibility level is set to 170 (SQL Server 2025) using: ALTER DATABASE YourDBName SET COMPATIBILITY_LEVEL = 170;
  • Review the expression used in the CREATE INDEX ... ON (expression) statement for unsupported functions (e.g., non-deterministic functions like GETDATE() are not allowed in expression indexes).

Step 2: Clear Corrupted Plan Cache and Restart Related Services

  • Run DBCC FREEPROCCACHE; to clear any corrupted cached execution plans tied to the index operation.
  • Open Services.msc on Windows Server 2025 / Windows 11, locate SQL Server (MSSQLSERVER), right-click, and select Restart.
  • Alternatively, use PowerShell: Restart-Service -Name 'MSSQLSERVER' -Force

Step 3: Rebuild TempDB System Database

  • Internal errors during index creation are frequently linked to a degraded tempdb. Check tempdb health via DBCC CHECKDB(tempdb);
  • If corruption is found, stop the SQL Server service, delete the tempdb files located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\tempdb.mdf, and restart the service to force tempdb regeneration.

Step 4: Validate Schema and Table Permissions

  • Confirm the executing user has ALTER and REFERENCES permissions on the target table and schema: GRANT ALTER ON SCHEMA::dbo TO [YourUser];
  • Check for orphaned computed column metadata using: SELECT * FROM sys.computed_columns WHERE object_id = OBJECT_ID('YourTable');
  • Drop and recreate the computed column expression if metadata inconsistencies are found.

Step 5: Apply Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update for SQL Server 2025.
  • Run the installer with elevated privileges and confirm the build number post-install via SELECT @@VERSION;

Alternative or Verification Steps

  • After applying fixes, re-run the original CREATE INDEX statement with the expression in a test environment to confirm Error 5381 no longer appears in the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • If the error persists, bypass the expression index temporarily by creating a persisted computed column first, then build a standard non-expression index on that column as a workaround.

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

Troubleshooting Guide: Error 5376 – Cannot Modify Permissions for Index on Expression Column

Why This Error Happens

This error occurs because SQL Server 2025 does not permit explicit permission modifications (GRANT, DENY, REVOKE) directly on computed/expression columns that are referenced by an index, as the engine treats indexed expression columns as derived metadata objects rather than standard securables. This is typically triggered when a DBA or application role attempts to run a column-level security statement against a table where the target column is part of an indexed computed expression. Additionally, this can surface after an in-place upgrade from SQL Server 2022 to 2025, where legacy permission scripts attempt to re-apply column-level ACLs that are no longer compatible with the new Index-on-Expression security model.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Index and Column

  • 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 specific expression column causing the conflict:
  SELECT i.name AS IndexName, c.name AS ColumnName, c.is_computed 
  FROM sys.indexes i 
  INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
  INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
  WHERE c.is_computed = 1;
  • Note the IndexName and ColumnName returned in the result set.

Step 2: Drop and Isolate the Index Before Applying Permissions

  • Since permissions cannot be applied while the index is active on the expression, you must temporarily drop the index.
  • Use the following T-SQL syntax, replacing placeholders with your specific table and index names:
  DROP INDEX [YourIndexName] ON [dbo].[YourTableName];
  • Apply your required GRANT/DENY/REVOKE statements to the base table or the underlying physical columns used in the expression (not the computed column itself).

Step 3: Rebuild the Index with Updated Security Context

  • Once permissions have been successfully applied to the underlying base columns, recreate the index on the expression column.
  • Ensure the WITH (DROP_EXISTING = ON) clause is used if you are modifying an existing structure to maintain fragmentation efficiency:
  CREATE INDEX [YourIndexName] ON [dbo].[YourTableName] ([YourExpressionColumn]) WITH (DROP_EXISTING = ON);
  • Restart the SQL Server service via services.msc on Windows Server 2025 to clear any cached permission metadata if the error persists immediately after the rebuild.

Step 4: Check Group Policy and TLS Restrictions

  • On Windows 11 or Windows Server 2025 hosts, verify that Group Policy restrictions regarding “Network access: Restrict clients allowed to make remote calls to SAM” are not interfering with the SQL Server service account’s ability to modify schema-level security.
  • Navigate to Local Security Policy > Local Policies > Security Options to review these settings if the error correlates with a specific Windows user account rather than a SQL login.

Alternative or Verification Steps

  • Verification: Run SELECT * FROM fn_my_permissions('YourTableName', 'OBJECT'); to confirm that the “ALTER” and “CONTROL” permissions are correctly inherited by the expression column following the index rebuild.
  • Alternative: If the error persists, create a non-computed, persisted shadow column via ALTER TABLE ADD... PERSISTED, apply the specific permission set to that physical column, and then update the application logic to query the new persisted column instead of the original expression.

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

Troubleshooting Guide: SQL Server Error 5377

Why This Error Happens

Error 5377 occurs when a column referenced by an index on a computed/expression column is targeted directly by an ALTER TABLE ... ALTER COLUMN statement. SQL Server 2025 blocks this modification because changing the underlying column’s data type, nullability, or collation could invalidate the expression logic and corrupt the dependent index. This typically happens when developers forget that an index exists on a computed column or persisted expression tied to the column being altered, rather than on the base column itself.

Step-by-Step Resolution Guide

Step 1: Identify the Dependent Index and Expression

  • Run the following query to locate indexes built on computed columns referencing your target column:
SELECT i.name AS index_name, c.name AS column_name, cc.definition
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
JOIN sys.computed_columns cc ON c.object_id = cc.object_id AND c.column_id = cc.column_id
WHERE c.object_id = OBJECT_ID('YourTableName');
  • Note the index_name and cc.definition for use in later steps.

Step 2: Drop the Dependent Index Temporarily

  • Use SQL Server Management Studio (SSMS) 2025 or sqlcmd to drop the identified index:
DROP INDEX [IX_YourIndexName] ON [dbo].[YourTableName];
  • Confirm the drop by re-running the query from Step 1 — it should return no rows for that index.

Step 3: Alter the Base Column

  • Execute your original ALTER TABLE statement now that the dependency is removed:
ALTER TABLE [dbo].[YourTableName]
ALTER COLUMN [YourColumnName] NVARCHAR(100) NULL;
  • Verify no error 5377 or related dependency errors are returned in the Messages pane.

Step 4: Recreate the Index on the Expression Column

  • Rebuild the index using the original definition captured in Step 1:
CREATE INDEX [IX_YourIndexName]
ON [dbo].[YourTableName] ([YourComputedColumnName]);
  • If the computed column itself referenced the altered column’s old data type, update the computed column definition first via ALTER TABLE ... DROP COLUMN and ADD before recreating the index.

Step 5: Validate Index Health and Statistics

  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to confirm no corruption resulted from the rebuild.
  • Update statistics using UPDATE STATISTICS [dbo].[YourTableName]; to ensure the query optimizer has current data.

Alternative or Verification Steps

  • Verify the fix by querying sys.indexes and sys.computed_columns again to confirm the index exists and is marked as is_disabled = 0.
  • If dropping the index isn’t feasible due to high-availability constraints (e.g., Always On Availability Groups), consider altering the computed column expression instead to avoid referencing the problematic base column directly, then use WITH (ONLINE = ON) when rebuilding the index to minimize downtime.

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

Troubleshooting Guide: Error 5378 — “Adding Constraint to Index On Expression Column Is Not Allowed”

Why This Error Happens

This error occurs because SQL Server 2025 does not permit certain constraints—such as PRIMARY KEY, FOREIGN KEY, UNIQUE, or DEFAULT constraints—to be directly applied to a computed column that is based on an indexed expression. The root cause is typically a schema design conflict where a computed/expression-based column was indexed first, and a subsequent ALTER TABLE statement attempts to layer an unsupported constraint on top of it. This is a metadata validation restriction enforced by the Database Engine rather than a permissions or connectivity issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Index

  • Run sp_helpindex 'YourTableName' in SQL Server Management Studio (SSMS) to list all indexes on the table.
  • Cross-reference the column named in the error message (%.*s) with the sys.computed_columns system view using: SELECT name, definition FROM sys.computed_columns WHERE object_id = OBJECT_ID('YourTableName');
  • Confirm whether the column is persisted (is_persisted = 1) or purely virtual, as this affects how constraints can be applied.

Step 2: Drop the Existing Index on the Expression

  • Open a new query window in SSMS or Azure Data Studio connected to your Windows Server 2025 instance.
  • Execute DROP INDEX IX_IndexName ON YourSchema.YourTableName; to remove the index currently bound to the computed expression.
  • Verify the drop succeeded by re-running sp_helpindex to ensure the index no longer appears in the results.

Step 3: Restructure the Constraint Logic

  • Instead of applying the constraint directly to the expression-based column, create a new persisted computed column using ALTER TABLE YourTableName ADD NewColumnName AS (YourExpression) PERSISTED;
  • Apply the desired constraint (e.g., UNIQUE or CHECK) to this new persisted column rather than the original expression.
  • Update any application logic or views in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\ referencing the old column name to point to the new one.

Step 4: Rebuild the Index Separately

  • Once the constraint is successfully applied to the persisted column, recreate the index using CREATE INDEX IX_NewIndexName ON YourTableName(NewColumnName);
  • Ensure the index rebuild is scheduled during a maintenance window to avoid locking issues on large tables.
  • Check SQL Server Error Logs (via SSMS Object Explorer > Management > SQL Server Logs) to confirm no residual errors were logged during the rebuild.

Alternative or Verification Steps

  • Run DBCC CHECKCONSTRAINTS('YourTableName') to confirm the new constraint is active and valid without triggering Error 5378.
  • If the error persists, consider removing the PERSISTED keyword and instead enforcing the business rule via an INSTEAD OF trigger, which bypasses the expression-indexing limitation entirely.

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

Troubleshooting Guide: SQL Server Error 5374 – WITH Clause Not Supported for Connector/Format Combination

Why This Error Happens

This error occurs when SQL Server 2025’s PolyBase or External Data Source engine parses a CREATE EXTERNAL TABLE or OPENROWSET statement containing a WITH clause that specifies options incompatible with the target connector (e.g., ODBC, GENERIC, or S3) and format (e.g., PARQUET, DELTA, or CSV) combination. Certain connectors restrict which WITH options—such as DATA_SOURCE, FILE_FORMAT, or LOCATION—can be paired with specific file formats, and the engine enforces this validation strictly at parse time. This typically happens after a migration or script reuse from an older SQL Server version where the connector/format pairing rules were more permissive or different.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Connector and Format Combination

  • Open the failing script and locate the CREATE EXTERNAL TABLE, CREATE EXTERNAL DATA SOURCE, or OPENROWSET statement.
  • Note the LOCATION connector prefix (e.g., odbc://, s3://, https://) and the FORMAT_TYPE or FORMAT value specified in the WITH clause.
  • Cross-reference both values against the official Microsoft documentation table for SQL Server 2025 PolyBase connector/format support matrix.

Step 2: Remove or Relocate Unsupported WITH Clause Options

  • Strip out the WITH clause entirely from the LOCATION definition if the connector does not support inline formatting options.
  • Move format-specific settings (such as FIELDTERMINATOR, ROWTERMINATOR, or DATA_COMPRESSION) into a separate CREATE EXTERNAL FILE FORMAT object instead of inline in the WITH clause.
  • Example corrected syntax:
  CREATE EXTERNAL FILE FORMAT MyParquetFormat
  WITH (FORMAT_TYPE = PARQUET);

  CREATE EXTERNAL TABLE MyTable (...)
  WITH (LOCATION = 'odbc://server/path', FILE_FORMAT = MyParquetFormat);

Step 3: Update PolyBase Connectivity Configuration

  • Open SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Navigate to SQL Server Network Configuration and confirm PolyBase services are running under Services.msc as SQL Server PolyBase Engine and SQL Server PolyBase Data Movement.
  • Restart both services after any configuration file changes located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\Polybase\Settings\.

Step 4: Validate External Data Source Definition

  • Run sp_configure 'polybase enabled', 1; followed by RECONFIGURE; to ensure PolyBase features are active.
  • Re-create the EXTERNAL DATA SOURCE object explicitly specifying CONNECTION_OPTIONS compatible with the chosen format, avoiding deprecated syntax from SQL Server 2019/2022 scripts.

Step 5: Re-run the Query in a Clean Session

  • Disconnect and reconnect via SQL Server Management Studio (SSMS) 21 to clear cached metadata.
  • Execute the corrected CREATE EXTERNAL TABLE statement in a new query window to confirm the parser accepts the revised syntax.

Alternative or Verification Steps

  • Verify the fix by querying sys.external_tables and sys.external_file_formats to confirm the object was created without errors and metadata reflects the correct format type.
  • If the error persists, as an alternative, use OPENROWSET(BULK...) with a standalone FORMAT_OPTIONS clause instead of a connector-specific WITH clause, which bypasses the stricter validation path entirely for ad hoc queries.

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

Why This Error Happens

Error 5375 occurs when SQL Server 2025 attempts to directly reference a hidden internal computed column that backs a filtered or expression-based index, which is not permitted outside of internal query processing operations. This typically surfaces when a query, DBCC command, or third-party tool tries to explicitly select, update, or reference this system-generated column by name. It can also appear after a failed index rebuild or an in-place upgrade from an older SQL Server version where metadata for expression indexes became inconsistent.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Object

  • Capture the exact query text from the error message in SSMS or the SQL Server error log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • Run the following to locate indexes with expression-based or computed definitions on the affected table:
SELECT i.name, i.index_id, c.name AS column_name
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE i.object_id = OBJECT_ID('YourSchema.YourTable');
  • Confirm whether the referenced column name matches an internal %hind% or expression-generated identifier rather than a user-defined column.

Step 2: Rebuild or Drop/Recreate the Affected Index

  • Avoid referencing internal columns directly in SELECT, WHERE, or application ORM-generated queries; instead query the base computed column or expression itself.
  • Rebuild the index to force metadata regeneration:
ALTER INDEX ALL ON YourSchema.YourTable REBUILD;
  • If rebuild fails or the error persists, drop and recreate the index explicitly:
DROP INDEX IX_YourExpressionIndex ON YourSchema.YourTable;
CREATE INDEX IX_YourExpressionIndex ON YourSchema.YourTable (CONVERT(date, YourDateTimeColumn));

Step 3: Check for Upgrade or Compatibility Level Issues

  • Verify the database compatibility level matches SQL Server 2025 requirements:
SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • Run DBCC CHECKDB('YourDatabase') WITH DATA_PURITY to rule out metadata or page-level corruption affecting internal column structures.
  • Restart the SQL Server service via Services.msc or net stop MSSQLSERVER && net start MSSQLSERVER on Windows Server 2025 after applying compatibility or index changes.

Step 4: Restrict Direct Application Access

  • Audit any third-party reporting tools, ORMs (e.g., Entity Framework, Hibernate), or linked server queries that may auto-generate SELECT * statements exposing hidden columns.
  • Explicitly list required columns in views and stored procedures instead of using SELECT * on tables containing expression indexes.

Alternative or Verification Steps

  • Re-run the original failing query or application workflow to confirm error 5375 no longer appears in the SQL Server error log or Event Viewer.
  • If the issue persists after rebuilding, export the table data, drop all expression/filtered indexes entirely, recreate the table schema cleanly, and reapply indexes one at a time to isolate the corrupted definition.

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

Why This Error Happens

Error 5371 occurs when SQL Server 2025’s PolyBase or external data source connector detects a mismatch between the location prefix (such as abfss://, wasbs://, s3://, or odbc://) and the FORMAT type declared in the CREATE EXTERNAL FILE FORMAT or CREATE EXTERNAL TABLE statement. This typically happens because certain connector prefixes are only compatible with specific file formats (e.g., Delta Lake requires abfss:// or s3a://, while flat-file CSV formats support a narrower set of prefixes). The issue is also triggered by outdated PolyBase connectors that haven’t been patched to recognize newer prefix/format combinations introduced in SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Verify the External File Format Definition

  • Open SSMS and query sys.external_file_formats to inspect the FORMAT_TYPE currently bound to your external table.
  • Confirm the format type (e.g., PARQUET, DELTA, CSV) explicitly supports the connector prefix used in your LOCATION string.
  • Cross-check against Microsoft’s supported matrix: Delta format only supports abfss:// and s3a://; CSV/PARQUET support wasbs://, abfss://, s3://, and https://.

Step 2: Correct the Connector Prefix or FORMAT Clause

  • Edit the CREATE EXTERNAL DATA SOURCE statement to use a supported prefix. Example fix:
  CREATE EXTERNAL DATA SOURCE MyDataSource
  WITH (
      LOCATION = 'abfss://container@account.dfs.core.windows.net/path',
      CREDENTIAL = MyCredential
  );
  • If the prefix cannot change (due to storage account type), instead alter the FILE_FORMAT to one compatible with that prefix.
  • Drop and recreate the external table only after confirming the prefix/format pairing is valid.

Step 3: Update PolyBase and Connector Components

  • On Windows Server 2025/Windows 11, open PowerShell as Administrator and run:
  Get-Service MSSQLSERVER, MSSQLLaunchpad | Restart-Service
  • Check for and apply the latest Cumulative Update (CU) for SQL Server 2025, since connector-prefix validation logic is frequently patched.
  • Reinstall the PolyBase feature via SQL Server Setup if the connector DLLs (Microsoft.SqlServer.DataWarehouse.Connectivity.*) appear outdated in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\Polybase\.

Step 4: Validate Credential and Data Source Scope

  • Ensure the DATABASE SCOPED CREDENTIAL used matches the authentication method required by the prefix (e.g., SAS token for wasbs://, Managed Identity for abfss://).
  • Mismatched credentials can sometimes surface as Error 5371 instead of a standard authentication failure, so re-validate this mapping before re-testing.

Alternative or Verification Steps

  • Run a lightweight test query against the external table (SELECT TOP 10 * FROM MyExternalTable;) to confirm the prefix/format combination resolves without throwing Error 5371.
  • If the error persists, bypass the native connector and use OPENROWSET with the BULK option as an alternative method to read the external file directly, which uses a different validation path.

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

Troubleshooting Guide: Error 5372 in SQL Server 2025

Why This Error Happens

Error 5372 occurs when a BULK INSERT or OPENROWSET(BULK...) statement specifies an option (such as FORMATFILE, ROWTERMINATOR, or FIELDQUOTE) that is incompatible with the declared FILE_FORMAT or data source type (e.g., attempting CSV-specific syntax against a Parquet file). This typically arises from a mismatch between legacy flat-file bulk options and the newer structured file formats introduced for Data Lake integration in SQL Server 2025. It can also occur if a format file (.fmt or .xml) was generated for a different file type than the one currently being referenced in the BULK command.

Step-by-Step Resolution Guide

Step 1: Verify the File Format Compatibility

  • Check the FILE_FORMAT object definition using sp_helpexternalfileformat to confirm whether the source is defined as DELIMITEDTEXT, PARQUET, or ORC.
  • Ensure you are not mixing text-specific options (like CODEPAGE or ROWTERMINATOR) with a PARQUET or ORC format, as these binary formats manage schema internally and do not support manual delimiter overrides.

Step 2: Audit the T-SQL Syntax for Deprecated Options

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio and review the exact BULK INSERT query.
  • Remove deprecated flags such as KEEPNULLS or FIRE_TRIGGERS if the target FILE_FORMAT is set to PARQUET.
  • Cross-reference the specific option throwing the error against the sys.external_file_formats catalog view to ensure it exists for that format type.

Step 3: Recreate the External File Format Object

  • Drop the existing file format object to clear potential metadata corruption:
 DROP EXTERNAL FILE FORMAT [YourFormatName];
  • Recreate it with explicit, format-appropriate syntax. For a Parquet-based import, ensure you are not passing a FORMAT_TYPE = 'CSV' option:
 CREATE EXTERNAL FILE FORMAT [YourFormatName]
 WITH (FORMAT_TYPE = PARQUET);

Step 4: Check Windows Server 2025 File Path Permissions

  • Navigate to the physical storage location (local path or mapped network share) referenced in the BULK command.
  • Right-click the folder, select Properties > Security, and verify the NT SERVICE\MSSQLSERVER account has at least Read & Execute permissions.
  • Restart the SQL Server service via services.msc if permissions were just updated to ensure the token refreshes.

Alternative or Verification Steps

  • Verification: Re-run the original BULK INSERT or OPENROWSET query. If successful, query the destination table using SELECT TOP 10 * FROM [TargetTable] to confirm data integrity and correct column mapping.
  • Alternative: If the error persists specifically with Parquet files, bypass the BULK INSERT T-SQL command entirely and use the SQL Server Import and Export Wizard (available via SSMS 21) to graphically map the Parquet schema to the destination table.

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

Troubleshooting Guide: SQL Server Error 5373 – “All Input Parameters Should Be of the Same Type”

Why This Error Happens

Error 5373 occurs when a system or user-defined function (commonly spatial functions, CONCAT_WS, or table-valued parameters) receives mixed data types across arguments where SQL Server expects uniform typing. This frequently stems from implicit conversions failing silently during schema upgrades, or from client applications (ODBC/OLE DB drivers) passing mismatched parameter types in a batch. In SQL Server 2025, stricter type-checking in the query optimizer surfaces this issue more aggressively than in prior versions, especially after in-place upgrades from SQL Server 2019/2022.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query or Procedure

  • Capture the exact T-SQL statement using Extended Events or the SQL Server Error Log (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG).
  • Run SELECT * FROM sys.dm_exec_query_stats cross-applied with sys.dm_exec_sql_text to pinpoint the query handle associated with Error 5373.
  • Check if the error correlates with spatial functions (geography::STUnion) or CONCAT_WS/IIF calls with mixed tinyint, smallint, or int parameters.

Step 2: Correct Parameter Data Types Explicitly

  • Modify the query to explicitly CAST or CONVERT all parameters to a single matching type, prioritizing tinyint if that is the base type referenced in the error.
  • Example fix: SELECT dbo.MyFunction(CAST(@Param1 AS tinyint), CAST(@Param2 AS tinyint)).
  • Update any stored procedures or views in SSMS (Object Explorer → Programmability → Stored Procedures) that pass variables without explicit casting.

Step 3: Update Client Drivers and Connection Strings

  • Ensure the application server (Windows Server 2025) is using the latest Microsoft OLE DB Driver 19 or ODBC Driver 18 for SQL Server, downloadable via winget install Microsoft.ODBCDriverforSQLServer.
  • Verify connection string parameters aren’t auto-converting types inconsistently (e.g., mixing SqlDbType.TinyInt and SqlDbType.Int in ADO.NET parameter collections).
  • Restart the SQL Server (MSSQLSERVER) service via services.msc after driver updates to clear cached execution plans.

Step 4: Clear and Rebuild Execution Plan Cache

  • Run DBCC FREEPROCCACHE to eliminate any corrupted or outdated cached plans that may be enforcing incorrect type assumptions from before a schema change.
  • Follow with UPDATE STATISTICS on the affected tables to ensure the optimizer has current type/cardinality metadata.

Alternative or Verification Steps

  • Re-run the original query or application transaction that triggered Error 5373 and confirm it completes without the type-mismatch exception in the Windows Event Viewer (Application Log, Source: MSSQLSERVER).
  • If the error persists, isolate the issue by testing the function/procedure directly in SSMS with hardcoded literal values of a single explicit type to confirm whether the root cause is client-side parameter binding rather than the database schema itself.

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

Why This Error Happens

Error 5368 occurs when a BACKUP or RESTORE command includes an option that is incompatible with the specified backup format, such as attempting to use COMPRESSION with a format that does not support it, or mixing legacy TAPE syntax with BACKUP TO URL. This typically happens due to a T-SQL syntax mismatch, an outdated script that uses deprecated flags, or an attempt to apply enterprise-only features (like compression or encryption) on an edition that does not support them. In Microsoft SQL Server 2025, stricter format validation was introduced, causing scripts that previously worked (with silent ignores) to now throw a hard error.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Syntax

  • Open the specific T-SQL script that triggered Error 5368 in SQL Server Management Studio (SSMS).
  • Look for the specific options mentioned in the error message (e.g., WITH FORMAT, COMPRESSION, MEDIANAME).
  • Check if you are mixing BACKUP ... TO URL (Azure Blob Storage) with local disk-specific options like SKIP or NOREWIND, which are not interchangeable.

Step 2: Validate Backup Compression Settings

  • Navigate to SSMS > Right-click Server > Properties > Database Settings.
  • Verify the “Compress backup” default setting is appropriate for your target format.
  • If using a direct query, ensure the syntax follows the 2025 standard:
BACKUP DATABASE [YourDB] 
TO DISK = N'C:\Backups\YourDB.bak' 
WITH COMPRESSION, STATS = 10;
  • Remove the COMPRESSION flag entirely if you are backing up to a VIRTUAL_DEVICE or a format that explicitly rejects it.

Step 3: Check Edition Compatibility

  • Run the following query to confirm you are not running Standard Edition while trying to use Enterprise-only backup options:
SELECT SERVERPROPERTY('Edition');
  • If the output shows “Standard Edition,” remove advanced options like COMPRESSION or ENCRYPTION from the script, as these are restricted on non-Enterprise builds in specific format contexts.

Step 4: Update Maintenance Plans

  • Open SQL Server Agent > Jobs and locate the specific Maintenance Plan causing the failure.
  • Edit the “Back Up Database” task and toggle the “Set backup compression” dropdown to “Use the default server setting” instead of forcing a specific format manually.
  • Save and re-run the job step to clear the cached execution plan that holds the invalid syntax.

Alternative or Verification Steps

  • Verification: Run the backup command manually via a New Query window in SSMS. If the backup completes with “100 percent processed” and no red error text, the format conflict is resolved.
  • Alternative: If the error persists on complex jobs, strip the command down to the bare minimum (BACKUP DATABASE TO DISK) and add options back one by one to isolate exactly which specific flag Windows Server 2025 is rejecting.

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

Troubleshooting Guide: SQL Server Error 5369

Why This Error Happens

Error 5369 occurs when an external table or data source definition in SQL Server 2025 specifies an OPTION parameter that is incompatible with the combination of the connector type and the FORMAT value being used. This typically happens because PolyBase or the external data connector (e.g., S3, Azure Blob, Generic ODBC) enforces strict validation rules that reject format-specific options like FIELD_TERMINATOR or FIRST_ROW when the target format (such as PARQUET or DELTA) does not support row-level text parsing options. Essentially, the engine detects a mismatch between the serialization format and the storage connector’s supported option set, causing the external table creation or query to fail.

Step-by-Step Resolution Guide

Step 1: Review the External File Format Definition

  • Open the T-SQL script where the CREATE EXTERNAL FILE FORMAT statement is defined.
  • Check the FORMAT_TYPE value (e.g., PARQUET, DELIMITEDTEXT, DELTA, ORC).
  • Confirm whether the offending option (named in the error message as %ls) is actually valid for that format type. For example, FIELD_TERMINATOR and STRING_DELIMITER are only valid for DELIMITEDTEXT, not PARQUET.

Step 2: Align Connector and Format Compatibility

  • Identify the external connector/location prefix used in CREATE EXTERNAL DATA SOURCE (e.g., s3://, https://, odbc://, abfss://).
  • Cross-reference Microsoft’s connector compatibility matrix for SQL Server 2025 to confirm the format/connector pairing is supported.
  • Remove or comment out unsupported WITH clause options such as:
-- Example of invalid combination
WITH (
    FORMAT_TYPE = PARQUET,
    FIELD_TERMINATOR = ','  -- Invalid for PARQUET, remove this line
)

Step 3: Recreate the External Table or File Format

  • Drop the existing external file format and external table objects:
DROP EXTERNAL TABLE dbo.MyExternalTable;
DROP EXTERNAL FILE FORMAT MyFileFormat;
  • Recreate them using only the options valid for your chosen format and connector:
CREATE EXTERNAL FILE FORMAT MyFileFormat
WITH (
    FORMAT_TYPE = PARQUET
);
  • Re-run the CREATE EXTERNAL TABLE statement referencing the corrected file format.

Step 4: Update SQL Server and PolyBase Components

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 / Windows 11 and verify the installed SQL Server 2025 build number.
  • Apply the latest Cumulative Update (CU) via SQL Server Setup > Maintenance Updates, since connector/format validation logic is frequently patched.
  • Restart the SQL Server PolyBase Engine and SQL Server PolyBase Data Movement services from services.msc after patching.

Alternative or Verification Steps

  • Run a simple SELECT TOP 10 * FROM dbo.MyExternalTable; query after recreating the table to confirm data retrieval works without triggering Error 5369.
  • If the issue persists, switch the FORMAT_TYPE to a more universally supported format (such as DELIMITEDTEXT with only FIELD_TERMINATOR and STRING_DELIMITER options) to isolate whether the problem is connector-specific or format-specific.

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

Troubleshooting Guide: SQL Server Error 5370 — Invalid Column Reference in View

Why This Error Happens

This error occurs when the underlying schema of a base table referenced by a view has changed (such as columns being added, dropped, renamed, or reordered) after the view was originally created, causing the view’s cached metadata to become stale. SQL Server stores column binding information at view creation time, and when this binding no longer matches the actual table structure, the engine cannot resolve the column references correctly. This is particularly common after schema migrations, ALTER TABLE operations, or database restores where views were not refreshed alongside structural changes.

Step-by-Step Resolution Guide

Step 1: Identify the Affected View and Base Table

  • Open SQL Server Management Studio (SSMS) and connect to the instance reporting the error.
  • Run the following query to capture the exact view name from the error message:
SELECT * FROM sys.views WHERE name = 'YourViewName';
  • Cross-reference the view definition using sp_helptext 'YourViewName' to identify which base table columns are referenced.

Step 2: Refresh the View Metadata Using sp_refreshview

  • Execute the built-in system stored procedure to force SQL Server to re-evaluate and re-bind the view’s column metadata:
EXEC sp_refreshview 'dbo.YourViewName';
  • If the database contains multiple views affected by the same base table change, loop through them using a cursor or run sp_refreshview individually for each.
  • Check for error output; if sp_refreshview itself fails, this indicates deeper schema mismatches requiring manual recreation (proceed to Step 3).

Step 3: Manually Drop and Recreate the View (If Refresh Fails)

  • Script out the original view definition using SSMS (Right-click view → Script View as → CREATE To).
  • Drop the broken view:
DROP VIEW dbo.YourViewName;
  • Recreate it with the corrected column list matching the current base table schema:
CREATE VIEW dbo.YourViewName AS
SELECT Column1, Column2, Column3
FROM dbo.BaseTable;
  • Ensure any SELECT * usage in the original view is replaced with explicit column names to prevent recurrence after future schema changes.

Step 4: Audit Related Dependent Objects

  • Use sys.sql_expression_dependencies to check if other views, stored procedures, or functions depend on the view you just fixed:
SELECT * FROM sys.sql_expression_dependencies 
WHERE referenced_entity_name = 'YourViewName';
  • Refresh any dependent objects using the same sp_refreshview or sp_refreshsqlmodule (for stored procedures/functions) to prevent cascading errors.

Alternative or Verification Steps

  • Verify the fix by querying the view directly (SELECT TOP 10 * FROM dbo.YourViewName;) and confirming no error 5370 is thrown and data returns as expected.
  • If sp_refreshview consistently fails due to encryption (WITH ENCRYPTION views) or schema binding conflicts, use SSMS Generate Scripts Wizard to export the full view definition, drop it, and recreate it manually with updated column references as outlined in Step 3.

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

Why This Error Happens

Error 5366 occurs when a T-SQL query attempts to use a ranking, aggregate, or analytic function (such as RANK(), LAG(), SUM(), or ROW_NUMBER()) without specifying a required OVER clause, or when a referenced WINDOW definition lacks an ORDER BY subclause. SQL Server 2025 strictly enforces that these window functions must define how rows are partitioned and ordered before computation, as the function has no implicit way to determine row sequence otherwise. This typically stems from a syntax oversight in application-generated queries, ORM-generated SQL, or scripts migrated from older database platforms that do not require this clause.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log or SSMS output pane for the exact query text referencing error 5366.
  • Use SELECT * FROM sys.dm_exec_requests combined with sys.dm_exec_sql_text(sql_handle) to capture the live query if it’s coming from an application connection.
  • Note the specific function name reported in the error message (e.g., RANK, DENSE_RANK, LAG).

Step 2: Add or Correct the OVER Clause

  • Modify the query to include an explicit OVER clause immediately after the function call.
  • Example fix: change SELECT RANK() FROM Sales; to SELECT RANK() OVER (ORDER BY SaleDate) FROM Sales;
  • If partitioning is required, include PARTITION BY inside the same clause, e.g., OVER (PARTITION BY RegionID ORDER BY SaleDate).

Step 3: Validate Named WINDOW Definitions

  • If the query uses the WINDOW clause (introduced for reusable window specs), ensure every named window includes an ORDER BY definition.
  • Example: WINDOW w AS (PARTITION BY CustomerID ORDER BY OrderDate) instead of WINDOW w AS (PARTITION BY CustomerID).
  • Re-run the query in SSMS or Azure Data Studio to confirm the parser no longer raises error 5366.

Step 4: Update Application or ORM-Generated SQL

  • If the query originates from an ORM (Entity Framework, Hibernate, etc.), check the generated SQL template for missing ORDER BY logic in ranking functions.
  • Patch the ORM mapping or raw SQL override to always inject an ORDER BY column when generating window functions.
  • Deploy the corrected query/application build to a test environment before pushing to production on Windows Server 2025.

Alternative or Verification Steps

  • Re-execute the corrected query directly in SQL Server Management Studio (SSMS) connected to the SQL Server 2025 instance and confirm no error 5366 is returned.
  • If the issue persists in a packaged application, enable SQL Server Profiler or Extended Events to trace the exact query being sent at runtime, then compare it against your corrected version to catch any caching of the old query plan.

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

Troubleshooting Guide: SQL Server Error 5367

Why This Error Happens

Error 5367 occurs when a T-SQL query attempts to redefine a named window (using the WINDOW clause or inline OVER() specification) that has already been declared earlier in the same query batch. This typically results from copy-paste errors in complex analytical queries, duplicate alias names across CTEs or subqueries, or a corrupted/outdated query plan cache retaining a stale window definition. In SQL Server 2025, this can also surface when application code dynamically generates window functions and inadvertently reuses a window name across unioned or nested query blocks.

Step-by-Step Resolution Guide

Step 1: Identify the Duplicate Window Definition

  • Open the query in SQL Server Management Studio (SSMS) 21 and locate all instances of the WINDOW keyword.
  • Search for repeated alias names (e.g., WINDOW w1 AS (...)) appearing more than once in the same scope.
  • Use Ctrl+F with “Find All” to scan the full batch, including nested subqueries and CTEs.

Step 2: Rename or Consolidate Conflicting Window Specifications

  • If two windows are functionally identical, remove the duplicate and reference the single named window in all OVER(w1) clauses.
  • If the windows are meant to be different, rename the second occurrence (e.g., w2) and update all corresponding OVER() references.
  • Ensure each WINDOW clause is scoped correctly to its own SELECT statement rather than leaking across UNIONed blocks.

Step 3: Clear the Plan Cache and Recompile

  • Run DBCC FREEPROCCACHE in a non-production environment to eliminate stale cached execution plans tied to the old window definition.
  • Alternatively, use sp_recompile 'YourProcedureName' for a targeted recompilation of the affected stored procedure.
  • Re-execute the corrected query to confirm the batch compiles without Error 5367.

Step 4: Audit Application-Generated SQL

  • If the query is built dynamically (e.g., via an ORM or string concatenation in C#/.NET), inspect the code path that appends WINDOW clauses.
  • Add validation logic to prevent duplicate alias names from being generated when loops or recursive functions construct the query.

Alternative or Verification Steps

  • Execute the revised query directly in SSMS or Azure Data Studio and confirm it returns results without raising Error 5367.
  • If the error persists, use SET SHOWPLAN_XML ON to inspect the query execution plan for any residual references to the conflicting window name before re-deploying the fix.

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

Troubleshooting Guide: SQL Server Error 5363 — “Function May Not Have ORDER BY in OVER or WINDOW Clause”

Why This Error Happens

This error occurs because certain functions, such as aggregate functions used in specific contexts (like %.*ls), do not support an ORDER BY clause within the OVER() or WINDOW clause by T-SQL design restrictions. This is typically a query syntax issue rather than a server configuration problem, often arising when a developer mistakenly applies ranking-function syntax (like ROW_NUMBER() or RANK()) rules to aggregate functions (like SUM() or AVG()) that do not support ordering within that specific clause. It can also surface after migrating queries from an older SQL Server version to SQL Server 2025 if new window function syntax restrictions have changed.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your Windows Server 2025 instance.
  • Check the Messages tab in the query results pane to locate the exact line number and function name referenced in the error.
  • Run the following diagnostic query to check recent query history if using Query Store:
  SELECT query_sql_text FROM sys.query_store_query_text WHERE query_sql_text LIKE '%OVER%ORDER BY%';

Step 2: Review the Function Syntax

  • Verify if the function you are using is a Ranking Function (supports ORDER BY) or an Aggregate Function (may not support ORDER BY in specific window contexts).
  • Remove the ORDER BY clause from inside the OVER() parentheses if the function is strictly aggregate-based and doesn’t require frame ordering.
  • Example of an incorrect query:
  SELECT SomeFunction(Column1) OVER (PARTITION BY Column2 ORDER BY Column3) FROM TableName;

Step 3: Modify the Query Logic

  • If ordering is logically required for your calculation, move the ORDER BY outside the window function and apply it to the outer SELECT statement instead.
  • Alternatively, restructure the query using a Common Table Expression (CTE) to pre-sort the data before applying the window function.
  • Save the corrected script to a local path, such as C:\Scripts\SQLFixes\WindowFunctionFix.sql, for version control.

Step 4: Update Database Compatibility Level

  • Sometimes this error appears due to compatibility level mismatches after an upgrade to SQL Server 2025.
  • Check the current compatibility level by running:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If necessary, update it to match the new engine’s requirements:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Verification: Execute the corrected query in a test environment to confirm the OVER clause compiles without throwing Error 5363, and check the execution plan to ensure the logic remains accurate.
  • Alternative: If the specific function absolutely requires an order for calculation purposes, consider refactoring the logic to use a subquery with ROW_NUMBER() first, then apply your aggregate function in the outer query layer.

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

Troubleshooting Guide: SQL Server Error 5364

Why This Error Happens

This error occurs when a T-SQL query uses a window function with an explicit frame specification (ROWS BETWEEN... or RANGE BETWEEN...) but omits the required ORDER BY clause within the OVER() clause. SQL Server 2025’s query parser cannot determine a logical sequence for the rows in the window partition without an ordering definition, making the frame boundaries (such as UNBOUNDED PRECEDING or CURRENT ROW) meaningless. This is a syntax/logic validation failure rather than a permissions or connectivity issue, and it typically surfaces after migrating legacy T-SQL code or during the development of new analytical queries involving SUM() OVER(), AVG() OVER(), or similar aggregate window functions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Locate the exact line number referenced in the Error 5364 message in the Messages pane.
  • Look specifically for the keywords ROWS BETWEEN or RANGE BETWEEN within an OVER() clause.

Step 2: Insert a Valid ORDER BY Clause

  • Modify the OVER() clause to include an ORDER BY statement immediately before the ROWS or RANGE keyword.
  • Example of broken syntax: SUM(SalesAmount) OVER (PARTITION BY Region ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
  • Corrected syntax: SUM(SalesAmount) OVER (PARTITION BY Region ORDER BY OrderDate ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
  • Ensure the column used in ORDER BY (e.g., OrderDate or a unique ID) logically defines the sequence of the dataset.

Step 3: Validate Data Types for Ordering

  • If using RANGE (as opposed to ROWS) with specific offsets, confirm that the ORDER BY column is a single column with a numeric or datetime data type.
  • Remove any composite (multi-column) ORDER BY statements if you are using RANGE BETWEEN with specific numeric boundaries, as SQL Server restricts RANGE frames to a single sort key.

Step 4: Recompile and Execute

  • Clear the execution plan cache for the specific query to ensure SQL Server 2025 validates the new syntax rather than pulling a corrupted cached plan: DBCC FREEPROCCACHE;
  • Run the corrected script via sqlcmd or SSMS to confirm the parser accepts the new window frame definition.

Alternative or Verification Steps

  • Verification: Execute the query and check that the result set populates the calculated window function column (e.g., running totals or moving averages) without throwing a red error banner in the SSMS output.
  • Alternative: If a logical order isn’t required for your business logic but the frame is necessary, use ORDER BY (SELECT NULL) as a placeholder to satisfy the syntax requirement while maintaining the original partition logic.

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

Troubleshooting Guide: SQL Server Error 5365 – “Cyclic Window References Are Not Permitted”

Why This Error Happens

This error occurs when a T-SQL query defines a named window (using the WINDOW clause) that directly or indirectly references itself through the OVER clause chain, creating a circular dependency that SQL Server’s query optimizer cannot resolve. It typically arises from a misconfigured window alias where Window B is defined in terms of Window A, and Window A is simultaneously defined in terms of Window B. This can also surface after upgrading to SQL Server 2025 if legacy queries relied on non-standard window-chaining syntax that was previously tolerated by the parser but is now strictly validated.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log or the client application’s exception stack trace to locate the exact query batch returning Error 5365.
  • Run the query in SQL Server Management Studio (SSMS) connected to your Windows Server 2025 instance to reproduce the error in isolation.
  • Look specifically for WINDOW clause definitions (e.g., WINDOW w AS (...)) in the query text.

Step 2: Audit the Window Definitions for Circular Logic

  • Manually trace each named window reference back to its base definition.
  • Example of a problematic pattern to search for:
  WINDOW 
      w1 AS (PARTITION BY col1 ORDER BY w2),
      w2 AS (PARTITION BY col1 ORDER BY w1)
  • Confirm no window alias refers back to itself, either directly or through a chain of two or more intermediate windows.

Step 3: Refactor the Query to Break the Cycle

  • Rewrite the query so each named window is based solely on physical columns or constants, not on other window aliases.
  • Example of a corrected definition:
  WINDOW 
      w1 AS (PARTITION BY col1 ORDER BY col2),
      w2 AS (PARTITION BY col1 ORDER BY col3)
  • If the logic truly requires sequential dependency, restructure using nested Common Table Expressions (CTEs) instead of chained window aliases.

Step 4: Update Database Compatibility Level (If Applicable)

  • If the query previously ran on an older engine, verify the database compatibility level is appropriate for SQL Server 2025 features:
  ALTER DATABASE [YourDatabaseName] SET COMPATIBILITY_LEVEL = 170;
  • Restart the SQL Server service via services.msc on Windows Server 2025 if compatibility changes require a service refresh.

Step 5: Clear Cached Execution Plans

  • Flush the plan cache to ensure SQL Server does not retry a stale, invalid plan tied to the old cyclic definition.
  DBCC FREEPROCCACHE;
  • Re-execute the corrected query to confirm a new, valid execution plan is generated.

Alternative or Verification Steps

  • Verification: Re-run the corrected query in SSMS and confirm it returns results without Error 5365; check SQL Server Profiler or Extended Events to ensure no deadlocked parser warnings appear during execution.
  • Alternative: If the application generating the query is a third-party ORM or reporting tool, update it to the latest version compatible with SQL Server 2025, as older query-generation logic may auto-construct cyclic window syntax that manual query rewriting cannot permanently fix at the source.

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

Troubleshooting Guide: SQL Server Error 5360 – “WITH Clause” Issue

Why This Error Happens

Error 5360 typically occurs when SQL Server encounters a malformed or unsupported WITH clause structure, often due to a Common Table Expression (CTE) being incorrectly referenced or nested within a query that doesn’t support it. This can also stem from missing semicolon terminators before the WITH statement, as SQL Server requires the preceding statement to be properly closed. Additionally, corrupted query execution plans or outdated compatibility levels in SQL Server 2025 can trigger this parsing failure.

Step-by-Step Resolution Guide

Step 1: Verify Statement Termination

  • Check that the statement immediately preceding your WITH clause ends with a semicolon (;).
  • Open SQL Server Management Studio (SSMS) and locate the query causing the error.
  • Add a semicolon before the WITH keyword if one is missing, as SQL Server 2025 enforces stricter parsing rules than previous versions.

Step 2: Validate CTE Syntax and Scope

  • Ensure the CTE is not referenced outside its valid scope (a CTE is only valid for the single statement that follows it).
  • Confirm there are no duplicate CTE names within the same query batch.
  • Rewrite nested CTEs as separate, sequential WITH statements if complexity is causing parser confusion.

Step 3: Check Database Compatibility Level

  • Navigate to SSMS, right-click the database, and select Properties > Options.
  • Verify the Compatibility Level is set to 170 (SQL Server 2025) under Windows Server 2025 or Windows 11 environments.
  • Run the following command to confirm via T-SQL:
  • SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';

Step 4: Clear and Rebuild the Query Execution Plan

  • Execute DBCC FREEPROCCACHE to clear potentially corrupted cached execution plans.
  • Restart the SQL Server service via services.msc or run NET STOP MSSQLSERVER followed by NET START MSSQLSERVER in an elevated Command Prompt.
  • Re-run the original query to confirm the WITH clause now parses correctly.

Alternative or Verification Steps

  • Run the query in a new SSMS query window with SET SHOWPLAN_TEXT ON to confirm the execution plan parses the WITH clause without throwing Error 5360.
  • If the error persists, isolate the CTE into a temporary table or table variable as a workaround while reviewing the original query logic for structural issues.

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

Troubleshooting Guide: SQL Server Error 5361 – Unsupported Combination of DATAFILETYPE Option and Format

Why This Error Happens

Error 5361 occurs when a BULK INSERT, BCP, or OPENROWSET(BULK...) operation specifies a DATAFILETYPE value (such as char, native, widechar, or widenative) that is incompatible with the format file version or format type being used. This commonly happens when a format file generated for native/binary data is paired with a character-based import, or when an XML-based format file (.xml) is used alongside a non-XML FORMATFILE directive. It can also surface after upgrading to SQL Server 2025 if legacy format files created in older BCP versions use deprecated syntax that no longer maps correctly to the new format file schema validation introduced in this release.

Step-by-Step Resolution Guide

Step 1: Verify the DATAFILETYPE Value Matches Your Source Data

  • Confirm whether your source file is character-based (ASCII) or native (binary) by inspecting it in a hex editor or text editor.
  • Match the DATAFILETYPE parameter accordingly: use char or widechar for text files, and native or widenative only for binary exports generated by BCP from SQL Server.
  • Example correction in T-SQL:
  BULK INSERT dbo.TargetTable
  FROM 'C:\ImportData\sourcefile.dat'
  WITH (DATAFILETYPE = 'char', FORMATFILE = 'C:\ImportData\format.fmt');

Step 2: Regenerate the Format File Using the Correct BCP Syntax

  • Delete any outdated .fmt or .xml format files tied to the import job.
  • Regenerate the format file using the bcp utility with explicit format type flags:
  bcp YourDatabase.dbo.YourTable format nul -c -x -f C:\ImportData\format.xml -S YourServer -T
  • Use -c for character format or -n for native format — ensure this matches the DATAFILETYPE used in Step 1.
  • Save the regenerated file in the same directory referenced by your BULK INSERT or OPENROWSET statement.

Step 3: Check Format File XML Schema Version Compatibility

  • Open the .xml format file in a text editor and confirm the <BCPFORMAT> root element references a schema version supported by SQL Server 2025.
  • If the file was migrated from SQL Server 2016/2019, regenerate it natively on the SQL Server 2025 instance rather than reusing a legacy copy.
  • Ensure the xsi:schemaLocation attribute is not pointing to an unreachable or outdated namespace URL.

Step 4: Validate File Permissions and Path Accessibility

  • Confirm the SQL Server service account has read access to both the format file and the data file locations.
  • On Windows Server 2025 / Windows 11, check folder permissions via:
  icacls "C:\ImportData" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)R"
  • Restart the SQL Server service if permission changes were applied:
  Restart-Service -Name 'MSSQLSERVER' -Force

Alternative or Verification Steps

  • Re-run the original BULK INSERT or BCP command after applying the fixes above; a successful row count return (with no Error 5361) confirms resolution.
  • As an alternative, bypass format file dependency entirely by using WITH (FORMAT = 'CSV', FIRSTROW = 2) for simple character-delimited imports, which avoids DATAFILETYPE/format file mismatches altogether.

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

Troubleshooting Guide: SQL Server Error 5362 — “Window ‘%.*ls’ is undefined”

Why This Error Happens

This error occurs when a T-SQL query references a named window (defined via the WINDOW clause or referenced in an OVER() clause) that either does not exist in the current query scope or was misspelled/mistyped during query construction. It is commonly triggered after upgrading to SQL Server 2025, which introduces stricter parsing and validation of the ANSI SQL WINDOW clause syntax used for named window specifications. Corrupted or partially migrated stored procedures, views, or ORM-generated queries that reference window definitions inconsistently can also cause this failure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query and Window Reference

  • Capture the exact query text from the error message, noting the window name shown in place of %.*ls.
  • Run the query manually in SQL Server Management Studio (SSMS) or Azure Data Studio connected to your SQL Server 2025 instance to reproduce the error.
  • Check the query for a WINDOW clause definition (e.g., WINDOW w AS (PARTITION BY ... ORDER BY ...)) and confirm the name used in OVER(w) matches exactly, including case sensitivity if the database collation is case-sensitive.

Step 2: Validate and Correct the Window Clause Syntax

  • Ensure the named window is declared before it is referenced, typically placed after the WHERE/GROUP BY clause and before ORDER BY.
  • Confirm there are no typos, extra whitespace, or mismatched brackets in the window name declaration versus its usage in OVER().
  • If the query was auto-generated by an ORM (e.g., Entity Framework, Hibernate), regenerate the query or manually inspect the generated SQL for malformed window definitions.
  • Example corrected syntax:
  SELECT SalesPerson, SUM(Amount) OVER w AS TotalSales
  FROM Sales
  WINDOW w AS (PARTITION BY SalesPerson ORDER BY SaleDate)

Step 3: Check for Corrupted or Outdated Stored Procedures/Views

  • Use sp_helptext 'ProcedureName' or OBJECT_DEFINITION(OBJECT_ID('ViewName')) to inspect the stored object’s definition for inconsistent window references.
  • Drop and recreate the stored procedure or view with corrected syntax using DROP PROCEDURE / CREATE PROCEDURE (or the ALTER equivalent).
  • If the object was migrated from an older SQL Server version, verify compatibility level using:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Update compatibility level if necessary with ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160; (adjust to the appropriate level for SQL Server 2025).

Step 4: Apply Latest Cumulative Updates

  • Navigate to Windows Server 2025 / Windows 11 Update settings or use SQL Server Setup to check for the latest Cumulative Update (CU) for SQL Server 2025, as parser-level bugs affecting named windows may be patched in later builds.
  • Download and install the CU from the official Microsoft Download Center.
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after installation.

Alternative or Verification Steps

  • Re-run the original failing query after corrections; confirm no Error 5362 appears and that result sets return as expected.
  • As an alternative, avoid named windows entirely by inlining the PARTITION BY/ORDER BY logic directly inside each OVER() clause, which bypasses the named window parser path completely.

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

Troubleshooting Guide: SQL Server Error 5357

Why This Error Happens

Error 5357 occurs when a BULK INSERT or OPENROWSET(BULK…) command specifies an option (such as FORMATFILE_DATA_SOURCE, CODEPAGE, or certain field/row terminators) that is incompatible with the combination of the declared data FORMAT (e.g., CSV) and the PARSER_VERSION being used (e.g., 2.0). This typically happens because PARSERVERSION 2.0 uses a stricter, high-performance parsing engine that does not support legacy options available in PARSERVERSION 1.0. It can also occur after an in-place upgrade to SQL Server 2025 if existing ETL scripts or SSIS packages were written against older parser defaults that are no longer backward compatible.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Syntax

  • Locate the specific T-SQL script or stored procedure referenced in the error log that triggered Error 5357.
  • Check the WITH clause of your BULK INSERT or OPENROWSET statement for the exact option named in the error message (the first %ls).
  • Cross-reference this option against the official Microsoft documentation for PARSER_VERSION 2.0 limitations.

Step 2: Adjust the PARSER_VERSION Argument

  • If you require the legacy option (e.g., specific code pages or complex format files), force the engine back to the original parser.
  • Modify your script to explicitly include: PARSER_VERSION = '1.0'
  • Example syntax:
  BULK INSERT dbo.YourTable
  FROM 'D:\Data\import.csv'
  WITH (
      FORMAT = 'CSV',
      PARSER_VERSION = '1.0',
      FIRSTROW = 2
  );

Step 3: Remove Incompatible Options for Format 2.0

  • If performance is a priority and you want to keep PARSER_VERSION = '2.0', remove the unsupported option from the WITH clause entirely.
  • Replace deprecated format file dependencies with inline specifications where possible, as PARSER_VERSION 2.0 often requires CSV or WIDECHAR formats without relying on older .fmt file structures for row terminators.

Step 4: Validate File Encoding and Format Alignment

  • Ensure the source file referenced in the path (e.g., D:\Data\import.csv) matches the FORMAT type declared in the query.
  • Open the source file in a hex editor or Notepad++ to verify the terminator characters match what is allowed by the specific parser version you settled on in Step 2 or 3.

Alternative or Verification Steps

  • Verify the Fix: Re-run the BULK INSERT command in SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance. A successful execution with a “rows affected” message confirms the syntax conflict is resolved.
  • Alternative Solution: If the specific option is mandatory for your business logic and is strictly unsupported in 2.0, bypass the native BULK INSERT limitations by importing the data via OPENROWSET combined with Azure Data Factory or the SQL Server Import/Export Wizard, which handles format abstraction automatically.

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

Troubleshooting Guide: Error 5358 – ERRORFILELOCATION Cannot Be Specified Without ERRORFILEDATA_SOURCE

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) command specifies the ERRORFILE or ERRORFILE_LOCATION parameter without pairing it with a required ERRORFILE_DATA_SOURCE argument. SQL Server 2025 enforces stricter syntax validation for bulk import operations, requiring that any error logging path be tied to an explicitly defined external data source object rather than a raw file path. Essentially, the engine does not know where (which credential/endpoint) to write the error file because the physical path lacks a corresponding logical data source reference.

Step-by-Step Resolution Guide

Step 1: Verify the Current Bulk Insert Syntax

  • Open SQL Server Management Studio (SSMS) 21 or Azure Data Studio connected to your SQL Server 2025 instance.
  • Locate the specific BULK INSERT or OPENROWSET statement throwing Error 5358.
  • Check if ERRORFILE = 'path' is present without an accompanying ERRORFILE_DATA_SOURCE clause.

Step 2: Create an External Data Source Object

  • Run the following T-SQL to define a data source pointing to your error log container or network share:
CREATE EXTERNAL DATA SOURCE MyErrorLogSource
WITH (
    TYPE = BLOB_STORAGE,
    LOCATION = 'https://yourstorageaccount.blob.core.windows.net/errorlogs'
);
  • If using a local file path instead of Azure Blob Storage, ensure you are referencing a valid Windows Server 2025 file share with a CREDENTIAL object attached if authentication is required.

Step 3: Update the Bulk Insert Command

  • Modify your original script to explicitly include the ERRORFILE_DATA_SOURCE argument alongside ERRORFILE_LOCATION:
BULK INSERT dbo.YourTable
FROM 'data/importfile.csv'
WITH (
    DATA_SOURCE = 'MyDataSource',
    ERRORFILE_LOCATION = 'errors/import_errors.log',
    ERRORFILE_DATA_SOURCE = 'MyErrorLogSource'
);
  • Ensure the SQL Server Service Account (e.g., NT Service\MSSQLSERVER) has write permissions to the target error log directory if using local storage.

Step 4: Validate File System Permissions

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ or your custom error log directory in Windows Server 2025.
  • Right-click the folder, select Properties > Security, and confirm the SQL Server service account has Write and Modify permissions.
  • Restart the SQL Server service via services.msc if permissions were just updated.

Alternative or Verification Steps

  • Re-run the BULK INSERT command and check the designated error file path to confirm the log file is generated successfully upon a forced bad-row import.
  • If the error persists, use sys.external_data_sources to query and confirm the data source object exists and is correctly linked: SELECT * FROM sys.external_data_sources;

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

Troubleshooting Guide: Error 5359 – ERRORFILEDATASOURCE Without ERRORFILE_LOCATION

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) statement specifies the ERRORFILE_DATA_SOURCE option without also specifying the required ERRORFILE_LOCATION option. SQL Server 2025 requires both parameters to be defined together because ERRORFILE_DATA_SOURCE only identifies where the external data source lives (such as Azure Blob Storage or an S3-compatible endpoint), while ERRORFILE_LOCATION defines the actual file path for logging rejected rows. Without a valid location path, SQL Server has no destination to write the error log file, causing the statement to fail validation before execution even begins.

Step-by-Step Resolution Guide

Step 1: Review the Bulk Operation Syntax

  • Open the T-SQL script or stored procedure that triggered Error 5359.
  • Locate the BULK INSERT or OPENROWSET command containing the ERRORFILE_DATA_SOURCE clause.
  • Confirm whether ERRORFILE_LOCATION is missing entirely or commented out.

Step 2: Add the ERRORFILE_LOCATION Parameter

  • Insert a valid ERRORFILE_LOCATION value immediately alongside ERRORFILE_DATA_SOURCE in the WITH clause.
  • Example corrected syntax:
  BULK INSERT dbo.TargetTable
  FROM 'data/import.csv'
  WITH (
      DATA_SOURCE = 'MyExternalDataSource',
      ERRORFILE = 'errors/import_errors.log',
      ERRORFILE_DATA_SOURCE = 'MyExternalDataSource',
      ERRORFILE_LOCATION = 'errors/import_errors.log'
  );
  • Ensure the path format matches the external data source type (container path for Azure Blob, bucket path for S3-compatible storage).

Step 3: Validate External Data Source Permissions

  • Confirm the SQL Server service account or managed identity has write access to the error file destination.
  • Run SELECT * FROM sys.external_data_sources; to verify the data source referenced in ERRORFILE_DATA_SOURCE is correctly configured and reachable.
  • Check Windows Firewall or network security group rules on Windows Server 2025 if the external storage is not on the local machine.

Step 4: Re-Execute the Statement

  • Run the corrected BULK INSERT or OPENROWSET statement in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Monitor the Messages pane for successful completion or any new error codes.

Alternative or Verification Steps

  • Verify success by checking that the specified ERRORFILE_LOCATION path now contains a .log and .log.error.txt file pair after running a bulk load with intentionally malformed test data.
  • If the error persists, bypass external data sources entirely by using a local UNC path (e.g., \\ServerName\SharedFolder\errors\) for both ERRORFILE and ERRORFILE_LOCATION to isolate whether the issue is permissions-related or syntax-related.

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

Troubleshooting Guide: Error 5354 – Parser Version Not Supported

Why This Error Happens

Error 5354 occurs when SQL Server 2025 encounters a query, script, or compatibility-level directive that references a parser version it does not recognize or support. This typically happens after an incomplete upgrade, a mismatch between the database compatibility level and the installed SQL Server engine version, or corrupted system metadata/plan cache entries referencing a deprecated parser. It can also surface when linked servers, replication scripts, or client tools (such as SSMS or sqlcmd) built for a different SQL Server version send T-SQL constructs that the current parser engine cannot interpret.

Step-by-Step Resolution Guide

Step 1: Verify SQL Server Build and Compatibility Level

  • Open SQL Server Management Studio (SSMS) and run SELECT @@VERSION; to confirm the exact build of SQL Server 2025 installed.
  • Check the database compatibility level with SELECT name, compatibility_level FROM sys.databases;
  • Ensure the compatibility level (e.g., 170 for SQL Server 2025) matches a level actually supported by your installed build — mismatches commonly trigger Error 5354.

Step 2: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and download the latest Cumulative Update for SQL Server 2025.
  • Run the installer as Administrator on Windows Server 2025 / Windows 11: Setup.exe /ACTION=Patch /IACCEPTSQLSERVERLICENSETERMS
  • Restart the SQL Server service via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER after installation completes.

Step 3: Clear Corrupted Plan Cache and Metadata

  • Run DBCC FREEPROCCACHE; to clear any cached execution plans tied to an unsupported parser version.
  • Run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out metadata corruption.
  • If corruption is found, restore from a known good backup rather than attempting manual repair.

Step 4: Update Client Tools and Drivers

  • Confirm SSMS, sqlcmd, and any ODBC/OLE DB drivers are updated to versions certified for SQL Server 2025.
  • Download the latest SSMS installer from Microsoft and reinstall if the current version predates SQL Server 2025 release.
  • Uninstall legacy native client providers that may be sending outdated parser directives in connection strings.

Step 5: Review and Correct T-SQL Scripts

  • Search recent scripts, stored procedures, or replication jobs for explicit parser version references (e.g., hints tied to deprecated syntax).
  • Remove or update any hardcoded compatibility hints such as USE PLAN or legacy OPTION clauses tied to older parser builds.
  • Re-deploy the corrected scripts and re-test the failing operation.

Alternative or Verification Steps

  • Run the originally failing query or job again and confirm Error 5354 no longer appears in the SQL Server Error Log (EXEC xp_readerrorlog 0, 1;).
  • If the issue persists, temporarily lower the database compatibility level to the last known stable version (ALTER DATABASE YourDB SET COMPATIBILITY_LEVEL = 160;) to isolate whether the parser conflict is version-specific, then escalate to Microsoft Support with the CU build number.

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

Troubleshooting Guide: SQL Server Error 5355

Why This Error Happens

Error 5355 occurs when SQL Server’s BULK INSERT or OPENROWSET(BULK…) operation receives an empty string (”) for a format-related option—such as FIELDTERMINATOR, ROWTERMINATOR, or FORMATFILE—when the specified data format (CSV, native, or JSON) and PARSERVERSION require a non-empty value. This is typically caused by dynamically generated SQL scripts, ETL tools, or ORM frameworks that pass blank variables instead of NULL or a valid delimiter. It can also surface after migrating scripts to PARSERVERSION=’2.0′, which enforces stricter validation on format options than the legacy parser.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement and Option

  • Check the SQL Server error log or SSMS output for the exact option name referenced in the error message (e.g., FIELDTERMINATOR, ROWTERMINATOR, FORMATFILEDATASOURCE).
  • Run the failing query manually in SSMS to isolate which parameter is being passed as an empty string.
  • Review any stored procedures or application code that constructs the BULK INSERT/OPENROWSET statement dynamically, especially string concatenation logic.

Step 2: Correct the Parameter Values

  • Replace empty string assignments with valid values or NULL. For example:
  BULK INSERT dbo.MyTable
  FROM 'C:\Data\import.csv'
  WITH (
      FORMAT = 'CSV',
      FIELDTERMINATOR = ',',   -- must not be ''
      ROWTERMINATOR = '\n',
      PARSER_VERSION = '2.0'
  );
  • If the application passes variables, ensure default values in config files (e.g., appsettings.json or .env) are not blank strings for delimiter/terminator fields.
  • For FORMATFILE-based imports, verify the path (e.g., C:\SQLData\FormatFiles\import.fmt) is correctly populated and not an empty path variable.

Step 3: Validate PARSER_VERSION Compatibility

  • If using PARSER_VERSION = ‘2.0’, confirm all required options for CSV format are explicitly set, since the 2.0 parser does not fall back to defaults like the legacy ‘1.0’ parser.
  • Temporarily test with PARSER_VERSION = ‘1.0’ to confirm whether the issue is version-specific.
  • Update documentation or templates used by developers to include mandatory non-empty values for all format-related clauses.

Step 4: Rebuild and Test the Import Script

  • Clear any cached execution plans related to the procedure using DBCC FREEPROCCACHE (only in non-production environments) to ensure the corrected script is used.
  • Re-run the BULK INSERT/OPENROWSET command from SSMS or via the Windows Server 2025 task scheduler job to confirm success.

Alternative or Verification Steps

  • Verify the fix by re-executing the import with SET STATISTICS IO ON; and confirming zero errors in sys.dm_exec_requests or the SQL error log.
  • If the error persists, bypass dynamic parameter injection entirely and hardcode a known-good FORMATFILE (.fmt) to confirm whether the issue lies in file-based configuration versus inline T-SQL options.

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

Troubleshooting Guide: SQL Server Error 5356 — “Specifying Database or Server Credential Is Not Supported for OPENROWSET”

Why This Error Happens

This error occurs because SQL Server 2025’s OPENROWSET function, when used in bulk data access mode (e.g., reading files via BULK or ad hoc queries), does not support inline specification of database-scoped or server-scoped credentials directly in the function call. Instead, SQL Server expects authentication to be handled through a properly configured Database Scoped Credential tied to an External Data Source, rather than passed as a parameter. This typically surfaces when legacy T-SQL scripts or migrated queries attempt to pass credentials in a syntax pattern no longer supported by the current Database Engine.

Step-by-Step Resolution Guide

Step 1: Verify Ad Hoc Distributed Queries Configuration

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following to confirm the feature is enabled:
  EXEC sp_configure 'show advanced options', 1;
  RECONFIGURE;
  EXEC sp_configure 'Ad Hoc Distributed Queries';
  • If the run_value is 0, enable it:
  EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
  RECONFIGURE;

Step 2: Create a Proper External Data Source and Credential

  • Instead of embedding credentials in the OPENROWSET call, create a dedicated Database Scoped Credential:
  CREATE DATABASE SCOPED CREDENTIAL MyAzureCredential
  WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
  SECRET = '<your_sas_token>';
  • Link this credential to an External Data Source:
  CREATE EXTERNAL DATA SOURCE MyExternalSource
  WITH (
      TYPE = BLOB_STORAGE,
      LOCATION = 'https://yourstorageaccount.blob.core.windows.net/container',
      CREDENTIAL = MyAzureCredential
  );

Step 3: Rewrite the OPENROWSET Query

  • Remove any inline CREDENTIAL= parameters from the OPENROWSET syntax.
  • Reference the External Data Source instead:
  SELECT *
  FROM OPENROWSET(
      BULK 'folder/file.csv',
      DATA_SOURCE = 'MyExternalSource',
      FORMAT = 'CSV'
  ) AS DataFile;

Step 4: Restart SQL Server Services

  • On Windows Server 2025 / Windows 11, open Services.msc.
  • Restart SQL Server (MSSQLSERVER) and SQL Server Agent to apply configuration changes.
  • Confirm the instance reloads advanced configuration flags without reverting to default.

Alternative or Verification Steps

  • Run a test query using the updated OPENROWSET syntax with DATA_SOURCE instead of direct credentials; confirm Error 5356 no longer appears in SSMS or the Windows Event Viewer (under Applications and Services Logs > MSSQLSERVER).
  • If the error persists, verify that the SQL Server service account has proper NTFS/network permissions to the external storage location, as misconfigured permissions can mimic the same error when credentials silently fail to resolve.

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

Troubleshooting Guide: Error 5351 – Partial File Cannot Be Provided Together with TABLESAMPLE Clause

Why This Error Happens

This error occurs when a query attempts to use the TABLESAMPLE clause against a table or view that involves partial file access, such as remote block storage, filestream partial reads, or a database that has files residing in a partially restored or partially online state. SQL Server 2025 blocks this combination because TABLESAMPLE relies on randomly accessing data pages across the entire physical structure of the table, which is architecturally incompatible with a partial or streamed file retrieval operation. This typically surfaces when working with database snapshots, Stretch Database remote tables, or files that are still undergoing piecemeal restore operations on Windows Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Affected Table and File State

  • Run sp_helpfile or query sys.master_files in SQL Server Management Studio (SSMS) to check the status of the filegroup associated with the table in question.
  • Look specifically for filegroups marked as RECOVERY_PENDING, OFFLINE, or RESTORING.
  • Confirm whether the table referenced in your query resides on a remote data source (e.g., Stretch Database or PolyBase external table), as these inherently use partial file streaming.

Step 2: Complete Any Pending Restore Operations

  • If the database is undergoing a piecemeal restore, finish the restore sequence before attempting sampled queries.
  • Use the following command to check restore status:
RESTORE DATABASE YourDB WITH RECOVERY;
  • Verify all secondary filegroups have been brought fully online using:
ALTER DATABASE YourDB MODIFY FILEGROUP [FG_Name] ONLINE;

Step 3: Remove TABLESAMPLE from Remote or Streamed Data Queries

  • Rewrite the query to eliminate the TABLESAMPLE clause when targeting Stretch Database tables, external tables, or FILESTREAM-partial columns.
  • Replace sampling logic with a TOP (N) ORDER BY NEWID() approach as a functional workaround:
SELECT TOP (1000) * FROM YourTable ORDER BY NEWID();
  • Ensure the query targets a fully local, fully online table if sampling behavior is required for statistical accuracy.

Step 4: Validate File Group and Storage Configuration on Windows Server 2025

  • Open Server Manager > File and Storage Services and confirm that the underlying disk volumes hosting the .mdf/.ndf files are not in a degraded or reconnecting state.
  • Check Windows Event Viewer under Windows Logs > System for any disk or Storage Spaces Direct (S2D) warnings that could cause SQL Server to treat files as “partial.”
  • Restart the SQL Server service via SQL Server Configuration Manager if storage reconnected after being flagged as partial.

Alternative or Verification Steps

  • To verify the fix, re-run the original query with TABLESAMPLE against the table once all filegroups report ONLINE status via sys.database_files; the error should no longer trigger.
  • If the issue persists, use the TOP (N) ORDER BY NEWID() workaround permanently for any object that must remain integrated with Stretch Database, PolyBase, or active piecemeal restore operations.

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

Troubleshooting Guide: SQL Server Error 5352 – Missing Update Assignment in Update With Action Hint

Why This Error Happens

This error typically occurs when the SQL Server query optimizer encounters an UPDATE statement containing an action hint (such as those used in batch mode or hint-driven execution plans) that fails to map a valid column assignment to the target table. This often results from corrupted query plan cache entries, mismatched schema metadata after a recent migration, or an incomplete update statement generated by an ORM or third-party replication tool. In Windows Server 2025 environments, this can also surface due to incompatible compatibility-level settings introduced after an in-place upgrade from SQL Server 2022.

Step-by-Step Resolution Guide

Step 1: Clear the Procedure Cache and Validate Query Plans

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run DBCC FREEPROCCACHE; to eliminate any corrupted cached execution plans.
  • Re-execute the failing UPDATE statement to confirm whether Error 5352 persists.

Step 2: Verify Database Compatibility Level

  • Navigate to Database Properties > Options > Compatibility Level.
  • Ensure the compatibility level matches SQL Server 2025 standards (160 or higher).
  • Run the following T-SQL command to confirm or set it manually:
  ALTER DATABASE [YourDatabase] SET COMPATIBILITY_LEVEL = 160;

Step 3: Inspect the UPDATE Statement for Missing Column Mapping

  • Review the exact UPDATE syntax being executed, especially where action hints (e.g., OPTION (USE HINT('ASSUME_JOIN_PREDICATE_DEPENDS_ON_FILTERS'))) are applied.
  • Confirm every column referenced in the SET clause explicitly matches a column in the target table schema.
  • Check for recent schema drift using:
  SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTable';

Step 4: Rebuild Affected Indexes and Statistics

  • Run sp_updatestats on the target database to refresh outdated statistics.
  • Rebuild indexes on the affected table using:
  ALTER INDEX ALL ON [YourTable] REBUILD;
  • Restart the SQL Server service via Services.msc on Windows Server 2025 to clear any lingering locks.

Alternative or Verification Steps

  • Re-run the original UPDATE statement with the action hint removed temporarily to confirm whether the hint itself is the trigger; if successful, isolate and rewrite the hint syntax.
  • Check the SQL Server Error Log (via SSMS > Management > SQL Server Logs) for Event ID 5352 recurrence after applying fixes to confirm full resolution.

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

Troubleshooting Guide: SQL Server Error 5353

Why This Error Happens

Error 5353 occurs when SQL Server 2025 attempts to parse structured data (such as JSON, CSV, or Parquet files used in OPENROWSET or BULK INSERT operations) using a parser version that does not match or support the file’s declared format specification. This typically happens after an in-place upgrade where legacy format files were created with an older parser version, or when a format file has been manually edited and now references a FORMAT_VERSION or DATA_SOURCE configuration incompatible with the installed SQL Server build. It can also occur if the Data Virtualization or PolyBase feature components are outdated relative to the core database engine.

Step-by-Step Resolution Guide

Step 1: Verify the Format File and Parser Compatibility

  • Open the format file (.fmt or .json schema) referenced in your BULK INSERT, OPENROWSET, or CREATE EXTERNAL FILE FORMAT statement.
  • Check the FORMAT_VERSION or DATA_COMPRESSION attribute at the top of the file and compare it against supported versions listed in sys.dm_exec_external_file_formats.
  • Run the following query to confirm supported parser versions:
  SELECT * FROM sys.dm_exec_external_file_formats;

Step 2: Update PolyBase and Data Virtualization Components

  • Launch SQL Server Installation Center from Start Menu on Windows Server 2025 / Windows 11.
  • Navigate to Maintenance > Edition Upgrade and ensure “PolyBase Query Service for External Data” is updated to the latest Cumulative Update (CU) matching SQL Server 2025 core engine version.
  • Restart the PolyBase services via PowerShell:
  Restart-Service MSSQLSERVER
  Restart-Service "SQL Server PolyBase Engine"
  Restart-Service "SQL Server PolyBase Data Movement"

Step 3: Recreate the External File Format with Explicit Parser Version

  • Drop the existing file format definition:
  DROP EXTERNAL FILE FORMAT MyFileFormat;
  • Recreate it while explicitly specifying a supported parser version:
  CREATE EXTERNAL FILE FORMAT MyFileFormat
  WITH (
      FORMAT_TYPE = PARQUET,
      DATA_COMPRESSION = 'org.apache.hadoop.io.compress.SnappyCodec'
  );
  • Ensure the FORMAT_TYPE matches the actual file structure (e.g., do not mix CSV parser syntax with JSON-formatted source files).

Step 4: Check for Corrupted or Mismatched Source Files

  • Inspect the source file’s header manually using Get-Content -TotalCount 5 "C:\Data\sourcefile.json" in PowerShell to confirm the structure matches the expected schema.
  • Re-export or regenerate the source file using a tool compatible with SQL Server 2025, discarding any legacy export utilities tied to SQL Server 2019/2022 schemas.

Alternative or Verification Steps

  • Re-run the original OPENROWSET or BULK INSERT query after applying the fixes; if successful, no error 5353 should appear in SQL Server Error Log or Event Viewer under Applications and Services Logs > MSSQLSERVER.
  • As an alternative, use the sp_describe_first_result_set stored procedure against your data source to validate schema parsing independently of the full import job before re-attempting the bulk operation.

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

Troubleshooting Guide: Error 5348 — ERRORFILESECRET Cannot Be Specified with ERRORFILEDATA_SOURCE

Why This Error Happens

This error occurs when a BULK INSERT, OPENROWSET(BULK...), or external bulk load command simultaneously defines both the ERRORFILE_SECRET and ERRORFILE_DATA_SOURCE options in the same syntax block. SQL Server 2025 treats these two parameters as mutually exclusive because they represent two different authentication/access methods for writing error logs—one uses a Database Scoped Credential/Secret tied to cloud storage (like Azure Blob or S3-compatible storage), while the other relies on a predefined EXTERNAL DATA SOURCE object. Since the engine cannot determine which access path takes priority for routing the error output, it immediately throws a syntax validation error (5348) rather than guessing the connection method.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Script

  • Locate the specific BULK INSERT or OPENROWSET statement in your T-SQL script or SSIS package that triggered Error 5348.
  • Look specifically for the WITH clause where error file options are being configured.
  • Example of the faulty syntax pattern to search for:
  WITH (
     ERRORFILE = 'errorlog.txt',
     ERRORFILE_DATA_SOURCE = 'MyExternalSource',
     ERRORFILE_SECRET = 'MySecretCredential'
  )

Step 2: Choose a Single Access Method

  • Decide whether you are authenticating via a Database Scoped Credential (Secret) or via a pre-configured External Data Source.
  • If you are using a Secret (common for direct cloud storage access via SAS tokens), remove the ERRORFILE_DATA_SOURCE parameter entirely from the command.
  • If you are using an External Data Source (common for pre-linked storage containers), remove the ERRORFILE_SECRET parameter entirely.

Step 3: Rewrite the Query Syntax

  • Modify the script to include only one of the two parameters alongside the standard ERRORFILE path.
  • Option A (Using Data Source):
  WITH (
     ERRORFILE = 'errorlog.txt',
     ERRORFILE_DATA_SOURCE = 'MyExternalSource'
  )
  • Option B (Using Secret):
  WITH (
     ERRORFILE = 'errorlog.txt',
     ERRORFILE_SECRET = 'MySecretCredential'
  )
  • Save the updated query file on your local drive (e.g., C:\Scripts\BulkLoad.sql).

Step 4: Validate Credential Permissions

  • If you chose the ERRORFILE_SECRET route, verify the associated credential exists in the database by running:
  SELECT * FROM sys.database_credentials;
  • Ensure the service account running the SQL Server 2025 instance on Windows Server 2025 has the necessary network permissions to write to the target error log path.

Step 5: Re-execute the Bulk Operation

  • Run the corrected script via SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Monitor the “Messages” tab to confirm the command completes without throwing Error 5348.

Alternative or Verification Steps

  • Verification: Check the target storage container or local Windows directory path specified in ERRORFILE to confirm a new log file (or .error.txt) is generated only if row rejections occur during the bulk load.
  • Alternative Fix: If removing one parameter breaks connectivity to your specific storage blob, create a new External Data Source that already has the Secret/Credential embedded within its definition, allowing you to reference only ERRORFILE_DATA_SOURCE without needing a separate inline secret.

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

Troubleshooting Guide: Error 5349 — ERRORFILE_SECRET Cannot Be Specified Without ERRORFILE Option

Why This Error Happens

This error occurs when a BACKUP or RESTORE statement in SQL Server 2025 includes the ERRORFILE_SECRET option without also specifying the required ERRORFILE parameter. The ERRORFILE_SECRET option is designed to supply a decryption key or token specifically tied to an error log file defined by ERRORFILE, so SQL Server’s parser rejects the command because it cannot validate an orphaned secret with no target file. This is typically caused by a manually written or auto-generated T-SQL script that was edited incorrectly, or a migration/automation tool that failed to pass both parameters together.

Step-by-Step Resolution Guide

Step 1: Locate the Offending T-SQL Script

  • Identify the specific BACKUP DATABASE or RESTORE DATABASE statement that triggered Error 5349 in SQL Server Management Studio (SSMS) or your deployment pipeline logs.
  • Check Windows Event Viewer under Applications and Services Logs > MSSQLSERVER for the exact timestamp and query context tied to Event ID 5349.

Step 2: Add the Missing ERRORFILE Parameter

  • Open the script in SSMS or your preferred editor and locate the WITH clause of the backup/restore command.
  • Add the ERRORFILE option pointing to a valid, writable path, for example:
  BACKUP DATABASE [YourDB]
  TO DISK = 'C:\SQLBackups\YourDB.bak'
  WITH ERRORFILE = 'C:\SQLBackups\Logs\YourDB_error.log',
       ERRORFILE_SECRET = 'YourSecretValue';
  • Ensure the folder (e.g., C:\SQLBackups\Logs\) exists on the Windows Server 2025 host and is accessible to the SQL Server service account.

Step 3: Verify File System Permissions

  • Confirm the SQL Server service account (visible in SQL Server Configuration Manager) has Write and Modify permissions on the ERRORFILE directory.
  • Use icacls "C:\SQLBackups\Logs" in an elevated PowerShell or Command Prompt window to audit and, if needed, grant permissions:
  icacls "C:\SQLBackups\Logs" /grant "NT SERVICE\MSSQLSERVER:(OI)(CI)M"

Step 4: Re-run the Script and Monitor Execution

  • Execute the corrected script in SSMS or via sqlcmd.
  • Watch the Messages tab or command-line output for successful completion without Error 5349 reappearing.

Alternative or Verification Steps

  • Run SELECT * FROM msdb.dbo.backupset ORDER BY backup_start_date DESC; to confirm the backup job completed and logged correctly.
  • If the error persists, remove ERRORFILE_SECRET entirely (if encryption isn’t strictly required) and re-test with only ERRORFILE specified to isolate whether the secret value itself is malformed.

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

Troubleshooting Guide: SQL Server Error 5350 — “CSV format supports only TABLESAMPLE PERCENT option”

Why This Error Happens

This error occurs when a query uses the TABLESAMPLE clause with the ROWS option while attempting to read from or export data to a CSV-formatted external data source, such as a CSV file accessed via PolyBase or an external table in SQL Server 2025. The CSV format’s underlying row-reading mechanism cannot guarantee a fixed physical row count sample because it processes data as a streamed, delimited text format rather than a fixed-page structure. As a result, SQL Server rejects any TABLESAMPLE syntax that isn’t expressed as a PERCENT value, since percentage-based sampling is the only method compatible with sequential text parsing.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Review the T-SQL query or stored procedure that triggered Error 5350.
  • Search specifically for the TABLESAMPLE keyword followed by a numeric row count (e.g., TABLESAMPLE (1000 ROWS)).
  • Confirm the target table is an external table pointing to a CSV data source by running:
  SELECT name, location, data_source_id FROM sys.external_tables;

Step 2: Rewrite the Query to Use PERCENT Syntax

  • Replace the ROWS clause with an equivalent PERCENT value.
  • Example fix:
  -- Incorrect (causes Error 5350)
  SELECT * FROM dbo.ExternalCsvTable TABLESAMPLE (500 ROWS);

  -- Corrected
  SELECT * FROM dbo.ExternalCsvTable TABLESAMPLE (10 PERCENT);
  • If an approximate row count is required, calculate the percentage manually based on estimated total rows in the source file (e.g., 500 rows out of ~5,000 total ≈ 10 PERCENT).

Step 3: Validate External Data Source and File Format Settings

  • Open SQL Server Management Studio (SSMS) and check the external file format definition:
  SELECT * FROM sys.external_file_formats WHERE format_type = 'DELIMITEDTEXT';
  • Ensure the FORMAT_TYPE is correctly set to DELIMITEDTEXT (the internal type used for CSV) and not mistakenly mapped to a row-addressable format like PARQUET or ORC.
  • If the table was meant to use a different format that supports ROWS sampling, recreate the external table using PARQUET instead of DELIMITEDTEXT.

Step 4: Apply Latest Cumulative Update

  • On Windows Server 2025, open Settings > Windows Update and check for pending SQL Server 2025 Cumulative Updates (CUs), as early builds may have stricter or buggy TABLESAMPLE validation logic.
  • Alternatively, download the latest CU directly from the Microsoft Update Catalog and install via:
  Start-Process -FilePath "SQLServer2025-KB*****-x64.exe" -ArgumentList "/quiet /IAcceptSQLServerLicenseTerms"

Alternative or Verification Steps

  • Re-run the corrected query in SSMS or Azure Data Studio and confirm it executes without raising Error 5350; verify the returned row count approximates your expected sample size.
  • As an alternative, if row-exact sampling is a hard requirement, first import the CSV data into a standard SQL Server table (via BULK INSERT or OPENROWSET) and then apply TABLESAMPLE (N ROWS) on the native table instead of the external CSV source.

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

Why This Error Happens

Error 5345 occurs when you define an inline schema using the WITH clause in an OPENROWSET(BULK...) statement and specify only OFFSET or only LENGTH for a column, instead of both. SQL Server 2025’s bulk schema parser requires both the starting byte position (OFFSET) and the exact byte count (LENGTH) to correctly map fixed-width or binary data into a column definition. Without both values, the engine cannot determine the field boundaries, so it rejects the query at parse/compile time rather than risk a silent data-misalignment during the read operation.

Step-by-Step Resolution Guide

Step 1: Review the Inline Schema Definition

  • Open the T-SQL script containing the OPENROWSET(BULK...) WITH (...) clause.
  • Locate every column definition that uses OFFSET or LENGTH as part of fixed-width field parsing.
  • Confirm whether both keywords are present for each column — partial definitions (only one of the two) are the direct trigger for Error 5345.

Step 2: Correct the Column Definitions

  • Edit the schema so each affected column explicitly declares both parameters, for example:
SELECT *
FROM OPENROWSET(
    BULK 'C:\Data\legacyfile.dat',
    SINGLE_BLOB
) AS x
CROSS APPLY OPENJSON(x.BulkColumn)
WITH (
    EmployeeID   INT      '$.id'      OFFSET 0  LENGTH 4,
    EmployeeName VARCHAR(50) '$.name' OFFSET 4  LENGTH 50
);
  • Ensure the OFFSET value reflects the correct starting byte in the source file/stream and the LENGTH value matches the exact byte-width expected for that field.
  • Save the corrected script in your project directory, e.g., C:\Scripts\SQL2025\FixOpenRowsetSchema.sql.

Step 3: Validate Syntax in SQL Server Management Studio (SSMS)

  • Open SSMS (connected to your SQL Server 2025 instance on Windows Server 2025 or Windows 11).
  • Paste the corrected query and use Query > Parse (Ctrl+F5) to confirm there are no syntax errors before executing.
  • Execute the query and confirm Error 5345 no longer appears in the Messages tab.

Step 4: Check for Legacy or Copy-Pasted Scripts

  • Search your solution or deployment scripts folder (e.g., C:\DeploymentScripts\) for other instances of OPENROWSET or OPENJSON with inline WITH schemas.
  • Apply the same OFFSET/LENGTH pairing fix to any additional occurrences to prevent the error from resurfacing in other stored procedures or ETL jobs.

Alternative or Verification Steps

  • Re-run the corrected query and confirm the result set returns properly parsed columns without truncation or misaligned data — this verifies both the fix and correct byte mapping.
  • As an alternative, if you don’t need fixed-width binary parsing, remove OFFSET/LENGTH entirely and let SQL Server infer schema automatically via OPENJSON default parsing (WITH clause using only JSON path, without byte offsets).

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

Troubleshooting Guide: Error 5346 — “DATAFILETYPE can only be used with schema inference or WITH clause”

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) statement specifies the DATAFILETYPE option without pairing it with a compatible schema discovery mechanism, such as automatic schema inference or an explicit WITH clause defining column formats. SQL Server 2025 enforces stricter parsing rules for bulk data operations, requiring the engine to know the structure of incoming data before it can correctly interpret the DATAFILETYPE flag. Without this context, the parser cannot validate how to map raw file bytes (native, char, widechar, etc.) to the destination schema, causing the statement to fail during compilation.

Step-by-Step Resolution Guide

Step 1: Review the Bulk Operation Syntax

  • Open the query or SSIS/T-SQL script that triggered the error and locate the BULK INSERT or OPENROWSET(BULK...) statement.
  • Confirm whether a WITH clause is present immediately after the file path declaration.
  • Check for a missing comma or malformed clause structure, as this often causes SQL Server to treat DATAFILETYPE as an orphaned parameter.

Step 2: Add an Explicit WITH Clause

  • Modify the statement to include a properly formatted WITH clause, for example:
  BULK INSERT dbo.TargetTable
  FROM 'C:\Data\import.dat'
  WITH (
      DATAFILETYPE = 'widechar',
      FIELDTERMINATOR = ',',
      ROWTERMINATOR = '\n'
  );
  • Ensure DATAFILETYPE values match the actual file encoding (char, native, widechar, or widenative).

Step 3: Enable Schema Inference (If Using OPENROWSET)

  • For OPENROWSET(BULK...) queries targeting Parquet, CSV, or JSON sources, confirm that FORMAT = 'CSV' or FORMAT = 'PARQUET' is declared alongside DATAFILETYPE.
  • If schema inference is required, add SINGLE_CLOB, SINGLE_BLOB, or a format file reference (FORMATFILE = 'C:\Data\format.xml') to give SQL Server enough metadata to resolve columns automatically.
  • Restart the SQL Server service via services.msc on Windows Server 2025 if cached execution plans continue referencing the old malformed syntax.

Step 4: Validate File Path and Permissions

  • Confirm the SQL Server service account has read access to the file path (e.g., C:\Data\import.dat) under Windows Server 2025 security policies.
  • Use icacls C:\Data /grant "NT SERVICE\MSSQLSERVER":(R) to grant read permissions if access is denied, which can sometimes surface as a misleading syntax error.

Alternative or Verification Steps

  • Run the corrected BULK INSERT statement in SQL Server Management Studio (SSMS) and confirm it executes without Error 5346, then check sys.dm_exec_requests to verify the session completed successfully.
  • If the error persists, test with a minimal reproduction script using a sample .csv file and a basic WITH (DATAFILETYPE = 'char') clause to isolate whether the issue is syntax-related or environment-related (file permissions, SQL Server patch level).

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

Troubleshooting Guide: Error 5347 — USETYPEDEFAULT Option Cannot Be Provided Without WITH Schema

Why This Error Happens

This error occurs when a BULK INSERT, OPENROWSET(BULK...), or format file operation specifies the USE_TYPE_DEFAULT option without also declaring the WITH clause schema definition required to interpret column data types. SQL Server 2025 requires an explicit schema context so it knows how to apply default values to columns containing missing or NULL data during a bulk load. Without this schema declaration, the engine cannot resolve how USE_TYPE_DEFAULT should map to target column types, causing the statement to fail at parse time.

Step-by-Step Resolution Guide

Step 1: Review the Bulk Operation Syntax

  • Open the T-SQL script or stored procedure that triggered the error (check SSMS query window or the calling application’s SQL log).
  • Confirm whether USE_TYPE_DEFAULT is being passed as a standalone option inside BULK INSERT, OPENROWSET, or a format file reference.
  • Identify the exact command, for example:
  BULK INSERT dbo.MyTable
  FROM 'C:\Data\import.csv'
  WITH (USE_TYPE_DEFAULT);

Step 2: Add the Required WITH Schema Clause

  • Modify the statement to include a full WITH clause that defines formatting and schema-related options alongside USE_TYPE_DEFAULT.
  • Example corrected syntax:
  BULK INSERT dbo.MyTable
  FROM 'C:\Data\import.csv'
  WITH (
      FORMATFILE = 'C:\Data\import.fmt',
      USE_TYPE_DEFAULT = 1,
      FIRSTROW = 2
  );
  • Ensure the format file path (C:\Data\import.fmt) exists and is accessible by the SQL Server service account on Windows Server 2025.

Step 3: Validate the Format File Schema

  • Open the .fmt file in a text editor and confirm it contains valid column definitions matching the target table structure.
  • If the format file is missing or corrupted, regenerate it using the bcp utility:
  bcp dbo.MyTable format nul -c -f C:\Data\import.fmt -S localhost -T
  • Re-run the BULK INSERT statement after confirming the format file is valid.

Step 4: Check Permissions on File and Database Objects

  • Verify the SQL Server service account (visible in Services.msc on Windows Server 2025 / Windows 11) has Read access to the source file and format file directories.
  • Confirm the executing login has ADMINISTER BULK OPERATIONS or bulkadmin server role permissions.
  • Restart the SQL Server (MSSQLSERVER) service if permission changes were made.

Alternative or Verification Steps

  • Re-execute the corrected BULK INSERT or OPENROWSET statement and confirm it completes without Error 5347 in SQL Server Management Studio’s Messages tab.
  • If the error persists, bypass USE_TYPE_DEFAULT entirely and instead define explicit column defaults in the target table schema using ALTER TABLE ... ADD CONSTRAINT DEFAULT.

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

Troubleshooting Guide: Error 5342 — ROWTERMINATOR/FIELDTERMINATOR Requires WITH Schema

Why This Error Happens

Error 5342 occurs when a BULK INSERT or OPENROWSET(BULK...) statement specifies formatting options like ROWTERMINATOR, FIELDTERMINATOR, or DELIMITER outside the required WITH (...) schema clause. SQL Server 2025 parses these options strictly as sub-arguments of the WITH clause, so placing them directly after the source file path or table name without the proper wrapper causes a syntax validation failure. This is almost always a query-authoring issue rather than a server configuration problem, often introduced when scripts are migrated from older T-SQL syntax or copy-pasted from incompatible templates.

Step-by-Step Resolution Guide

Step 1: Locate the Offending Statement

  • Check the SQL script or stored procedure referenced in the error output for BULK INSERT or OPENROWSET(BULK...) calls.
  • Look specifically for ROWTERMINATOR, FIELDTERMINATOR, or DELIMITER appearing without a preceding WITH keyword.
  • Example of broken syntax: BULK INSERT dbo.MyTable FROM 'C:\Data\file.csv' ROWTERMINATOR = '\n', FIELDTERMINATOR = ',';

Step 2: Wrap Options Inside the WITH Clause

  • Rewrite the statement so all formatting arguments are enclosed in parentheses after WITH.
  • Corrected syntax: BULK INSERT dbo.MyTable FROM 'C:\Data\file.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n');
  • For OPENROWSET, ensure the same pattern: SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', FORMATFILE = 'C:\Data\format.xml') AS DataSource;
  • Double-check comma placement between arguments inside the parentheses.

Step 3: Validate File Paths and Permissions

  • Confirm the file path (e.g., C:\Data\file.csv) is accessible from the SQL Server service account on Windows Server 2025.
  • Verify the SQL Server service account has at least Read permission on the folder via icacls C:\Data.
  • If using a UNC path, confirm the SQL Server service account has network share access and that the path is not blocked by Windows Defender Firewall.

Step 4: Re-run and Capture Execution Plan

  • Execute the corrected statement in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Enable SET STATISTICS XML ON beforehand to confirm the parser accepts the syntax without throwing Error 5342 again.
  • Review the Messages tab for any secondary warnings related to data type mismatches or format file issues.

Alternative or Verification Steps

  • Run SELECT TOP 10 * FROM dbo.MyTable; after the bulk load completes to confirm rows were inserted correctly with the expected delimiters applied.
  • If the error persists, try using a Format File (-f with bcp or FORMATFILE = in OPENROWSET) instead of inline terminators, as this isolates the issue to the WITH clause syntax rather than delimiter logic.

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

Why This Error Happens

Error 5343 occurs when a BULK INSERT or OPENROWSET statement specifies ROWTERMINATOR and FIELDTERMINATOR/DELIMITER arguments without providing either a WITH clause that defines column schema or enabling schema inference for the flat file. SQL Server 2025’s updated bulk-load parser requires explicit structural context to interpret delimiters correctly, since the engine no longer assumes a default schema for ambiguous file formats. This typically happens after migrating scripts from older SQL Server versions where delimiter-only syntax was still permitted without a formal schema definition.

Step-by-Step Resolution Guide

Step 1: Review the Current Bulk Import Statement

  • Open the T-SQL script or stored procedure that triggered Error 5343.
  • Check whether the OPENROWSET(BULK...) or BULK INSERT command includes a WITH (...) clause.
  • Confirm if FIELDTERMINATOR, ROWTERMINATOR, or DELIMITER are declared without accompanying column definitions.

Step 2: Add an Explicit WITH Clause or Format File

  • Modify the statement to include a WITH clause specifying column names, data types, and ordinal positions, for example:
    WITH (col1 INT, col2 VARCHAR(50))
  • Alternatively, generate a .fmt format file using bcp with the -f switch and reference it via FORMATFILE = 'C:\SQLData\import.fmt'.
  • Ensure the format file path is accessible to the SQL Server service account on Windows Server 2025.

Step 3: Enable Schema Inference for Flat Files

  • If using OPENROWSET with FORMAT = 'CSV', add PARSER_VERSION = '2.0' and set HEADER_ROW = TRUE to allow automatic schema inference.
  • Confirm the file encoding (UTF-8) and header row are properly formatted, since inference depends on consistent column headers.
  • Re-run the query after saving changes to validate that the terminators are now recognized within a defined schema context.

Step 4: Restart SQL Server Service and Clear Plan Cache

  • Open SQL Server Configuration Manager on Windows Server 2025 and restart the SQL Server (MSSQLSERVER) service.
  • Run DBCC FREEPROCCACHE; to remove any cached execution plans referencing the old syntax.
  • Re-execute the corrected bulk import script.

Alternative or Verification Steps

  • Run the corrected script in SQL Server Management Studio (SSMS) and confirm the import completes without Error 5343, then validate row counts in the target table.
  • If the error persists, test the import using a minimal sample CSV file with a manually defined WITH clause to isolate whether the issue is file-specific or schema-specific.

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

Troubleshooting Guide: Error 5344 – Duplicate Column Ordinal in WITH Schema Clause

Why This Error Happens

Error 5344 occurs when a query using the WITH <schema> clause (commonly in OPENROWSET, OPENJSON, or external table definitions) specifies the same column ordinal position more than once. This typically results from a manually authored or auto-generated schema definition where column indexes were copy-pasted incorrectly or a script loop failed to increment the ordinal counter. It can also surface after a schema migration where column mappings were merged or duplicated without validation.

Step-by-Step Resolution Guide

Step 1: Locate and Inspect the Offending Query

  • Open SQL Server Management Studio (SSMS) and pull the exact query from the SQL Server error log or Extended Events session.
  • Identify the WITH (...) clause and list every column definition along with its ordinal value (e.g., col1 VARCHAR(50) 1, col2 INT 2).
  • Pay close attention to queries using OPENJSON with an explicit schema, as these are the most common source of this error.

Step 2: Audit and Correct Column Ordinal Values

  • Manually count the ordinal numbers in sequence starting from 1 (or 0, depending on the data source convention).
  • Remove any duplicate ordinal references — each column must have a unique position value.
  • If the schema was generated programmatically (e.g., via PowerShell or a dynamic SQL script), inspect the generation script for a broken loop counter, such as a hardcoded index instead of an incrementing variable.

Step 3: Rebuild the Schema Definition Cleanly

  • Drop and recreate the WITH clause definition rather than patching it, to avoid missing a secondary duplicate.
  • For external tables, run:
  DROP EXTERNAL TABLE dbo.YourTableName;

then recreate it with corrected ordinals.

  • Save the corrected script and re-run it against a test database before deploying to production.

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

  • Run DBCC FREEPROCCACHE to eliminate any cached execution plan referencing the old, broken schema.
  • Restart the SQL Server service via services.msc on Windows Server 2025 only if the issue persists after cache clearing.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS and confirm it returns results without Error 5344 appearing in the Messages tab or the SQL Server error log.
  • As an alternative, use sp_describe_first_result_set against your query to validate the column ordinal sequence programmatically before deploying it in production code.

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

Troubleshooting Guide: SQL Server Error 5339 — CSV Format Restriction with BCP Data File Type

Why This Error Happens

Error 5339 occurs when the bcp utility or BULK INSERT command is executed with the FORMAT = 'CSV' option alongside an incompatible datafiletype value, such as native or widenative. SQL Server 2025 strictly enforces that the CSV format option is only valid when paired with char or widechar datafiletype arguments. This restriction exists because CSV formatting relies on character-based field and row terminators, which cannot be interpreted correctly against binary or native data representations.

Step-by-Step Resolution Guide

Step 1: Review the BCP Command Syntax

  • Open the command prompt or PowerShell session where the bcp command was issued.
  • Check the -c (char) or -w (widechar) flag is present; CSV format requires one of these.
  • Example of an invalid command: bcp dbo.Table out data.csv -n -t, -r\n -S server -T
  • Note that -n specifies native type, which is incompatible with CSV formatting.

Step 2: Correct the Datafiletype Argument

  • Replace -n (native) or -N (widenative) with -c (char) or -w (widechar) in your bcp command.
  • Corrected example: bcp dbo.Table out data.csv -c -t, -r\n -S server -T
  • If using BULK INSERT in T-SQL, verify the DATAFILETYPE parameter is set to 'char' or 'widechar' in the WITH clause.
  • Example: BULK INSERT dbo.Table FROM 'C:\Data\import.csv' WITH (FORMAT='CSV', DATAFILETYPE='char', FIRSTROW=2);

Step 3: Validate Format File Compatibility (If Used)

  • Navigate to the format file location, typically under C:\SQLData\FormatFiles\.
  • Open the .fmt or .xml format file in a text editor and confirm field types are set to SQLCHAR rather than binary types like SQLBINARY or SQLNUMERIC.
  • Regenerate the format file if necessary using: bcp dbo.Table format nul -c -x -f C:\SQLData\FormatFiles\table.xml -S server -T

Step 4: Re-run the Import/Export Operation

  • Execute the corrected bcp or BULK INSERT command.
  • Confirm the operation completes without raising Error 5339 in the SQL Server Error Log or command output.

Alternative or Verification Steps

  • Verify success by checking SQL Server Logs (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for absence of Error 5339 entries after re-running the command.
  • If CSV output is not strictly required, consider using -n (native format) for faster, binary-safe data transfer between SQL Server instances instead of forcing CSV compatibility.

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

Troubleshooting Guide: Error 5340 — WITH Schema Clause Conflict in SQL Server 2025

Why This Error Happens

This error occurs because the OPENROWSET(BULK...) or BULK INSERT statement is attempting to use a WITH <schema> clause simultaneously with a FORMATFILE parameter or a SINGLE_BLOB/SINGLE_CLOB/SINGLE_NCLOB option. SQL Server’s Bulk Import engine treats these as mutually exclusive instructions: the WITH schema clause manually defines column structure, while FORMATFILE reads structure from an external XML/non-XML file, and the SINGLE_* options treat the entire file as a single binary object with no structure at all. Since the engine cannot determine whether to parse the file using your manual schema, an external file definition, or treat it as raw unstructured data, it throws a syntax conflict rather than guessing your intent.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Syntax in Your Query

  • Open the T-SQL script containing the BULK INSERT or OPENROWSET(BULK...) command triggering Error 5340.
  • Look specifically for a WITH (...) clause that contains column definitions (e.g., col1 INT, col2 VARCHAR(50)) appearing alongside FORMATFILE = 'path' or SINGLE_BLOB.
  • Example of the broken pattern:
  SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', FORMATFILE = 'C:\Data\format.xml', SINGLE_CLOB) AS Data;

Step 2: Choose a Single Schema-Definition Method

  • Decide whether you want to use a Format File (recommended for complex, multi-column CSV/flat files) or Single Blob Mode (recommended for loading one entire file into one variable, like JSON or XML parsing).
  • If using FORMATFILE, remove the manual WITH (col1 INT...) schema clause entirely and let the .xml format file handle column mapping.
  • If using SINGLE_BLOB, SINGLE_CLOB, or SINGLE_NCLOB, remove the FORMATFILE parameter, as these options ignore column structure entirely and return the whole file as one row/one column.

Step 3: Rewrite the Query Using Correct Syntax

  • For structured data with a Format File (no manual schema needed):
  SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', FORMATFILE = 'C:\Data\format.xml') AS Data;
  • For raw/unstructured ingestion (e.g., loading a JSON file into a variable):
  SELECT BulkColumn FROM OPENROWSET(BULK 'C:\Data\file.json', SINGLE_CLOB) AS Data;
  • Save the script and re-run it against the Windows Server 2025 instance.

Step 4: Validate File Paths and Permissions

  • Ensure the SQL Server (MSSQLSERVER) service account has Read NTFS permissions on the folder housing the file and format file (e.g., C:\Data\).
  • Verify the path is accessible locally to the SQL instance; UNC paths require the service account to have domain-level read access if running on Windows Server 2025 in a clustered environment.

Alternative or Verification Steps

  • Verify the Fix: Re-execute the corrected query in SSMS (SQL Server Management Studio) connected to your SQL Server 2025 instance; a successful run will return the data preview grid without throwing the 5340 syntax error.
  • Alternative Approach: If you specifically need both a custom schema and raw byte access, use OPENROWSET(BULK...) with SINGLE_BLOB first to pull the data into a staging table, then use a secondary SELECT INTO statement with explicit CAST/CONVERT functions to apply your schema afterward.

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

Troubleshooting Guide: SQL Server Error 5341 — “WITH schema clause cannot be provided without FORMAT = ‘CSV’ option”

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) statement includes a WITH clause defining a schema (such as column definitions, field terminators, or format specifications) while the FORMAT parameter is either missing or set to a value other than 'CSV'. SQL Server 2025 enforces strict validation requiring that any schema-related options passed through the WITH clause are only applicable when the source file is explicitly declared as CSV-formatted. This typically results from a query written for a flat file import where the FORMAT = 'CSV' argument was omitted, mistyped, or left over from a different import method (such as native or fixed-width format).

Step-by-Step Resolution Guide

Step 1: Review the Bulk Import Query Syntax

  • Open the query in SSMS (SQL Server Management Studio) or Azure Data Studio that triggered Error 5341.
  • Locate the BULK INSERT or OPENROWSET(BULK...) statement and inspect the WITH clause.
  • Confirm whether a schema definition (e.g., FORMATFILE, FIELDTERMINATOR, or column list) is present without a corresponding FORMAT value.

Step 2: Add or Correct the FORMAT Parameter

  • Explicitly add FORMAT = 'CSV' inside the WITH clause of your statement.
  • Example corrected syntax:
  BULK INSERT dbo.TargetTable
  FROM 'C:\ImportData\sourcefile.csv'
  WITH (
      FORMAT = 'CSV',
      FIRSTROW = 2,
      FIELDTERMINATOR = ',',
      ROWTERMINATOR = '\n'
  );
  • Ensure the file path (e.g., C:\ImportData\) is accessible by the SQL Server service account on Windows Server 2025.

Step 3: Validate the Source File Format

  • Confirm the source file is genuinely comma-separated and saved with a .csv extension (not .txt or .dat with a renamed extension).
  • Open the file in Notepad or a text editor to verify delimiters match FIELDTERMINATOR settings in your query.
  • If using a FORMATFILE, ensure it was generated using the bcp utility with CSV-compatible settings.

Step 4: Check SQL Server Service Permissions

  • Navigate to SQL Server Configuration Manager on Windows Server 2025 / Windows 11.
  • Confirm the SQL Server service account has read access to the folder containing the import file.
  • Restart the SQL Server service if permission changes were made:
  Restart-Service -Name 'MSSQLSERVER'

Alternative or Verification Steps

  • Re-run the corrected BULK INSERT statement and confirm the import completes without Error 5341; check SQL Server Logs via SSMS (Management > SQL Server Logs) to verify no related warnings appear.
  • If the issue persists, use the OPENROWSET(BULK...) function with the SINGLE_CLOB option instead to manually parse the file content, bypassing the native CSV schema requirement entirely.

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

Troubleshooting Guide: SQL Server Error 5336 – Recursive Reference in EXCEPT Operator

Why This Error Happens

This error occurs because SQL Server’s recursive CTE (Common Table Expression) syntax explicitly disallows the recursive member from referencing itself on the right-hand side of an EXCEPT set operator. This is a query design limitation enforced by the SQL Server query parser/optimizer to prevent ambiguous or infinite recursion logic, not a server configuration or permissions issue. The error typically surfaces when developers attempt to use EXCEPT to filter out already-visited rows in hierarchical or graph-traversal queries (a common pattern for avoiding cycles), which is structurally incompatible with how SQL Server compiles recursive CTEs.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Structure

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the recursive CTE definition.
  • Look specifically for a pattern like SELECT ... FROM RecursiveCTE WHERE ... EXCEPT SELECT ... FROM RecursiveCTE in the anchor/recursive member.
  • Confirm the recursive table reference appears on the right side of the EXCEPT clause — this is the direct trigger for Error 5336.

Step 2: Rewrite the Recursive Member Using NOT EXISTS or LEFT JOIN

  • Replace the EXCEPT logic with a WHERE NOT EXISTS subquery to exclude duplicate or visited rows instead.
  • Example pattern: SELECT c.Col1, c.Col2 FROM Table c INNER JOIN RecursiveCTE r ON c.ParentID = r.ID WHERE NOT EXISTS (SELECT 1 FROM RecursiveCTE r2 WHERE r2.ID = c.ID).
  • Alternatively, use a LEFT JOIN back to the CTE and filter with WHERE r2.ID IS NULL to achieve the same de-duplication effect.
  • Save the modified query and re-parse it in SSMS using Ctrl+F5 to validate syntax before execution.

Step 3: Restructure Cycle Detection Logic (If Applicable)

  • If the EXCEPT was being used for cycle detection in a hierarchy traversal, add a tracking column (e.g., Path as varchar(max)) that concatenates visited node IDs.
  • Use WHERE CHARINDEX(CAST(c.ID AS varchar(10)), r.Path) = 0 in the recursive member instead of EXCEPT.
  • Ensure the MAXRECURSION hint is explicitly set (e.g., OPTION (MAXRECURSION 100)) to guard against unintended infinite loops once the EXCEPT logic is removed.

Step 4: Validate Against SQL Server 2025 Compatibility Level

  • Check the database compatibility level using SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';.
  • Ensure it is set to 170 (or the current SQL Server 2025 level) since older compatibility levels may handle CTE parsing differently and mask or alter this error.
  • Update if needed: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;.

Alternative or Verification Steps

  • Execute the rewritten query in a test environment and confirm it returns expected row counts without triggering Error 5336 or infinite recursion (verify via SET STATISTICS TIME ON to check execution doesn’t hang).
  • If rewriting is too complex for the existing logic, consider replacing the recursive CTE entirely with a WHILE loop and temporary table, which allows full control over row exclusion logic without the EXCEPT/recursion restriction.

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

Troubleshooting Guide: SQL Server Error 5337 — Constant Folding Error

Why This Error Happens

Error 5337 occurs when SQL Server’s query optimizer attempts to pre-compute (fold) a constant expression during the creation or alteration of a computed column, check constraint, or index, and that computation results in an arithmetic overflow, divide-by-zero, or invalid data type conversion. This typically happens because the underlying data type (e.g., INT, DECIMAL, or TINYINT) cannot hold the result of the expression being evaluated at compile time. It can also occur after upgrading to SQL Server 2025 if legacy schema definitions contain expressions that were valid under older compatibility levels but now trigger stricter constant-folding validation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Object Definition

  • Run the CREATE or ALTER TABLE statement again and capture the full error output, noting the %S_MSG object name (table, index, or constraint).
  • Use sp_helptext '<ObjectName>' or query sys.computed_columns to review the exact expression causing the failure.
  • Look specifically for implicit conversions between mismatched data types (e.g., INT divided by INT expected to return DECIMAL).

Step 2: Correct the Data Type or Expression

  • Explicitly cast constants and intermediate calculations using CAST() or CONVERT() to a larger or more precise data type.
  • Example fix: change (col1 / col2) to CAST(col1 AS DECIMAL(18,4)) / CAST(col2 AS DECIMAL(18,4)).
  • If the issue involves a hard-coded constant (e.g., 9999999999 in an INT column), adjust the constant to fit within the valid range of the target data type.

Step 3: Adjust Database Compatibility Level (If Applicable)

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 160; (or the appropriate prior level) temporarily to confirm if stricter SQL Server 2025 folding rules are the cause.
  • Test the CREATE/ALTER statement again under the older compatibility level to isolate whether this is a new optimizer behavior versus a genuine data overflow bug.

Step 4: Rebuild the Object with Corrected Logic

  • Drop the problematic constraint, computed column, or index using DROP CONSTRAINT or DROP INDEX.
  • Re-create the object using the corrected expression from Step 2.
  • Run DBCC CHECKCONSTRAINTS afterward to ensure no orphaned or invalid constraints remain on the table.

Alternative or Verification Steps

  • Verify the fix by re-running the original CREATE/ALTER script in a non-production environment and confirming Error 5337 no longer appears in SSMS or the SQL Server Error Log (Event Viewer > Applications and Services Logs > MSSQLSERVER).
  • If the error persists, isolate the exact failing sub-expression by testing each computed column or constraint individually using a SELECT statement with sample data to manually reproduce the overflow before re-applying it to the schema.

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

Troubleshooting Guide: SQL Server Error 5338 – “Format Option Cannot Be Specified Together with SINGLE_BLOB”

Why This Error Happens

This error occurs when a BULK INSERT or OPENROWSET(BULK...) statement incorrectly mixes incompatible options within the same command. Specifically, the SINGLE_BLOB option is designed to import data as a single, unstructured binary object, which conflicts directly with formatting options like FORMATFILE, FIELDTERMINATOR, or FORMAT = 'CSV' that expect structured, row-based data. Since the SQL Server parser cannot reconcile “treat this as one giant blob” with “parse this using specific column rules,” it rejects the query before execution.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Syntax in Your Query

  • Open the specific T-SQL script that triggered Error 5338 in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Look for a BULK INSERT or OPENROWSET statement that contains SINGLE_BLOB alongside FORMAT, FIELDTERMINATOR, ROWTERMINATOR, or FORMATFILE.
  • Example of the broken syntax: SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', SINGLE_BLOB, FORMAT='CSV') AS Data;

Step 2: Determine Your Actual Import Intent

  • Decide if you need to import the file as raw binary data (e.g., for a VARBINARY(MAX) column, such as loading an image or a PDF) or if you need to parse a structured text file (e.g., CSV).
  • If raw binary is needed, you must strip out all formatting arguments.
  • If structured parsing is needed, you must remove the SINGLE_BLOB keyword entirely.

Step 3: Correct the Query Syntax

  • For Raw Binary Imports: Remove the format arguments. The corrected syntax should look like: SELECT * FROM OPENROWSET(BULK 'C:\Data\file.csv', SINGLE_BLOB) AS Data;
  • For Structured CSV/Text Imports: Remove SINGLE_BLOB and define the structure explicitly. The corrected syntax should look like: BULK INSERT dbo.YourTable FROM 'C:\Data\file.csv' WITH (FORMAT = 'CSV', FIRSTROW = 2, FIELDTERMINATOR = ',');
  • Ensure the file path (e.g., C:\Data\file.csv) is accessible to the SQL Server service account on the Windows Server 2025 host.

Step 4: Validate File Permissions and Path Accessibility

  • Navigate to the folder containing the target data file in Windows Explorer or via PowerShell.
  • Right-click the folder, select Properties > Security, and ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has at least Read permissions.
  • Re-run the corrected query in a new query window to confirm the syntax error (5338) has cleared.

Alternative or Verification Steps

  • Verification: Execute the corrected query with SET STATISTICS IO ON; to confirm the data loads successfully without triggering a syntax error, and check the Messages tab in SSMS for a “rows affected” confirmation.
  • Alternative: If you need to combine binary data handling with metadata/row structure, use OPENROWSET(BULK...) to load the file as SINGLE_BLOB into a temporary variable first, and then process the formatting logic within the T-SQL query itself rather than within the BULK clause.

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

Troubleshooting Guide: Error 5333 in Microsoft SQL Server 2025

Why This Error Happens

Error 5333 occurs because the WHEN NOT MATCHED clause in a MERGE statement only has access to columns from the source table, not the target table, since no matching target row exists at that point in execution. This typically happens when a query incorrectly references a target-table column (or an alias scoped to the target) inside the INSERT logic of the WHEN NOT MATCHED branch. It can also arise from copy-pasted MERGE templates where column references were not updated to match the actual source/target schema.

Step-by-Step Resolution Guide

Step 1: Review the MERGE Statement Syntax

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the WHEN NOT MATCHED THEN INSERT clause.
  • Confirm that every column referenced inside this clause belongs only to the source table or source-derived expressions.
  • Check for stray references to the target table alias (commonly named T or Target) within this specific clause.

Step 2: Correct the Column References

  • Replace any target-table column reference with the corresponding source-table column.
  • If a target-only column (such as an identity or default-value column) is being referenced, remove it from the INSERT column list and let SQL Server apply the default/identity value automatically.
  • Example fix:
  WHEN NOT MATCHED THEN
      INSERT (ID, Name, CreatedDate)
      VALUES (S.ID, S.Name, GETDATE())
  • Ensure GETDATE(), constants, or source-derived expressions are used instead of target columns like T.CreatedDate.

Step 3: Validate Table Aliases and Scope

  • Double-check alias definitions in the USING and ON clauses to ensure the source and target aliases are not accidentally swapped.
  • Search the full MERGE block for alias typos (e.g., using T.ColumnName where S.ColumnName was intended).
  • Run the query in a test environment on a non-production database to confirm the identifier resolves correctly.

Step 4: Rebuild and Test the Query Incrementally

  • Temporarily simplify the MERGE statement by removing the WHEN NOT MATCHED clause and confirm the rest of the statement compiles.
  • Reintroduce the clause one column at a time to isolate the specific invalid identifier.
  • Save a corrected version of the script and re-run it against a staging table before deploying to production.

Alternative or Verification Steps

  • Verify the fix by executing the corrected MERGE statement against a test dataset and confirming no Error 5333 is raised, then check that new rows are inserted correctly into the target table.
  • As an alternative, if column logic is complex, consider pre-staging source data using a temporary table or CTE with only the required columns, simplifying the WHEN NOT MATCHED clause to straightforward VALUES (source_column1, source_column2, ...) references.

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

Troubleshooting Guide: MSSQL Error 5334 in MERGE Statement

Why This Error Happens

Error 5334 occurs when the WHEN NOT MATCHED BY SOURCE clause of a MERGE statement references a column or identifier that does not belong to the target table or the clause’s allowed scope. SQL Server 2025 strictly enforces that this specific clause can only bind to target table columns during an UPDATE or DELETE action, since there is no matching source row to reference. This typically results from a copy-paste error where a column intended for the WHEN MATCHED clause (which has access to both source and target) was mistakenly left in the NOT MATCHED BY SOURCE logic.

Step-by-Step Resolution Guide

Step 1: Isolate the Faulty Clause

  • Open SSMS or Azure Data Studio and locate the exact line number provided in the Error 5334 message.
  • Identify the specific WHEN NOT MATCHED BY SOURCE THEN UPDATE SET... or DELETE block causing the parse failure.
  • Copy the specific identifier mentioned in the error text (e.g., Source.ColumnName) to search for it within the script.

Step 2: Remove Source Table References

  • Check the SET logic within the WHEN NOT MATCHED BY SOURCE block.
  • Replace any reference to the source alias (e.g., Source.Status) with a static value, a function (like GETDATE()), or a target-table-only reference (e.g., Target.Status = 'Inactive').
  • Ensure you are not attempting to use source columns in a WHERE sub-clause attached to this specific WHEN condition.

Step 3: Validate Table Aliases

  • Confirm that the identifier isn’t simply a typo of a column that exists only in the target table.
  • Verify the alias used in the USING clause matches the alias referenced in your MATCHED block, ensuring no overlap into the NOT MATCHED BY SOURCE logic.
  • Run sp_help 'YourTargetTableName' to confirm the exact column names available in the scope.

Step 4: Recompile and Test

  • Save the corrected T-SQL script.
  • Execute the script using SQLCMD or directly within SSMS to check for the removal of Error 5334.
  • Look for secondary syntax errors that may have been masked by the initial binding failure.

Alternative or Verification Steps

  • Verification: Run the MERGE statement with SET NOCOUNT ON; and check the “Messages” tab in SSMS to confirm the query compiles and returns row-affected counts without throwing Error 5334.
  • Alternative: If complex logic is required for unmatched source rows, consider splitting the logic into a separate UPDATE...FROM statement executed immediately after the MERGE to avoid clause-scope restrictions entirely.

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

Troubleshooting Guide: SQL Server Error 5335 — “The data type %ls cannot be used as an operand to the UNION”

Why This Error Happens

This error occurs when a UNION or UNION ALL statement attempts to combine columns that include incompatible or unsupported large object (LOB) data types, such as text, ntext, image, xml, geography, geometry, or CLR user-defined types, without proper conversion. SQL Server’s query engine cannot implicitly compare or merge these data types across result sets because they lack a defined sort or equality operator required for the DISTINCT-style processing that UNION performs internally. This typically surfaces after a schema change, a migration from an older SQL Server version, or when a query was written against columns that were later altered to deprecated or large-object types.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Data Type

  • Run the failing query in SQL Server Management Studio (SSMS) and note the exact error message, which specifies the problematic data type (e.g., text, xml, geography).
  • Use sp_help 'YourTableName' or query sys.columns joined with sys.types to confirm which column(s) in your SELECT statements use the flagged type.
  • Check both sides of the UNION to ensure column order and types align correctly.

Step 2: Explicitly Cast or Convert the Column

  • Modify the query to cast the problematic column to a comparable type, such as NVARCHAR(MAX) for text/ntext/xml, or VARBINARY(MAX) for image.
  • Example fix:
SELECT CAST(MyXmlColumn AS NVARCHAR(MAX)) FROM TableA
UNION
SELECT CAST(MyXmlColumn AS NVARCHAR(MAX)) FROM TableB;
  • For spatial types (geography/geometry), convert using .STAsText() or .ToString() before applying UNION.

Step 3: Replace UNION with UNION ALL Where Duplicates Are Acceptable

  • If the deduplication behavior of UNION is not required, switch to UNION ALL, which does not attempt to sort/compare rows and may bypass the type restriction for certain scenarios.
  • Validate this doesn’t introduce duplicate records that break downstream reporting or application logic.

Step 4: Update Application or ORM-Generated Queries

  • If the query is auto-generated by an ORM (Entity Framework, Dapper, etc.), check the model/entity definitions for columns mapped to deprecated types.
  • Update the data access layer to explicitly handle type conversion before the UNION operation is constructed.

Step 5: Audit Table Schema for Deprecated Types

  • On Windows Server 2025 / Windows 11 hosts running SQL Server 2025, open SSMS and run sys.dm_db_uncontained_entities or a custom script to flag all text, ntext, and image columns still in use, since these are deprecated and should be migrated to varchar(max), nvarchar(max), or varbinary(max) long-term.

Alternative or Verification Steps

  • Re-run the original query after applying the CAST/CONVERT fix and confirm Error 5335 no longer appears in the SSMS results pane or the SQL Server Error Log (Application and Services Logs > SQL Server in Windows Event Viewer).
  • If the error persists, isolate each SELECT statement individually (without the UNION) to confirm each runs cleanly, then incrementally reintroduce the UNION to pinpoint exactly which column pairing still triggers the type mismatch.

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

Troubleshooting Guide: Error 5330 – Full-Text Predicates Cannot Appear in the OUTPUT Clause

Why This Error Happens

This error occurs because SQL Server does not support using full-text search predicates such as CONTAINS, FREETEXT, CONTAINSTABLE, or FREETEXTTABLE within the OUTPUT clause of an INSERT, UPDATE, DELETE, or MERGE statement. The OUTPUT clause is designed to capture row-level data changes directly, and it cannot evaluate full-text index predicates because those operations rely on the asynchronous Full-Text Engine rather than the core relational engine. This is a syntax/architecture limitation rather than a configuration or permissions issue, meaning the query itself must be restructured to avoid the conflict.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) connected to your SQL Server 2025 instance.
  • Locate the exact INSERT, UPDATE, DELETE, or MERGE statement that triggered Error 5330.
  • Check the OUTPUT clause specifically for any full-text functions like CONTAINS(), FREETEXT(), CONTAINSTABLE(), or FREETEXTTABLE().

Step 2: Refactor the Query to Separate Full-Text Logic

  • Remove the full-text predicate from the OUTPUT clause entirely.
  • Move the full-text filtering logic into the WHERE clause of the main DML statement instead, since WHERE fully supports full-text predicates.
  • Example corrected syntax:
UPDATE Documents
SET Status = 'Reviewed'
OUTPUT inserted.DocID, inserted.Title
WHERE CONTAINS(Content, 'SQLServer2025');
  • If you need full-text scoring data (like RANK) in your results, run a separate SELECT query using CONTAINSTABLE before or after the DML operation rather than trying to merge it into OUTPUT.

Step 3: Use a Staging Table or CTE Workaround

  • If you require the output data to be joined with full-text search results, first capture the OUTPUT results into a temporary table or table variable (without the full-text predicate).
  • Example:
DECLARE @Output TABLE (ID INT, Title NVARCHAR(255));

INSERT INTO Documents (Title, Content)
OUTPUT inserted.ID, inserted.Title INTO @Output
VALUES ('New Doc', 'Sample content');
  • Then, run a secondary SELECT statement joining @Output with your full-text catalog table using CONTAINS or FREETEXT in the WHERE clause.

Step 4: Validate the Full-Text Catalog Configuration

  • Navigate to Object Explorer > Databases > [YourDB] > Storage > Full Text Catalogs in SSMS to confirm the catalog is populated and the population status is not stalled.
  • Run the following to check catalog health:
SELECT * FROM sys.fulltext_catalogs;
SELECT * FROM sys.dm_fts_index_population;
  • Ensure the Full-Text Filter Daemon Launcher service (MSSQLFDLauncher) is running via services.msc on Windows Server 2025.

Alternative or Verification Steps

  • Re-run the modified query (with full-text predicates moved to the WHERE clause) and confirm Error 5330 no longer appears in the SQL Server Error Log (SSMS > Management > SQL Server Logs).
  • As an alternative, use SELECT with CONTAINSTABLE/FREETEXTTABLE joined against your target table post-DML to retrieve ranked full-text match data without violating OUTPUT clause restrictions.

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

Troubleshooting Guide: SQL Server Error 5331

Why This Error Happens

Error 5331 occurs when a Transact-SQL query attempts to use a full-text predicate—such as CONTAINS or FREETEXT—inside a clause that references a nested INSERT statement (typically via INSERT ... EXEC or a derived table containing an OUTPUT INTO with an insert). SQL Server’s query optimizer cannot bind full-text index predicates to a rowset that is generated dynamically by a nested data modification statement because the full-text catalog requires a static, pre-existing base table to resolve the search. This is a structural limitation in the query plan compiler rather than a corruption or permissions issue, meaning the query itself must be rewritten to separate the insert logic from the full-text search logic.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Structure

  • Open SQL Server Management Studio (SSMS) and locate the query referenced in the SQL Server error log or Event Viewer (Event ID 5331).
  • Look specifically for a FROM clause containing INSERT INTO ... EXEC or a Common Table Expression (CTE) that wraps an INSERT while simultaneously joining to a full-text indexed column using CONTAINS() or FREETEXT().
  • Confirm the table involved has an active full-text index by running sp_help_fulltext_tables.

Step 2: Decouple the Insert Logic from the Full-Text Search

  • Modify the query to use a temporary table or table variable to stage the results of the INSERT operation first.
  • Example fix: Change INSERT INTO #Temp EXEC dbo.MyProc followed immediately by a search, to a two-step batch:
  • INSERT INTO #Temp EXEC dbo.MyProc;
  • SELECT * FROM #Temp WHERE CONTAINS(ColumnName, 'SearchTerm');
  • Ensure the full-text predicate only runs in the second, separate batch step once the temporary data is fully materialized.

Step 3: Update Statistics and Full-Text Catalogs

  • Navigate to Object Explorer > Databases > [Your DB] > Storage > Full Text Catalogs in SSMS.
  • Right-click the specific catalog and select Rebuild to ensure the index fragmentation isn’t contributing to the parser confusion.
  • Run ALTER FULLTEXT INDEX ON [TableName] START FULL POPULATION; via a new query window to force a refresh.

Step 4: Validate Compatibility Level Settings

  • Right-click the Database in SSMS, go to Properties > Options.
  • Verify the Compatibility Level is set appropriately for SQL Server 2025 (160) to ensure the legacy query optimizer isn’t attempting to parse the nested insert incorrectly.
  • Apply the change and restart the specific query session to clear the cached execution plan.

Alternative or Verification Steps

  • Verification: Execute the modified two-step batch query in a test environment; if it returns results without throwing Error 5331, the fix is successful.
  • Alternative: If rewriting the query is not immediately feasible, wrap the nested insert logic inside a Stored Procedure first, then call the full-text search predicate against the output table of that procedure in a completely separate, subsequent batch.

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

Troubleshooting Guide: SQL Server Error 5332 – CLR TVF ORDER Hint Violation

Why This Error Happens

This error occurs when a CLR table-valued function (TVF) is decorated with an ORDER hint in its SqlFunctionAttribute, but the actual data returned by the IEnumerable/IEnumerator implementation does not physically match that declared sort order. SQL Server 2025’s query optimizer trusts the ORDER hint at compile time to skip an actual sort operation in the execution plan, so when the runtime data stream violates that promise, the engine throws Error 5332 to prevent returning incorrectly ordered results to the client. This is almost always a developer/code-contract mismatch rather than a server configuration or permissions issue, and it is commonly triggered after a .NET assembly update, a data source change, or a collation change on the underlying columns being sorted.

Step-by-Step Resolution Guide

Step 1: Identify the Offending CLR TVF and Its Declared Order

  • Query sys.assembly_modules to locate the function: SELECT * FROM sys.assembly_modules WHERE assembly_class LIKE '%YourClassName%';
  • Open the CLR project source and locate the [SqlFunction(FillRowMethodName = "...", TableDefinition = "...")] attribute.
  • Check the SqlMethodAttribute or OrderedTableFunctionAttribute for the exact ORDER(...) column list and sort direction (ASC/DESC) declared in code.

Step 2: Audit the Underlying Data Source for Actual Sort Order

  • Trace the C# IEnumerable<SqlDataRecord> or IEnumerator implementation feeding the TVF.
  • Verify whether the data source (external API call, file read, cached collection, or LINQ query) still guarantees the same sort order it did previously — a common cause is a missing .OrderBy() clause after a LINQ provider upgrade.
  • If the data comes from an external file or API, confirm the upstream system has not changed its native sort behavior following a Windows Server 2025 update to locale/collation libraries (ICU changes affect default string sorting).

Step 3: Correct the Mismatch (Code Fix)

  • Either add/fix an explicit in-memory sort in the .NET code so the output truly matches the declared ORDER hint: data = data.OrderBy(x => x.ColumnName);
  • Or, if the data order is intentionally different now, update the ORDER hint in the SqlFunction attribute to reflect the real output order, then recompile the assembly (.dll).
  • Redeploy the updated assembly using ALTER ASSEMBLY YourAssemblyName FROM 'C:\Path\To\YourAssembly.dll' WITH PERMISSION_SET = SAFE;

Step 4: Rebuild and Refresh the CLR Function Metadata

  • Drop and recreate the function definition if ALTER ASSEMBLY does not refresh cached metadata: DROP FUNCTION dbo.YourCLRFunction; then re-run the CREATE FUNCTION ... ORDER(...) script matching the corrected hint.
  • Clear the procedure cache for the affected database to force plan recompilation: DBCC FREEPROCCACHE; (use with caution in production — prefer sp_recompile on specific objects when possible).

Step 5: Validate Collation and Culture Settings on the Host

  • On Windows Server 2025, confirm the server’s regional/locale settings in Control Panel > Region or via PowerShell Get-WinSystemLocale haven’t changed, as .NET string comparisons (StringComparer.Ordinal vs StringComparer.CurrentCulture) can silently alter sort behavior across OS patches.
  • Ensure the CLR assembly explicitly specifies StringComparer.Ordinal or an invariant culture comparer if cross-environment consistency is required.

Alternative or Verification Steps

  • Run the TVF query directly with OPTION (RECOMPILE) and inspect the actual execution plan in SSMS to confirm no “Sort” warning or 5332 exception appears, validating the hint now matches the stream.
  • If reworking the CLR code isn’t immediately feasible, a temporary workaround is to remove the ORDER hint entirely from the function definition — this forces SQL Server to add its own Sort operator in the plan (slight performance cost) but eliminates the error until a permanent code fix is deployed.

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

Why This Error Happens

This error occurs when the OPENROWSET or external table definition specifies an ORDER hint on a column whose data type is incompatible with ordered reads, such as nvarchar(max), varbinary(max), XML, or SQL_VARIANT. SQL Server 2025’s PolyBase/External Data engine requires ORDER hints to be applied only to fixed-length, comparable data types so it can correctly predicate pushdown and optimize partition elimination. This typically surfaces when importing or querying Parquet/CSV external data sources where the schema mapping was auto-generated incorrectly or the T-SQL script was copied from a template without adjusting column types.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column

  • Open the error detail and note the column name and data source referenced in the message ('%.*ls' placeholders will show actual names in the real error).
  • Run sp_help 'dbo.YourExternalTable' or check sys.external_tables / sys.external_columns in SQL Server Management Studio (SSMS) to confirm the data type of that column.
  • Cross-reference this with your CREATE EXTERNAL TABLE or OPENROWSET(...) WITH (ORDER (...)) statement to locate the exact ORDER clause causing the conflict.

Step 2: Modify or Remove the Invalid ORDER Hint

  • Edit the T-SQL script and remove the ORDER hint from any column with MAX types, XML, SQL_VARIANT, or CLR user-defined types.
  • Replace the ORDER hint target with a fixed-length, orderable column (e.g., INT, BIGINT, DATETIME2, or VARCHAR(n) where n is a defined length).
  • Example fix:
  WITH (
      DATA_SOURCE = MyDataSource,
      FILE_FORMAT = MyFileFormat,
      ORDER (OrderDate ASC) -- changed from DescriptionColumn (nvarchar(max))
  )

Step 3: Recreate the External Table or Data Source Mapping

  • Drop and recreate the external table definition in SSMS or Azure Data Studio to force a schema refresh:
  DROP EXTERNAL TABLE dbo.YourExternalTable;
  CREATE EXTERNAL TABLE dbo.YourExternalTable (...) WITH (...);
  • On Windows Server 2025, ensure the PolyBase service (MSSQLSERVER_POLYBASE) and the SQL Server Launchpad service are both running via services.msc or Get-Service *PolyBase* in PowerShell, since stale cached metadata can also trigger phantom type mismatches.

Step 4: Validate File Format Schema Consistency

  • If the data source is a Parquet or CSV file, confirm the actual underlying file schema matches what’s declared in CREATE EXTERNAL FILE FORMAT.
  • Use SELECT TOP 10 * FROM OPENROWSET(BULK ...) AS t without the ORDER hint first to confirm the column types resolve correctly before re-adding the hint.

Alternative or Verification Steps

  • Re-run the original query or data load job; if Error 5327 no longer appears and results return successfully, the fix is confirmed.
  • As a fallback, remove ORDER hints entirely from the external table definition (they are an optimization, not a requirement) and rely on standard query optimization — this bypasses the type restriction entirely while you redesign the schema.

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

Troubleshooting Guide: SQL Server Error 5328 — Identity Column Conflict in Nested INSERT

Why This Error Happens

This error occurs because SQL Server 2025 does not allow an explicit value to be inserted into an IDENTITY column when the INSERT statement’s data source involves a nested INSERT (such as INSERT ... EXEC or an INSERT used inside an OUTPUT INTO chain combined with FROM). The engine cannot simultaneously honor SET IDENTITY_INSERT ON and resolve the nested INSERT’s result set because the internal query processor treats the nested operation as a nondeterministic source for identity enforcement. This typically surfaces in migration scripts, ETL jobs, or stored procedures where a developer is copying data between tables and nests nested data-modification statements inside a single INSERT INTO ... SELECT/FROM construct.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio connected to your instance.
  • Use SELECT * FROM sys.messages WHERE message_id = 5328; to confirm the exact error text and the table/column referenced.
  • Check the job history or application logs (Event Viewer → Applications and Services Logs > MSSQLSERVER) to locate the exact batch that triggered the error.

Step 2: Refactor the Nested INSERT Logic

  • Rewrite the query to eliminate the nested INSERT inside the FROM clause — stage the nested result into a temporary table or table variable first.
  • Example pattern:
  SELECT * INTO #StagingTable FROM (EXEC dbo.YourNestedProc);
  INSERT INTO TargetTable (ID, Col1, Col2)
  SELECT ID, Col1, Col2 FROM #StagingTable;
  • Ensure the staging step completes and commits before the final INSERT runs.

Step 3: Enable IDENTITY_INSERT Correctly

  • Wrap only the final INSERT (not the nested/staging operation) with:
  SET IDENTITY_INSERT TargetTable ON;
  INSERT INTO TargetTable (ID, Col1, Col2)
  SELECT ID, Col1, Col2 FROM #StagingTable;
  SET IDENTITY_INSERT TargetTable OFF;
  • Confirm only one table per session has IDENTITY_INSERT enabled, as SQL Server 2025 still enforces single-table scope per session.

Step 4: Validate Server and Database Compatibility Level

  • Run SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabase';
  • If the database is running an older compatibility level (e.g., 140 or 150) on SQL Server 2025, update it using:
  ALTER DATABASE YourDatabase SET COMPATIBILITY_LEVEL = 170;
  • This ensures the query optimizer uses the updated nested-INSERT handling introduced in newer SQL Server builds.

Alternative or Verification Steps

  • Re-run the corrected script in a test environment and confirm no Error 5328 appears in the SQL Server Error Log (EXEC sp_readerrorlog;).
  • If the issue persists, use SQL Server Profiler or Extended Events to trace the exact execution plan and confirm the nested INSERT has been fully decoupled from the FROM clause before retrying the operation.

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

Troubleshooting Guide: SQL Server Error 5329

Why This Error Happens

This error occurs because SQL Server’s query optimizer cannot process windowed functions (such as ROW_NUMBER(), RANK(), OVER(), or aggregate windowing clauses) when the statement’s FROM clause references a nested INSERT (commonly via the INSERT ... OUTPUT pattern used as a data source). The engine restricts this combination because the execution plan cannot guarantee a stable row ordering or partition context when DML operations are composed inline with windowing logic. This typically surfaces in Microsoft SQL Server 2025 when developers attempt to use OUTPUT INTO or composable DML in combination with analytic functions in the same statement tree, which is an unsupported T-SQL construct rather than a bug or corrupted installation.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Review the SQL statement referenced in the error log or SSMS output pane.
  • Look specifically for a nested INSERT statement (e.g., INSERT INTO ... OUTPUT ... INTO) being used inside a FROM clause.
  • Check if a windowed function like OVER (PARTITION BY ... ORDER BY ...) appears in the SELECT, WHERE, or ORDER BY clause of the same outer query.

Step 2: Refactor the Query to Separate DML and Windowing Logic

  • Break the composable DML (INSERT ... OUTPUT) into its own standalone statement, writing results into a temporary table or table variable first.
  • Example pattern:
  • INSERT INTO #TempResults OUTPUT inserted.* INTO #StagingTable SELECT * FROM SourceTable;
  • Apply the windowed function in a separate, subsequent SELECT statement that reads from #StagingTable instead of nesting it directly.

Step 3: Update Application or ORM-Generated Queries

  • If the query is auto-generated by an ORM (Entity Framework, Dapper, etc.), check the generated SQL via SQL Server Profiler or Extended Events.
  • Modify the ORM mapping or raw SQL override to avoid combining OUTPUT clauses with windowed analytic functions in a single composed statement.
  • Redeploy the updated stored procedure or query to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\ dependent application logic if stored procedures are version-controlled externally.

Step 4: Validate T-SQL Compatibility Level

  • Open SSMS and run: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the database is running under SQL Server 2025 compatibility level (160 or higher) so that any newer workarounds or syntax improvements are available.
  • If running a lower compatibility level, update it via: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 160;

Alternative or Verification Steps

  • Re-run the refactored query in SSMS or Azure Data Studio and confirm Error 5329 no longer appears in the Messages tab.
  • If the issue persists, use a Common Table Expression (CTE) to isolate the INSERT OUTPUT operation from the windowed SELECT, ensuring no windowed function shares a query plan with the nested DML statement.

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

Troubleshooting Guide: SQL Server Error 5324 in MERGE Statement

Why This Error Happens

Error 5324 occurs when a MERGE statement attempts to reference the same row more than once through a self-referencing or cyclic relationship, typically caused by a MATCHED clause that updates a column used in the ON join condition. This violates SQL Server’s requirement that a single source row must not match and modify the same target row in a way that creates ambiguous update paths. It is also frequently triggered when the WHEN MATCHED clause attempts to update a column that is part of a foreign key or self-join condition, causing SQL Server’s query optimizer to detect a potential infinite update loop or non-deterministic result set.

Step-by-Step Resolution Guide

Step 1: Review the MERGE Statement Join Condition

  • Open the query in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the ON clause of the MERGE statement.
  • Check whether the column(s) used in the ON condition are also being modified in the WHEN MATCHED THEN UPDATE SET clause.
  • Example of a problematic pattern: ON target.ID = source.ID ... WHEN MATCHED THEN UPDATE SET target.ID = source.NewID.

Step 2: Eliminate Self-Referencing Updates

  • Rewrite the MERGE statement so that the join key is never part of the UPDATE SET list.
  • If a hierarchical or self-referencing table is involved (e.g., an EmployeeID referencing a ManagerID in the same table), split the operation into two separate statements: one for inserts and one for updates, instead of a single MERGE.
  • Use a staging table to pre-validate source data before executing the MERGE, ensuring no row maps back to itself in a way that creates a cycle.

Step 3: Add Explicit Row Uniqueness Checks

  • Add a GROUP BY or ROW_NUMBER() filter on the source table to confirm each target row is matched exactly once.
  • Modify the query as follows:
;WITH SourceDeduped AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS rn
    FROM SourceTable
)
MERGE INTO TargetTable AS target
USING (SELECT * FROM SourceDeduped WHERE rn = 1) AS source
ON target.ID = source.ID
WHEN MATCHED THEN UPDATE SET target.Value = source.Value
WHEN NOT MATCHED THEN INSERT (ID, Value) VALUES (source.ID, source.Value);
  • Deploy this corrected script via SSMS or through your deployment pipeline (e.g., Azure DevOps, SQL Server Agent Job) on Windows Server 2025.

Alternative or Verification Steps

  • Run the modified MERGE statement in a test environment first; if it executes without Error 5324 and the row counts match expected inserts/updates, the fix is confirmed.
  • If the error persists, replace the MERGE statement entirely with separate INSERT and UPDATE statements wrapped in a transaction — this avoids the internal cyclic-update detection logic entirely and is the recommended Microsoft workaround for complex self-referencing scenarios.

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

Troubleshooting Guide: Error 5325 – ORDER Hint Mismatch in BULK Rowset

Why This Error Happens

This error occurs when the SQL Server query optimizer detects that the actual physical order of rows in the source data file does not match the column order specified in the ORDER hint of a BULK INSERT, OPENROWSET(BULK...), or BCP-related operation. SQL Server relies on this hint to optimize sort-dependent operations (like merge joins or indexed inserts) without performing an actual sort, so any deviation—even a single out-of-sequence row—triggers a hard validation failure. This commonly happens after a data file has been modified, re-exported from a different source, or if the ORDER hint was copied from a template without verifying the actual file contents.

Step-by-Step Resolution Guide

Step 1: Verify the Actual Data Order in the Source File

  • Open the source .csv, .dat, or .txt file using a text editor or import it into a staging table without the ORDER hint.
  • Run a SELECT query against the staging table with an ORDER BY on the suspected key column(s) and compare row-by-row against the raw file.
  • Identify the exact column(s) and direction (ASC/DESC) that the data is actually sorted by.

Step 2: Correct the ORDER Hint in Your T-SQL Statement

  • Locate the BULK INSERT or OPENROWSET(BULK...) statement in your script.
  • Update the ORDER clause to exactly match the verified column order from Step 1, for example:
  • WITH (ORDER (CustomerID ASC, OrderDate ASC))
  • Ensure column names in the hint match the destination table schema exactly, including case sensitivity if using a case-sensitive collation.

Step 3: Re-Sort the Source File if the Hint Cannot Be Changed

  • If the ORDER hint is fixed by downstream dependencies (e.g., a merge join plan), re-sort the source file instead.
  • Use PowerShell on Windows Server 2025 to pre-sort the file:
  • Import-Csv .\sourcefile.csv | Sort-Object CustomerID, OrderDate | Export-Csv .\sourcefile_sorted.csv -NoTypeInformation
  • Re-point the BULK INSERT statement to the newly sorted file path.

Step 4: Check for Hidden Data Issues Causing False Mismatches

  • Inspect the file for blank lines, trailing whitespace, or inconsistent line terminators (\r\n vs \n), which can cause SQL Server to misread row boundaries and falsely report order violations.
  • Use ROWTERMINATOR and FIELDTERMINATOR arguments explicitly in your BULK INSERT statement to rule out parsing ambiguity.

Alternative or Verification Steps

  • To verify the fix, re-run the BULK INSERT statement and confirm Error 5325 no longer appears; check sys.dm_exec_query_stats or the SQL Server error log to confirm successful completion.
  • As an alternative, remove the ORDER hint entirely (if performance impact is acceptable) and let SQL Server perform an implicit sort—this avoids the validation check at the cost of additional CPU/I/O overhead.

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

Troubleshooting Guide: SQL Server Error 5326 – UNIQUE Hint Violation in BULK Rowset

Why This Error Happens

This error occurs when SQL Server’s OPENROWSET(BULK...) function is used with the UNIQUE hint on an ORDER column, but the source data file actually contains duplicate values in that column. The UNIQUE hint tells the Query Optimizer to treat the sorted column as having distinct values to generate a more efficient execution plan, and SQL Server validates this assumption during the bulk load. Because the underlying data violates that uniqueness constraint, the bulk operation fails rather than risk building an inaccurate query plan or corrupting downstream index assumptions.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Column and Query

  • Locate the OPENROWSET(BULK...) statement in your T-SQL script, SSIS package, or application code that references the .fmt format file.
  • Check the ORDER clause syntax, which typically looks like: ORDER (ColumnName ASC) UNIQUE.
  • Note the exact column name flagged with the UNIQUE hint, as this is the column containing duplicate data.

Step 2: Validate the Source Data File

  • Open the source flat file (CSV, TXT, etc.) referenced in the BULK path, usually found in a shared directory like D:\SQLData\ImportFiles\.
  • Use a text editor, PowerShell, or a staging table to scan for duplicate values in the specific column:
  • Get-Content "D:\SQLData\ImportFiles\source.txt" | Group-Object | Where-Object { $_.Count -gt 1 }
  • Confirm whether duplicates are legitimate data or the result of a faulty export/ETL process upstream.

Step 3: Remove or Correct the UNIQUE Hint

  • If the data is expected to contain duplicates, edit the T-SQL query and remove the UNIQUE keyword from the ORDER hint clause entirely.
  • Example corrected syntax: WITH (ORDER (ColumnName ASC)) instead of WITH (ORDER (ColumnName ASC) UNIQUE).
  • Save the updated script or stored procedure in SQL Server Management Studio (SSMS) and re-run the bulk insert job.

Step 4: Clean the Data Source (If Uniqueness Is Required)

  • If the application logic genuinely requires unique values (e.g., for a subsequent clustered index build), de-duplicate the source file before import.
  • Run a pre-processing script or Power Query transformation to strip duplicate rows from the .csv or .txt file.
  • Re-save the cleaned file to the import directory and re-attempt the bulk load with the UNIQUE hint intact.

Step 5: Re-run the Bulk Insert Operation

  • Execute the modified BULK INSERT or OPENROWSET(BULK...) statement again via SSMS or your automation tool (Agent Job/SSIS).
  • Monitor the Messages tab in SSMS for successful row count confirmation instead of Error 5326.

Alternative or Verification Steps

  • Verify the fix by querying the destination table post-load: SELECT ColumnName, COUNT(*) FROM TargetTable GROUP BY ColumnName HAVING COUNT(*) > 1;—this should return zero rows if duplicates were successfully handled.
  • As an alternative, bypass the hint entirely by loading data into a staging table without ORDER/UNIQUE hints, then use a MERGE or INSERT...SELECT DISTINCT statement to populate the final table safely.

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

Troubleshooting Guide: SQL Server Error 5322

Why This Error Happens

This error occurs when a T-SQL statement attempts to use an aggregate function (such as SUM(), COUNT(), or AVG()) directly within a clause that references a nested INSERT statement inside a FROM clause, typically via the OUTPUT INTO or data-consuming INSERT ... EXEC pattern. SQL Server’s query optimizer cannot resolve aggregation logic against a nested DML statement because the nested INSERT has not fully materialized its result set at the point the aggregate is evaluated. This is a query construction limitation rather than a server configuration or permissions issue, meaning the fix lies entirely in rewriting the offending query.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log or Extended Events session for the exact statement that triggered Error 5322.
  • Look specifically for a FROM clause containing a nested INSERT (commonly seen with INSERT ... OUTPUT combined with SELECT subqueries).
  • Confirm the aggregate function (SUM, COUNT, MAX, MIN, AVG) is being applied in the same statement block as the nested insert.

Step 2: Refactor the Query Using a Temporary Table or Table Variable

  • Instead of nesting the INSERT directly inside the FROM clause, redirect the OUTPUT results into a temporary table first.
  • Example pattern:
  DECLARE @Results TABLE (ID INT, Amount DECIMAL(18,2));

  INSERT INTO TargetTable (ID, Amount)
  OUTPUT inserted.ID, inserted.Amount INTO @Results
  SELECT ID, Amount FROM SourceTable;

  SELECT SUM(Amount) FROM @Results;
  • This separates the DML operation from the aggregation step, avoiding the parser conflict entirely.

Step 3: Update Stored Procedures and ORM-Generated Queries

  • If the query originates from an ORM (Entity Framework, Dapper, etc.), inspect the generated SQL in SQL Server Profiler or Extended Events.
  • Manually override the generated query with a stored procedure that uses the temp table pattern from Step 2.
  • Deploy the corrected stored procedure via SQL Server Management Studio (SSMS) 21 or Azure Data Studio, ensuring it replaces the inline query call.

Step 4: Validate Compatibility Level Settings

  • Open SSMS and run:
  SELECT compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • Ensure the database is running at compatibility level 160 or higher (SQL Server 2022/2025 engine behavior) since older compatibility levels can sometimes mask or alter how nested DML errors surface.
  • Adjust if needed:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Alternative or Verification Steps

  • Re-run the corrected query in SSMS or Azure Data Studio and confirm no Error 5322 appears in the Messages tab; check sys.messages to confirm error ID 5322 is no longer logged in the SQL Server error log.
  • As an alternative, wrap the aggregate logic in a separate SELECT statement that queries the final target table after the INSERT transaction commits, rather than attempting to aggregate in-flight data from the nested insert.

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

Troubleshooting Guide: Error 5323 in SQL Server 2025

Why This Error Happens

This error occurs when a Data Manipulation Language (DML) statement, such as an INSERT ... OUTPUT command, contains a subquery inside a clause where the FROM source itself relies on a nested INSERT operation. SQL Server’s query optimizer cannot resolve the execution plan because nested DML operations combined with correlated subqueries create an ambiguous dependency chain. This is typically a T-SQL syntax architecture issue rather than a server configuration or permissions problem, often surfacing after code migrations or ORM-generated queries targeting SQL Server 2025.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Open SQL Server Management Studio (SSMS) 20 or Azure Data Studio connected to your Windows Server 2025 instance.
  • Check the Activity Monitor or Extended Events session to capture the exact T-SQL statement that triggered Error 5323.
  • Look specifically for syntax combining INSERT INTO ... SELECT with a nested (INSERT INTO ... OUTPUT ...) inside the FROM clause.

Step 2: Refactor the Nested INSERT Logic

  • Isolate the nested INSERT statement and execute it independently, directing its output into a temporary table using OUTPUT INTO #TempResults.
  • Modify the path: Save the script typically found in C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Scripts\ for version control before editing.
  • Rewrite the outer query to select from the newly created temporary table (#TempResults) instead of nesting the INSERT directly inside the FROM clause.
  • Remove any correlated subqueries from the OUTPUT or FROM clause that reference columns from the nested insert directly.

Step 3: Update Compatibility Level and Validate Syntax

  • Open SSMS and right-click the Database in Object Explorer, navigate to Properties > Options.
  • Ensure the Compatibility Level is set to SQL Server 2025 (170) to ensure the parser uses the latest optimization rules.
  • Run DBCC FREEPROCCACHE to clear any cached execution plans that might be enforcing the old, broken query structure.
  • Re-execute the refactored script from Step 2 to confirm the parser accepts the new logic.

Step 4: Restart the SQL Server Service

  • Open the Services app (services.msc) on Windows Server 2025.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to ensure the new query plan logic is loaded fresh into the buffer pool.
  • Verify the Windows Event Viewer (Application Log) shows a clean startup with no residual 5323 flags.

Alternative or Verification Steps

  • Verification: Run the modified query in a transaction block (BEGIN TRAN ... ROLLBACK) to confirm it executes without throwing Error 5323, then commit once validated.
  • Alternative: If refactoring is not immediately possible, wrap the nested logic inside a Table-Valued Function (TVF) or a View first, then perform the INSERT from that View to bypass the nested DML restriction entirely.

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

Microsoft SQL Server 2025 – Error 5318 Troubleshooting Guide

Why This Error Happens

Error 5318 occurs when a MERGE statement’s ON clause join condition targets the same row in the target table more than once from the source, causing SQL Server to be unable to deterministically decide which action (UPDATE/DELETE) to apply. This typically results from a source table or derived query containing duplicate keys relative to the join predicate used in the MERGE. It can also surface when the source query lacks proper deduplication logic (e.g., missing GROUP BY, DISTINCT, or a windowing filter like ROW_NUMBER()).

Step-by-Step Resolution Guide

Step 1: Identify Duplicate Rows in the Source

  • Run a diagnostic query against your source table/query using GROUP BY on the join key(s) with HAVING COUNT(*) > 1.
  • Example: SELECT JoinKey, COUNT(*) FROM SourceTable GROUP BY JoinKey HAVING COUNT(*) > 1;
  • Confirm whether duplicates are expected (bad data) or a logic flaw in your source query.

Step 2: Deduplicate the Source Data Before the MERGE

  • Wrap the source in a CTE using ROW_NUMBER() OVER (PARTITION BY JoinKey ORDER BY SomeColumn) and filter to WHERE rn = 1.
  • Alternatively, use SELECT DISTINCT if full row duplication (not just key duplication) is the cause.
  • Update the USING (...) clause in your MERGE statement to reference this cleaned CTE/subquery instead of the raw table.

Step 3: Refine the ON Clause Join Predicate

  • Ensure the ON clause includes all necessary composite key columns to uniquely match target rows (not just a partial key).
  • Check for implicit cross joins caused by missing predicates in multi-column joins.
  • Validate against Windows Server 2025 collation settings if key comparisons involve case-sensitive or accent-sensitive text columns, as mismatched collations can cause unexpected multi-row matches.

Step 4: Test the MERGE in Isolation

  • Run the MERGE statement inside a transaction (BEGIN TRAN ... ROLLBACK) in SQL Server Management Studio (SSMS) 21 or Azure Data Studio.
  • Review the execution plan for unexpected join fan-out before committing changes.

Alternative or Verification Steps

  • Re-run the MERGE statement after deduplication; if it completes without Error 5318, commit the transaction and check affected row counts match expectations.
  • As an alternative, replace the MERGE with separate explicit UPDATE and INSERT statements wrapped in a transaction — this avoids MERGE‘s strict single-match requirement entirely and is often more predictable for complex source datasets.

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

Troubleshooting Guide: Error 5319 – Aggregates Not Allowed in MERGE WHEN Clause

Why This Error Happens

This error occurs because SQL Server’s T-SQL syntax explicitly disallows aggregate functions (such as SUM, COUNT, AVG, MIN, or MAX) directly within the WHEN MATCHED, WHEN NOT MATCHED, or WHEN NOT MATCHED BY SOURCE clauses of a MERGE statement. The query optimizer cannot resolve aggregate computations at the row-level matching stage of a MERGE operation, as aggregates require a grouping context that conflicts with the row-by-row evaluation logic of the MATCH conditions. This is a T-SQL language restriction rather than a server configuration or permissions issue, meaning the fix must occur in the query code itself rather than in SQL Server settings.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Aggregate Function

  • Open the MERGE statement in SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact WHEN clause triggering Error 5319.
  • Look for functions like SUM(), COUNT(), AVG(), MIN(), or MAX() placed inside the AND condition of a WHEN MATCHED or WHEN NOT MATCHED clause.
  • Example of invalid syntax: WHEN MATCHED AND SUM(source.Amount) > 100 THEN UPDATE...

Step 2: Pre-Calculate Aggregates Using a CTE or Derived Table

  • Rewrite the query so the aggregate logic is calculated before the MERGE statement runs, using a Common Table Expression (CTE) or a subquery.
  • Example structure:
  WITH AggregatedSource AS (
      SELECT CustomerID, SUM(Amount) AS TotalAmount
      FROM SourceTable
      GROUP BY CustomerID
  )
  MERGE INTO TargetTable AS target
  USING AggregatedSource AS source
  ON target.CustomerID = source.CustomerID
  WHEN MATCHED AND source.TotalAmount > 100 THEN
      UPDATE SET target.Status = 'High Value';
  • Ensure the CTE handles all necessary GROUP BY and HAVING logic so the MERGE statement only references the pre-aggregated column (source.TotalAmount).

Step 3: Validate Join Keys and Execute in a Test Environment

  • Confirm that the CTE’s GROUP BY columns match the join keys used in the MERGE ON clause to avoid cardinality mismatches (which can cause Error 8672 or duplicate row errors).
  • Deploy the corrected script to a non-production or staging instance of SQL Server 2025 first.
  • Run the query using SET STATISTICS IO ON to verify the execution plan resolves correctly without syntax errors.

Alternative or Verification Steps

  • Verification: Execute the modified MERGE statement in a transaction block (BEGIN TRAN) and check the Messages tab in SSMS for a successful “(N rows affected)” output instead of the 5319 error, then roll back if only testing.
  • Alternative Fix: If restructuring the MERGE is not feasible, split the logic into a standard UPDATE/INSERT pair using a WHERE EXISTS subquery containing the aggregate, bypassing the MERGE syntax entirely.

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

Troubleshooting Guide: SQL Server Error 5321

Why This Error Happens

This error occurs because SQL Server 2025 does not permit certain functions to be referenced in the OUTPUT clause (represented by %S_MSG) when the statement’s FROM clause contains a nested data-modification operation, such as an INSERT wrapped inside a composable DML query. This restriction exists because the query optimizer cannot guarantee deterministic row-ordering or side-effect consistency when volatile functions are evaluated against a result set that is simultaneously being modified by a nested writer. Essentially, the engine is blocking a syntax pattern where you are trying to read “in-flight” data changes using a function that isn’t safe for that context.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function in the Query

  • Open the specific stored procedure or ad-hoc query referenced in the SQL Server error log that triggered Event ID 5321.
  • Look specifically at the OUTPUT or RETURNING clause of the outer query.
  • Check if you are using Ranking functions (e.g., ROW_NUMBER(), RANK()) or aggregate functions directly inside this clause while the FROM source is a nested INSERT.

Step 2: Refactor the Nested INSERT into a Temporary Table

  • Instead of nesting the INSERT ... OUTPUT directly inside the FROM clause of the outer query, break the transaction into two distinct steps.
  • First, execute the nested INSERT statement and capture its OUTPUT into a temporary table or table variable (e.g., INSERT INTO #TempResults...).
  • Second, run your outer SELECT statement—including the restricted function—against the #TempResults table instead of the live nested insert.

Step 3: Update Compatibility Level and Apply Cumulative Updates

  • Navigate to SQL Server Management Studio (SSMS) and right-click the Database > Properties > Options.
  • Verify the “Compatibility Level” is set to SQL Server 2025 (170) to ensure the query processor uses the latest execution rules.
  • On your Windows Server 2025 host, check Windows Update or the SQL Server Installation Center for the latest Cumulative Update (CU), as early builds of SQL Server 2025 had stricter parsing bugs regarding this specific clause that were patched in subsequent updates.

Step 4: Validate T-SQL Syntax Using sqlcmd

  • Open a Command Prompt or PowerShell terminal on the Windows Server 2025 machine.
  • Run the modified query via the command line utility to isolate it from SSMS caching issues:
    sqlcmd -S localhost -d YourDatabaseName -Q "EXEC YourStoredProcedureName"
  • Check the terminal output directly for the removal of the 5321 error code.

Alternative or Verification Steps

  • Verification: Re-run the specific transaction via SSMS and check the “Messages” tab; if the fix was successful, the query will return a “Command(s) completed successfully” message instead of the %S_MSG clause error.
  • Alternative: If refactoring the query is not immediately feasible, wrap the restricted function logic in a Common Table Expression (CTE) that sits outside the nested insert logic, effectively separating the data modification from the data read-back operation.

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

Troubleshooting Guide: Error 5315 – “The Target of a MERGE Statement Cannot Be a Remote Table”

Why This Error Happens

This error occurs because SQL Server’s MERGE statement does not support referencing a remote table (via a linked server) as the target of the operation. SQL Server 2025 enforces strict transactional and locking guarantees for MERGE operations that cannot be reliably coordinated across a linked server connection. This limitation is architectural, not a bug, and typically surfaces when developers attempt cross-server data synchronization using MERGE instead of standard INSERT/UPDATE/DELETE logic.

Step-by-Step Resolution Guide

Step 1: Identify the Linked Server Reference in the MERGE Statement

  • Review the MERGE statement’s target clause (the table immediately following the MERGE INTO keyword).
  • Check if the target table name is qualified with a four-part name (e.g., LinkedServerName.DatabaseName.Schema.TableName).
  • Confirm the linked server by running SELECT * FROM sys.servers WHERE is_linked = 1; in SQL Server Management Studio (SSMS) 21.

Step 2: Restructure the Query to Use a Local Staging Table

  • Create a local temporary table or table variable on the server where the MERGE will execute.
  • Populate it with data pulled from the remote server first: SELECT * INTO #StagingTable FROM LinkedServerName.DB.Schema.SourceTable;
  • Rewrite the MERGE statement so both the source and target reference only local objects, using #StagingTable as the source instead of the remote reference.

Step 3: Push Execution to the Remote Server via Stored Procedure

  • If the target table must remain on the remote instance, use sp_executesql or OPENQUERY to execute the MERGE statement remotely instead of locally referencing it.
  • Example: Wrap the MERGE logic inside a stored procedure on the remote server, then call it using EXEC LinkedServerName.DatabaseName.Schema.ProcedureName; from the local instance.
  • Validate linked server permissions in SSMS > Server Objects > Linked Servers > Security to ensure the calling login has EXECUTE rights on the remote procedure.

Step 4: Verify Linked Server Configuration and Provider Settings

  • Open SQL Server Configuration Manager on Windows Server 2025 and confirm the OLE DB provider used for the linked server supports distributed transactions.
  • In SSMS, right-click the Linked Server, select Properties, and verify “RPC” and “RPC Out” are set to True under Server Options if remote procedure calls are required.
  • Restart the SQL Server service (services.msc or net stop MSSQLSERVER && net start MSSQLSERVER) after changing provider options.

Step 5: Enable MSDTC if Using Distributed Transactions

  • Open Component Services (dcomcnfg.exe) on both the local and remote Windows Server 2025 instances.
  • Navigate to Component Services > Computers > My Computer > Distributed Transaction Coordinator and ensure the MSDTC service is running.
  • Enable “Network DTC Access” under Security Configuration and restart the MSDTC service for changes to take effect.

Alternative or Verification Steps

  • Run the rewritten MERGE statement (using the local staging table approach) and confirm it executes without Error 5315 in the SSMS Messages pane.
  • As a quick alternative, replace the MERGE logic entirely with separate INSERT INTO ... SELECT, UPDATE, and DELETE statements targeting the linked server directly, since standard DML statements do not share the same remote-target restriction as MERGE.

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

Troubleshooting Guide: MERGE Statement Error 5316 (INSTEAD OF Trigger Conflict)

Why This Error Happens

This error occurs because SQL Server 2025 does not allow a MERGE statement to target a table that has an INSTEAD OF trigger defined on some, but not all, of the DML actions (INSERT, UPDATE, DELETE) used within that MERGE operation. The engine requires consistency—if an INSTEAD OF trigger exists for one action type (e.g., UPDATE), the MERGE statement effectively needs equivalent handling for the other actions it attempts to perform, or it will fail validation. This is typically a schema design conflict rather than a permissions or connectivity issue, often surfacing after a database migration or trigger update where legacy triggers were not refactored for MERGE compatibility.

Step-by-Step Resolution Guide

Step 1: Identify the Conflicting Trigger

  • Open SQL Server Management Studio (SSMS) and connect to your Windows Server 2025 instance.
  • Run the following query to inspect triggers on the target table: SELECT name, is_instead_of_trigger FROM sys.triggers WHERE parent_id = OBJECT_ID('YourTargetTable');
  • Note which specific DML action (INSERT, UPDATE, or DELETE) is mapped to the INSTEAD OF trigger causing the conflict.

Step 2: Refactor the MERGE Statement Logic

  • Since MERGE cannot mix standard actions with INSTEAD OF triggers inconsistently, break the single MERGE statement into separate, discrete INSERT, UPDATE, and DELETE statements.
  • Wrap these separate statements in an explicit transaction block (BEGIN TRAN / COMMIT TRAN) to maintain atomicity, replicating the original MERGE behavior.

Step 3: Modify the Trigger Definition (If Refactoring is Not an Option)

  • Navigate to the trigger definition via Object Explorer > Databases > [YourDB] > Tables > [YourTable] > Triggers in SSMS.
  • Update the trigger using ALTER TRIGGER to include logic for all three DML operations (INSERT, UPDATE, DELETE) rather than just one, ensuring the trigger acts as a comprehensive INSTEAD OF handler.
  • Save the changes and recompile the stored procedure containing the MERGE statement using sp_recompile 'YourTargetTable';.

Step 4: Restart SQL Server Service

  • Open the Services app on Windows Server 2025 (services.msc).
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart to clear any cached execution plans that might be holding the old trigger logic.

Alternative or Verification Steps

  • Verification: Execute the original stored procedure or script again in a test environment; if Error 5316 does not appear and the @@ROWCOUNT matches expected changes, the fix is successful.
  • Alternative: If modifying triggers is restricted by Database Owners (DBOs), use a temporary staging table to pre-process the MERGE logic outside the main table, then apply changes via a trigger-safe UPDATE loop.

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

Troubleshooting Guide: MSSQL Error 5317 — MERGE Target Cannot Be a Partitioned View

Why This Error Happens

Error 5317 occurs because the MERGE statement in SQL Server does not support partitioned views as a target object. This is a hard architectural limitation of the Database Engine, not a permissions or configuration defect — the query optimizer cannot resolve INSERT/UPDATE/DELETE actions generated by MERGE across the underlying member tables of a partitioned view. The error will persist regardless of compatibility level, service pack, or server configuration on Windows Server 2025 or Windows 11 until the underlying T-SQL logic is rewritten.

Step-by-Step Resolution Guide

Step 1: Identify the Partitioned View in the MERGE Statement

  • Open SQL Server Management Studio (SSMS) and locate the failing MERGE statement.
  • Run sp_helptext 'YourViewName' to confirm the target is a view built with UNION ALL across multiple tables with CHECK constraints (the definition of a partitioned view).
  • Check Event Viewer under Windows Logs > Application on Windows Server 2025 for the corresponding SQL Server error log entry referencing Error 5317.

Step 2: Replace the Partitioned View Target with a Partitioned Table

  • Migrate the underlying member tables into a single table using native table partitioning (CREATE PARTITION FUNCTION and CREATE PARTITION SCHEME) instead of a partitioned view.
  • Point the MERGE statement directly at the new partitioned table rather than the view.
  • Example:
  CREATE PARTITION FUNCTION pfRange (int)
  AS RANGE LEFT FOR VALUES (1000, 2000, 3000);

  CREATE PARTITION SCHEME psRange
  AS PARTITION pfRange ALL TO ([PRIMARY]);

Step 3: Rewrite the Logic Using Separate DML Statements

  • If migrating to a partitioned table is not immediately feasible, decompose the MERGE into individual INSERT, UPDATE, and DELETE statements targeting each underlying base table directly.
  • Wrap these statements inside an explicit transaction to preserve atomicity:
  BEGIN TRANSACTION;
      UPDATE dbo.Table_2024 SET Col1 = Src.Col1 FROM Staging AS Src WHERE ...;
      INSERT INTO dbo.Table_2025 (...) SELECT ... FROM Staging AS Src WHERE NOT EXISTS (...);
  COMMIT TRANSACTION;

Step 4: Validate Query Plans in SSMS

  • Open Include Actual Execution Plan in SSMS and re-run the rewritten statements.
  • Confirm no reference to the partitioned view appears as a write target in the plan — only base tables should show INSERT/UPDATE/DELETE operators.

Alternative or Verification Steps

  • Run sys.dm_exec_describe_first_result_set or re-execute the modified script in a test database to confirm Error 5317 no longer appears in the Messages tab.
  • If table partitioning is not an option, consider using an INSTEAD OF trigger on the view to internally redirect INSERT/UPDATE/DELETE logic, though this adds maintenance overhead compared to native partitioning.

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

Troubleshooting Guide: Error 5312 – “The input to the function ‘ntile’ cannot be bound”

Why This Error Happens

This error occurs when the NTILE() window function is used with an expression in its argument (such as a variable, subquery, or column reference) that SQL Server cannot resolve at compile time, since NTILE requires a constant, literal integer value for the number of groups. It can also surface when the function is nested improperly inside another ranking or aggregate function, or when a parameterized query passes a non-constant value directly into the NTILE argument. This is a query-construction limitation in SQL Server 2025’s T-SQL parser, not a server configuration or permissions issue.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server error log or Activity Monitor on Windows Server 2025 for the exact query text tied to Error 5312.
  • Look specifically for a NTILE(n) clause where n is a variable, column, or subquery instead of a hard-coded integer.
  • Example of a broken pattern: NTILE(@GroupCount) OVER (ORDER BY SalesAmount).

Step 2: Replace Dynamic Values with Constants

  • Rewrite the query so the NTILE argument is a literal integer, e.g., NTILE(4) OVER (ORDER BY SalesAmount).
  • If the group count must be dynamic, use Dynamic SQL instead:
  • DECLARE @sql NVARCHAR(MAX) = N'SELECT NTILE(' + CAST(@GroupCount AS NVARCHAR(10)) + N') OVER (ORDER BY SalesAmount) FROM Sales;'
  • EXEC sp_executesql @sql;
  • Ensure the dynamic value is validated/sanitized to prevent SQL injection before concatenation.

Step 3: Check for Nested Function Misuse

  • Confirm NTILE is not nested inside another window function or aggregate (e.g., SUM(NTILE(4) OVER(...))), which is invalid.
  • Separate the NTILE calculation into a CTE or derived table, then apply additional aggregation in an outer query.
  • Example: WITH Ranked AS (SELECT *, NTILE(4) OVER (ORDER BY SalesAmount) AS Grp FROM Sales) SELECT Grp, SUM(SalesAmount) FROM Ranked GROUP BY Grp;

Step 4: Update SQL Server Tools and Drivers

  • On Windows 11/Windows Server 2025 client machines, ensure SQL Server Management Studio (SSMS) and the OLE DB/ODBC drivers are updated to the latest build compatible with SQL Server 2025, as outdated client libraries can mis-parse newer T-SQL syntax.
  • Path to check: Control Panel > Programs and Features > Microsoft SQL Server Management Studio for version info, then update via the official Microsoft Download Center.

Alternative or Verification Steps

  • Run the corrected query in a new SSMS query window connected directly to the SQL Server 2025 instance and confirm no Error 5312 appears in the Messages tab.
  • If dynamic grouping is still required and sp_executesql is not feasible, consider using CASE statements to manually bucket rows as a workaround instead of NTILE.

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

Troubleshooting Guide: SQL Server Error 5313 — Synonym Refers to an Invalid Object

Why This Error Happens

This error occurs when a synonym object in SQL Server points to a base object (table, view, stored procedure, or function) that no longer exists, has been renamed, or resides in a schema/database the current user cannot access. It is commonly triggered after a deployment, migration, or refactoring process drops or renames the underlying object without updating or dropping the dependent synonym. Additionally, this can happen if the target object exists on a linked server that is unreachable, or if the executing login lacks the necessary permissions (SELECT, EXECUTE, or REFERENCES) on the base object itself.

Step-by-Step Resolution Guide

Step 1: Identify the Synonym and Its Target

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance on your Windows Server 2025/Windows 11 machine.
  • Run the following query to locate the synonym definition and its intended base object:
SELECT name, base_object_name, schema_id 
FROM sys.synonyms 
WHERE name = 'YourSynonymName';
  • Note the exact three or four-part name returned in base_object_name (e.g., ServerName.DatabaseName.SchemaName.ObjectName).

Step 2: Verify the Base Object Exists

  • Query sys.objects in the target database to confirm the base object is actually present and spelled correctly:
SELECT * FROM sys.objects WHERE name = 'BaseObjectName';
  • If the object was renamed or dropped during a recent release, check the deployment scripts or Default Trace / Extended Events logs for DROP or ALTER statements executed around the error timestamp.
  • If the base object sits on a linked server, verify connectivity using sp_testlinkedserver 'LinkedServerName'; and confirm the remote server is online and reachable over the network (check firewall rules on Windows Server 2025).

Step 3: Correct Permissions on the Base Object

  • Ensure the login/user executing the synonym call has explicit permissions on the underlying object, since permission checks in synonyms do not inherit automatically in all contexts:
GRANT SELECT ON dbo.BaseObjectName TO [YourUserOrRole];
  • For stored procedures or functions referenced by the synonym, grant EXECUTE instead of SELECT.

Step 4: Recreate the Synonym with the Correct Reference

  • If the base object was renamed or moved, drop and recreate the synonym pointing to the new valid path:
DROP SYNONYM dbo.YourSynonymName;
GO
CREATE SYNONYM dbo.YourSynonymName 
FOR DatabaseName.SchemaName.NewObjectName;
GO
  • Double-check case sensitivity and schema qualification, especially if the database collation is case-sensitive.

Alternative or Verification Steps

  • Re-run the query or application call that originally triggered Error 5313; a successful result set or execution with no 5313 error confirms the synonym now resolves correctly.
  • As an alternative, audit all synonyms in the database at once using SELECT * FROM sys.synonyms cross-referenced against sys.objects to catch any other orphaned synonyms before they cause production errors.

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

Troubleshooting Guide: SQL Server Error 5314 — “The Use of Aggregates Is Not Allowed in This Context”

Why This Error Happens

This error occurs when an aggregate function (such as SUM, COUNT, AVG, MIN, or MAX) is used in a part of a T-SQL statement where SQL Server’s query parser does not permit it, such as within a CHECK constraint, a computed column definition, a WHERE clause without a proper subquery, or inside certain system view definitions. The SQL Server 2025 query optimizer strictly validates the logical placement of aggregates during the binding phase, and if it detects an aggregate outside a valid scope (like a SELECT list, HAVING clause, or GROUP BY-enabled subquery), it immediately halts compilation. This is not a server configuration or permissions issue — it is a syntax/logic validation error rooted in how the query or object definition was written.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Statement Triggering the Error

  • Review the full error message in SQL Server Management Studio (SSMS) or Azure Data Studio to locate the line number and object name.
  • Check if the aggregate is being used inside a CHECK constraint, computed column, DEFAULT constraint, or a scalar subquery in a WHERE clause.
  • Run SELECT * FROM sys.messages WHERE message_id = 5314; to confirm the exact wording and context class for your SQL Server 2025 build.

Step 2: Rewrite the Query Using a Valid Aggregate Scope

  • Move the aggregate into the SELECT list and use a GROUP BY clause instead of placing it directly in WHERE.
  • Example fix: replace WHERE SUM(Sales) > 1000 with a subquery: WHERE EXISTS (SELECT 1 FROM Orders GROUP BY CustomerID HAVING SUM(Sales) > 1000).
  • If the aggregate is inside a computed column or CHECK constraint, refactor the logic into a scalar user-defined function (UDF) or a trigger instead.

Step 3: Validate Object Definitions After Migration or Upgrade

  • If this error surfaced after upgrading to Windows Server 2025 or migrating a database to SQL Server 2025, check all views, computed columns, and constraints using:
  • SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('YourObjectName');
  • Look specifically for aggregates embedded in CHECK constraints or inline table-valued function bodies, as these are common migration breakpoints.

Step 4: Test the Corrected Script in a Isolated Session

  • Open a new query window in SSMS, paste the corrected T-SQL, and execute it against a test/staging database first.
  • Confirm no other nested aggregate violations exist by running SET SHOWPLAN_TEXT ON; before execution to catch parser-level errors before runtime.

Alternative or Verification Steps

  • Re-run the original failing stored procedure, view, or query after applying the fix — Error 5314 should no longer appear, and results should return as expected.
  • If the error persists, use sp_helptext 'ObjectName' to dump the full object definition and manually audit every WHERE, ON, and constraint clause for improperly scoped aggregate calls.

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

Why This Error Happens

Error 5309 occurs because SQL Server’s query optimizer does not allow windowed functions (functions using the OVER() clause, such as ROW_NUMBER(), RANK(), SUM() OVER(), etc.) to be evaluated directly inside WHERE, HAVING, GROUP BY, or ON clauses. This is a T-SQL language restriction, not a server configuration or permissions issue—windowed functions can only be referenced in the SELECT list or the ORDER BY clause. The engine throws this error during query parsing/binding because it cannot logically resolve the window frame before the result set rows are filtered or grouped.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Clause

  • Open the query that triggered Error 5309 in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Look for any OVER() function (e.g., ROW_NUMBER() OVER (PARTITION BY ...)) placed inside a WHERE, HAVING, GROUP BY, or JOIN ... ON clause.
  • Confirm the exact error text: “Windowed functions can only appear in the SELECT or ORDER BY clauses.”

Step 2: Refactor the Query Using a CTE or Subquery

  • Move the windowed function into the SELECT list of an inner query, Common Table Expression (CTE), or derived table.
  • Apply your filtering logic in the outer query against the aliased column instead of the raw function call.
  • Example pattern:
WITH RankedData AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) AS RowNum
    FROM Orders
)
SELECT * FROM RankedData WHERE RowNum = 1;

Step 3: Validate Compatibility Level Settings

  • In SSMS, right-click the database → Properties → Options, and check the “Compatibility Level” field.
  • Ensure the database is running at compatibility level 160 (SQL Server 2022) or higher if using newer windowing syntax enhancements introduced in SQL Server 2025.
  • Run ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170; if an older compatibility level is causing parser conflicts with newer window function syntax.

Step 4: Re-Deploy and Test the Corrected Query

  • Save the revised script and execute it in a test environment first.
  • Check SQL Server error logs (C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) to confirm Error 5309 no longer appears after execution.

Alternative or Verification Steps

  • Run the corrected query with SET SHOWPLAN_TEXT ON; to confirm the execution plan compiles without binding errors before deploying to production.
  • If the error persists in complex nested queries, isolate each OVER() clause into its own CTE layer one at a time to pinpoint exactly which windowed function is misplaced.

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

Troubleshooting Guide: Error 5310 — Aggregates Not Allowed in VALUES List

Why This Error Happens

Error 5310 occurs when a T-SQL INSERT statement contains an aggregate function (such as SUM(), COUNT(), AVG(), MAX(), or MIN()) directly inside the VALUES clause, which SQL Server’s query parser does not permit by design. This is a syntax-level restriction rather than a permissions or configuration issue — the VALUES clause is meant for literal values, variables, or scalar expressions, not set-based aggregate calculations. It typically surfaces after a code migration, an ORM-generated query, or a manually written script where a developer intended to insert a computed summary value but used the wrong INSERT syntax pattern.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Statement

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and locate the exact query from the application log or SQL Profiler/Extended Events trace that raised Error 5310.
  • Look specifically for a pattern like: INSERT INTO TableName (Col1) VALUES (SUM(Col2)).
  • Confirm the aggregate function is positioned inside the VALUES(...) parentheses rather than in a SELECT clause.

Step 2: Rewrite the INSERT Using INSERT…SELECT Syntax

  • Replace the VALUES clause with a SELECT statement that performs the aggregation, since aggregates are valid in SELECT but not in VALUES.
  • Example corrected syntax:
  INSERT INTO TableName (Col1)
  SELECT SUM(Col2) FROM SourceTable WHERE Condition = 1;
  • If you need a single static aggregate result inserted, calculate it first into a variable, then insert the variable:
  DECLARE @Total INT;
  SELECT @Total = SUM(Col2) FROM SourceTable;
  INSERT INTO TableName (Col1) VALUES (@Total);

Step 3: Audit Application Code and Stored Procedures

  • Search stored procedures, triggers, and application data-access layers (Entity Framework, Dapper, or custom ADO.NET code) for dynamically generated INSERT statements.
  • On Windows Server 2025, check SQL Server Agent job steps under SQL Server Management Studio > SQL Server Agent > Jobs for scripts that may contain the same flawed pattern.
  • Update any ORM mapping logic that incorrectly concatenates aggregate functions into insert value lists.

Step 4: Test and Deploy the Fix

  • Run the corrected query in a non-production/staging SQL Server 2025 instance first.
  • Validate that the INSERT...SELECT statement returns the expected row(s) without raising Error 5310.
  • Deploy the corrected script to production once validated, using your standard change-management process.

Alternative or Verification Steps

  • Re-run the original failing transaction or application workflow and confirm Error 5310 no longer appears in the SQL Server Error Log (Management > SQL Server Logs in SSMS) or Windows Event Viewer.
  • If the error persists, enable SQL Server Extended Events to capture the exact query text in real time, as the error may be originating from a different, undocumented stored procedure or dynamic SQL string than initially suspected.

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

Troubleshooting Guide: SQL Server Error 5311 – Invalid Quote Character

Why This Error Happens

Error 5311 occurs when SQL Server 2025 parses a remote server definition, linked server command, or distributed query that contains an unmatched or unsupported quote character (', ", or extended Unicode quote variants) in an identifier or connection string. This is frequently triggered by copy-pasted T-SQL from word processors or web sources that silently convert straight quotes into “smart quotes” (curly quotes), which the SQL parser cannot interpret. It can also happen when a linked server or OPENQUERY command references an object name with inconsistent quoting (mixing single quotes and double quotes incorrectly) or when the collation/code page of the client doesn’t match the server, corrupting the quote character during transmission.

Step-by-Step Resolution Guide

Step 1: Identify and Inspect the Offending Command

  • Locate the exact T-SQL statement referenced in the SQL Server error log or Activity Monitor at the time Error 5311 was raised.
  • Check C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG for the full statement text.
  • Look specifically for linked server calls, sp_addlinkedserver, OPENQUERY, or EXECUTE AT statements.

Step 2: Replace Smart Quotes with Standard ASCII Quotes

  • Open the script in a plain text editor like Notepad or VS Code (avoid Word or rich-text editors).
  • Use Find & Replace to swap curly quotes (’ ‘ “ ”) with straight ASCII equivalents (' and ").
  • Re-run the corrected script directly in SQL Server Management Studio (SSMS) rather than pasting from an external source.

Step 3: Validate Linked Server and Identifier Syntax

  • Confirm that linked server names and four-part object identifiers use consistent bracket or quote delimiters (e.g., [ServerName].[Database].[Schema].[Table]).
  • Run sp_linkedservers to review existing configurations for malformed quoting.
  • Rebuild the linked server definition using EXEC sp_addlinkedserver with explicit, correctly escaped string literals if corruption is suspected.

Step 4: Check Client and Server Collation/Code Page Alignment

  • Verify client driver settings (ODBC/OLE DB) are using UTF-8 or a matching code page to the SQL Server instance.
  • Open SQL Server Configuration Manager > Client Protocols and ensure encoding settings align with server configuration.
  • Restart the SQL Server service after any configuration change via services.msc or net stop MSSQLSERVER && net start MSSQLSERVER.

Alternative or Verification Steps

  • Re-execute the corrected query in SSMS and confirm no Error 5311 appears in the Messages pane or ERRORLOG.
  • If the issue persists, recreate the linked server from scratch using sp_dropserver followed by sp_addlinkedserver, typing all quotes manually rather than copy-pasting to rule out character encoding corruption.

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

Troubleshooting Guide: Error 5306 — “Cursor Parameters Are Not Allowed for Functions”

Why This Error Happens

This error occurs because SQL Server’s T-SQL language specification explicitly prohibits user-defined functions (UDFs) from accepting cursor data types as input parameters. Unlike stored procedures, functions are designed to be deterministic and side-effect-free in most contexts, and cursors inherently manage stateful, row-by-row server-side memory pointers that conflict with this execution model. This typically surfaces when a developer migrates logic from a stored procedure into a scalar or table-valued function without refactoring the cursor-based variable declarations.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Function Definition

  • 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 function throwing the error based on the object name referenced in the error message:
SELECT definition FROM sys.sql_modules 
WHERE object_id = OBJECT_ID('YourFunctionName');
  • Look specifically for DECLARE @VariableName CURSOR within the CREATE FUNCTION block.

Step 2: Refactor the Logic into a Stored Procedure

  • Since functions cannot process cursors as parameters, convert the FUNCTION object type to a PROCEDURE using CREATE OR ALTER PROCEDURE.
  • Move any cursor declarations (e.g., DECLARE cursor_name CURSOR FOR...) into the body of the new stored procedure rather than the parameter list.
  • Update application connection strings or .sqlproj references in Visual Studio 2025 to call EXEC YourNewProcedure instead of SELECT dbo.YourOldFunction().

Step 3: Replace Cursor Logic with Set-Based Alternatives (Recommended)

  • If the business logic must remain in a function (for use in SELECT statements or computed columns), eliminate the cursor entirely.
  • Rewrite the row-by-row iteration using a Table-Valued Parameter (TVP) or a correlated subquery.
  • Example fix: Replace OPEN cursor_name; FETCH NEXT... loops with a CROSS APPLY or JOIN operation against a derived table.

Step 4: Deploy and Validate Permissions

  • Ensure the SQL Server Agent service account on Windows Server 2025 has ALTER permissions on the schema to drop and recreate the object.
  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log to check the ERRORLOG file for any residual compilation caching issues after the change.

Alternative or Verification Steps

  • Verification: Execute sp_helptext 'YourObjectName' to confirm the object type is now a stored procedure (or that the cursor syntax has been fully removed), then run a test execution to ensure the TOTAL_EXECUTION_TIME in Query Store does not return Error 5306.
  • Alternative: If third-party vendor code is generating this error dynamically, apply a trigger-based workaround to capture the required dataset into a temporary table first, then pass that temp table (not a cursor) to the function for processing.

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

Troubleshooting Guide: Error 5307 – Invalid Parameter Specified for sp_cursoropen

Why This Error Happens

Error 5307 occurs when the sp_cursoropen system stored procedure receives an invalid combination of parameters, typically caused by an incorrect cursor type, scroll option, or concurrency setting being passed by the calling application or driver. This often happens after a client library (ODBC/OLE DB) mismatch with SQL Server 2025, or when a legacy application passes deprecated cursor flags that are no longer supported. Corrupted connection strings or outdated database client components on Windows Server 2025 / Windows 11 can also trigger this mismatch between expected and actual parameter values.

Step-by-Step Resolution Guide

Step 1: Verify the Cursor Parameters in the Calling Application

  • Check the application code or query that invokes sp_cursoropen for the cursor type (1 = KEYSET, 2 = DYNAMIC, 4 = FORWARD_ONLY, etc.) and ensure it falls within supported ranges for SQL Server 2025.
  • Confirm that the scrollopt and ccopt bitmask values are not combined incorrectly (e.g., mixing FAST_FORWARD with OPTIMISTIC concurrency flags).
  • Review any ORM-generated queries (Entity Framework, Dapper) that may auto-generate cursor calls with outdated flags.

Step 2: Update SQL Server Native Client and ODBC Drivers

  • Navigate to Control Panel > Programs > Programs and Features on Windows Server 2025 / Windows 11 and check the installed version of “Microsoft ODBC Driver for SQL Server.”
  • Download and install the latest driver from the official Microsoft Download Center to ensure compatibility with SQL Server 2025 cursor APIs.
  • Restart the application pool or service consuming the connection after the driver update.

Step 3: Validate Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to the instance.
  • Run the following query to check the compatibility level of the affected database:
  SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the compatibility level is set below 160 (SQL Server 2022) or an unsupported legacy value, update it using:
  ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 4: Review SQL Server Error Logs for Context

  • Open SQL Server Configuration Manager and locate the ERRORLOG file path (typically C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\).
  • Search for Error 5307 entries and note the exact SPID and query context to identify which application or job triggered the invalid parameter call.
  • Cross-reference the timestamp with any recent deployment or driver update that coincides with the error’s first occurrence.

Alternative or Verification Steps

  • Re-run the failing query or application transaction after applying the driver update and compatibility level change; confirm no Error 5307 appears in the SQL Server ERRORLOG.
  • If the issue persists, use SQL Server Profiler or Extended Events to trace the exact sp_cursoropen call parameters in real-time and compare them against Microsoft’s documented valid parameter ranges for SQL Server 2025.

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

Troubleshooting Guide: SQL Server Error 5308 – Windowed Functions

Why This Error Happens

Error 5308 occurs when a windowed function (such as ROW_NUMBER(), RANK(), LAG(), or LEAD()) is used with an invalid ORDER BY clause or an unsupported frame specification within the OVER() clause. This typically happens when the database compatibility level is set too low to support the specific windowing syntax being used, or when a ROWS/RANGE frame is combined with a function that does not support frame clauses (like LAG or LEAD). Corrupted query plans cached from a previous SQL Server version during an in-place upgrade to SQL Server 2025 can also trigger this error unexpectedly.

Step-by-Step Resolution Guide

Step 1: Verify Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the current compatibility level: SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is below 160 (SQL Server 2022) or 170 (SQL Server 2025), update it using: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 2: Review and Correct the OVER() Clause Syntax

  • Inspect the specific query triggering the error in the SQL Server error log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Ensure that LAG() and LEAD() functions do not include a ROWS BETWEEN or RANGE BETWEEN frame specification, as this is unsupported.
  • Confirm that ORDER BY columns referenced in the windowed function actually exist in the underlying table or CTE and are not ambiguous.

Step 3: Clear the Procedure Cache

  • Corrupted or stale execution plans from a pre-upgrade environment can cause phantom 5308 errors.
  • Run DBCC FREEPROCCACHE; to clear the plan cache for the instance (use with caution in production environments during off-peak hours).
  • Re-execute the failing query to see if a fresh execution plan resolves the parsing error.

Step 4: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and search for the latest Cumulative Update for SQL Server 2025.
  • Download and run the update package on your Windows Server 2025 host.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Alternative or Verification Steps

  • Verify the Fix: Run the query in a new SSMS query window (Ctrl+N) to ensure the parser accepts the syntax without using a cached, broken execution plan.
  • Alternative Workaround: If the error persists specifically with LAG/LEAD, rewrite the logic using a ROW_NUMBER() subquery combined with a self-join to achieve the same lookahead/lookbehind result without triggering the frame specification conflict.

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

Why This Error Happens

This error occurs when SQL Server’s CLR integration engine attempts to apply a mutator method on a User-Defined Type (UDT) and the underlying .NET assembly returns a null reference instead of a valid object instance. This typically stems from a coding flaw in the custom CLR assembly where the Parse() or mutator method fails to properly instantiate the object before returning it. In rare cases, this can also be triggered by a corrupted or mismatched assembly binary that was deployed to SQL Server 2025 after a Windows Server update altered the .NET runtime binding.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Assembly and Type

  • Open SQL Server Management Studio (SSMS) and query sys.assemblies and sys.assembly_types to locate the specific CLR type referenced in the error message (%.*ls).
  • Run the following T-SQL to cross-reference the assembly:
SELECT a.name, t.name AS type_name 
FROM sys.assembly_types t
JOIN sys.assemblies a ON t.assembly_id = a.assembly_id;
  • Note the exact DLL path associated with this assembly for the next step.

Step 2: Audit the Source Code for the Mutator Method

  • Locate the Visual Studio project source for the UDT (usually a .cs file implementing IBinarySerialize).
  • Check the specific mutator method named in the error log; ensure it does not have a code path where the object reference is left uninitialized (e.g., return null; instead of return this;).
  • Recompile the assembly in Visual Studio 2022/2025 ensuring the target framework matches SQL Server 2025 CLR requirements (.NET Framework 4.8 or the updated .NET CLR strict security model).

Step 3: Redeploy the Assembly with UNSAFE Permissions (If Required)

  • If the UDT requires external resource access, verify the assembly permission set in SQL Server.
  • Drop and re-register the corrected assembly using the following commands in SSMS:
DROP ASSEMBLY YourAssemblyName;
GO
CREATE ASSEMBLY YourAssemblyName 
FROM 'C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\YourFile.dll' 
WITH PERMISSION_SET = SAFE;
GO
  • Ensure the file path points to the newly compiled DLL on the Windows Server 2025 host, not a cached or temporary build folder.

Step 4: Clear SQL Server Plan Cache

  • Since SQL Server 2025 caches execution plans for CLR type methods, a stale plan might still reference the old, broken binary logic.
  • Execute DBCC FREEPROCCACHE; to force SQL Server to recompile the execution path using the updated assembly.

Alternative or Verification Steps

  • Verification: Re-run the specific T-SQL transaction or stored procedure that triggered the original Event ID 5303. If the mutator executes without throwing an exception, the object instantiation logic has been successfully patched.
  • Alternative Fix: If recompiling the assembly is not immediately possible, wrap the calling T-SQL logic in a TRY...CATCH block to handle the SqlNullValueException gracefully, preventing the transaction from failing abruptly while you schedule a permanent code fix.

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

Troubleshooting Guide: SQL Server Error 5304 — Bulk Copy ALTER TABLE Permission Failure

Why This Error Happens

This error occurs because the target table of a bulk copy (BCP/BULK INSERT) operation contains one or more triggers or CHECK constraints, and SQL Server requires ALTER TABLE permission on that table to temporarily manage constraint/trigger enforcement during the load. The login or user account executing the bulk operation only has INSERT or SELECT rights, but lacks the elevated ALTER TABLE grant needed when triggers/constraints are present. This is a security-by-design restriction in SQL Server 2025 to prevent unauthorized schema-level manipulation during high-speed data loads.

Step-by-Step Resolution Guide

Step 1: Identify the Executing User and Target Table

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the instance reporting the error.
  • Run SELECT SUSER_SNAME(); to confirm which login triggered the bulk copy operation.
  • Identify the exact table name from the error message (the %.*ls placeholder in Event ID 5304).

Step 2: Grant ALTER TABLE Permission to the User or Role

  • Execute the following T-SQL command, replacing placeholders with your actual values:
  USE [YourDatabaseName];
  GRANT ALTER ON OBJECT::dbo.YourTableName TO [DOMAIN\BulkLoadUser];
  • If multiple tables are affected, consider granting ALTER at the schema level instead:
  GRANT ALTER ON SCHEMA::dbo TO [DOMAIN\BulkLoadUser];
  • Avoid granting db_owner or sysadmin roles solely to resolve this — use least-privilege ALTER grants only.

Step 3: Validate Triggers and Constraints on the Target Table

  • Run the following query to confirm which objects are triggering the permission requirement:
  SELECT name, type_desc FROM sys.triggers WHERE parent_id = OBJECT_ID('dbo.YourTableName');
  SELECT name FROM sys.check_constraints WHERE parent_object_id = OBJECT_ID('dbo.YourTableName');
  • If triggers/constraints are not business-critical for this specific load, consider using the -h "TABLOCK" hint combined with FIRE_TRIGGERS disabled in your BCP command to bypass trigger execution (requires ALTER TABLE regardless, but reduces overhead).

Step 4: Re-run the Bulk Copy Operation

  • From Command Prompt (Windows Server 2025 / Windows 11), re-attempt the BCP command:
  bcp YourDatabaseName.dbo.YourTableName in "C:\Data\import.csv" -S ServerName -T -c
  • Confirm no Error 5304 is thrown and rows are successfully inserted.

Alternative or Verification Steps

  • Verify the fix by querying fn_my_permissions for the affected user: SELECT * FROM fn_my_permissions('dbo.YourTableName', 'OBJECT'); — confirm ALTER now appears in the result set.
  • If granting ALTER TABLE is not permitted by your security policy, an alternative is to temporarily disable the triggers/constraints (ALTER TABLE YourTableName DISABLE TRIGGER ALL;) as a sysadmin before the bulk load, then re-enable them afterward — though this requires admin intervention each time and is not a permanent fix.

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

Troubleshooting Guide: SQL Server Error 5305 — Invalid rowdump/lockres Column Access

Why This Error Happens

This error occurs when a query attempts to select the %%lockres%% or rowdump-style virtual columns against an indexed view without explicitly including the NOEXPAND hint in the query. SQL Server 2025 requires NOEXPAND in these cases because, without it, the query optimizer is free to expand the view definition back into its underlying base tables, making row-locator metadata (like lockres) ambiguous or impossible to resolve. Essentially, the engine cannot guarantee a stable physical row reference unless it is forced to read directly from the materialized indexed view structure.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Locate the T-SQL statement referencing %%lockres%% or rowdump in the SELECT list.
  • Confirm the target object is an indexed view (check sys.views and sys.indexes for a clustered index on the view).
  • Example of a failing query:
  SELECT %%lockres%% FROM dbo.vw_SalesSummary;

Step 2: Add the NOEXPAND Hint to the Query

  • Modify the FROM clause to explicitly include WITH (NOEXPAND) immediately after the view name.
  • Updated query should look like:
  SELECT %%lockres%% 
  FROM dbo.vw_SalesSummary WITH (NOEXPAND);
  • If the query joins multiple objects, ensure NOEXPAND is applied only to the indexed view, not to standard base tables.

Step 3: Validate the Indexed View Still Exists and Is Usable

  • Run the following to confirm the view has a valid clustered index (required for NOEXPAND to work):
  SELECT i.name, i.type_desc 
  FROM sys.indexes i 
  JOIN sys.views v ON i.object_id = v.object_id 
  WHERE v.name = 'vw_SalesSummary';
  • If no clustered index exists, you cannot use NOEXPAND; you will need to create one via CREATE UNIQUE CLUSTERED INDEX on the view first.

Step 4: Update Application Code or Stored Procedures

  • Search application-layer code, ORM-generated queries, and stored procedures for any dynamic SQL hitting this view without the hint.
  • Patch all instances consistently, especially in reporting tools or diagnostic scripts that rely on lockres for row-versioning or conflict detection logic.

Alternative or Verification Steps

  • Re-run the original query with WITH (NOEXPAND) added and confirm Error 5305 no longer appears in SSMS or the application log.
  • If NOEXPAND cannot be used due to application constraints, consider querying the underlying base tables directly instead of the indexed view when lockres/rowdump values are required.

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

Troubleshooting Guide: SQL Server Error 5299 (Query Store Error)

Why This Error Happens

Error 5299 indicates that the Query Store feature has encountered an internal error while attempting to capture, persist, or flush query execution statistics to disk. This typically occurs due to corruption within the Query Store internal tables (located in the user database), insufficient disk space on the volume hosting the database files, or the database reaching its configured Query Store size quota while in a state that prevents cleanup. In rarer cases, this error surfaces when the underlying storage experiences I/O latency spikes or when Query Store metadata becomes inconsistent after an unexpected shutdown or forced failover.

Step-by-Step Resolution Guide

Step 1: Check Query Store Operational State and Disk Space

  • Open SQL Server Management Studio (SSMS) and connect to the affected instance.
  • Run the following query to check the current state: SELECT actual_state_desc, readonly_reason, current_storage_size_mb, max_storage_size_mb FROM sys.database_query_store_options;
  • Verify the volume hosting your .mdf/.ldf files (commonly C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\) has at least 20% free space.
  • If readonly_reason shows a non-zero value (e.g., 65536 indicating size cap reached), proceed to Step 2.

Step 2: Clear or Resize Query Store Data

  • Execute ALTER DATABASE [YourDatabaseName] SET QUERY_STORE CLEAR; to purge existing captured data if corruption or quota is suspected.
  • If clearing doesn’t resolve it, temporarily disable Query Store using ALTER DATABASE [YourDatabaseName] SET QUERY_STORE = OFF;
  • Increase the MAX_STORAGE_SIZE_MB parameter before re-enabling: ALTER DATABASE [YourDatabaseName] SET QUERY_STORE (MAX_STORAGE_SIZE_MB = 2048);
  • Re-enable Query Store: ALTER DATABASE [YourDatabaseName] SET QUERY_STORE = ON;

Step 3: Run Consistency Checks on the Database

  • Execute DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to rule out physical corruption affecting the internal Query Store tables.
  • Review the SQL Server Error Log (via SSMS > Management > SQL Server Logs, or physically at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG) for accompanying stack dumps or I/O warnings referencing the same timestamp as Error 5299.
  • If corruption is confirmed specifically in Query Store internal structures, you may need to drop and recreate Query Store entirely via the CLEAR command in Step 2, as these internal tables are not user-accessible for direct repair.

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

  • Open Services.msc on Windows Server 2025 / Windows 11.
  • Locate SQL Server (MSSQLSERVER) or your named instance.
  • Right-click and select Restart to force Query Store to re-initialize its in-memory state and flush pending writes cleanly.

Alternative or Verification Steps

  • Verify the fix by running SELECT actual_state_desc FROM sys.database_query_store_options; and confirming the state reads READWRITE rather than READONLY or ERROR.
  • If the error persists after all steps, consider migrating Query Store to QUERYCAPTUREMODE = CUSTOM with a lower capture threshold to reduce write volume, or temporarily move the database to SIMPLE recovery mode to rule out transaction log pressure as a contributing factor.

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

Why This Error Happens

This error occurs because the login performing the bulk load operation (via BULK INSERT, bcp, or OPENROWSET(BULK...)) only has INSERT permissions on the target table, but SQL Server requires ALTER TABLE permission whenever the destination table has triggers or check constraints defined on it. SQL Server enforces this because bulk load operations can bypass constraint checks by default, so it validates that the user has elevated rights to ensure data integrity rules aren’t silently skipped. This is a permissions-architecture safeguard, not a corruption or connectivity issue.

Step-by-Step Resolution Guide

Step 1: Confirm the Table Has Triggers or Check Constraints

  • Connect to the target database using SQL Server Management Studio (SSMS) on your Windows Server 2025 / Windows 11 machine.
  • Run SELECT * FROM sys.triggers WHERE parent_id = OBJECT_ID('YourSchema.YourTable');
  • Run SELECT * FROM sys.check_constraints WHERE parent_object_id = OBJECT_ID('YourSchema.YourTable');
  • Confirm at least one row is returned, validating this is the root cause.

Step 2: Grant ALTER Permission to the Login or Role

  • Open a new query window in SSMS connected as sysadmin or db_owner.
  • Execute: GRANT ALTER ON OBJECT::YourSchema.YourTable TO [DOMAIN\YourUser];
  • If multiple users need access, create a custom database role instead:
  • CREATE ROLE BulkLoadOperators;
  • GRANT ALTER ON OBJECT::YourSchema.YourTable TO BulkLoadOperators;
  • ALTER ROLE BulkLoadOperators ADD MEMBER [DOMAIN\YourUser];

Step 3: Alternatively, Use CHECKCONSTRAINTS or FIRETRIGGERS Hints

  • If you cannot grant ALTER TABLE due to security policy, modify your bulk load statement to explicitly fire triggers/constraints, which changes the permission requirement path:
  • BULK INSERT YourTable FROM 'C:\Data\file.csv' WITH (CHECK_CONSTRAINTS, FIRE_TRIGGERS);
  • Note this still requires ALTER TABLE in most configurations — this step is mainly for clarifying intended behavior, not bypassing the permission.

Step 4: Restart the Bulk Load Session

  • Close and reopen the application, bcp command prompt, or SSMS session to ensure the new permission token is refreshed.
  • Re-run the exact bulk load command that previously failed.

Alternative or Verification Steps

  • Verify the fix by running the original BULK INSERT or bcp command again and confirming Error 5301 no longer appears in the SQL Server Error Log (EXEC xp_readerrorlog 0, 1, N'5301';).
  • If granting ALTER TABLE is not permitted by your organization’s security policy, consider temporarily disabling the triggers/constraints (ALTER TABLE YourTable NOCHECK CONSTRAINT ALL;) during the load, then re-enabling and validating data afterward with WITH CHECK CHECK CONSTRAINT ALL;.

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

Why This Error Happens

This error occurs when a Transact-SQL statement attempts to invoke a mutator method on an instance of a CLR user-defined type (UDT)—such as geometry, geography, or a custom CLR type—that currently holds a NULL value. Because mutator methods are designed to modify the internal state of an existing object instance, SQL Server cannot execute the operation if there is no object to begin with. This is typically caused by application logic or T-SQL scripts that fail to initialize the variable (e.g., via STGeomFromText or a constructor) before calling a .Write() or similar mutator method on it.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query

  • Check the SQL Server Error Log or Extended Events session to capture the exact query text associated with Error 5302.
  • Look specifically for CLR data type variables (e.g., DECLARE @g geometry;) followed immediately by a method call.

Step 2: Initialize the Variable Before Calling Mutators

  • Ensure the variable is instantiated using a static method before any mutator is called.
  • Example of the fix in T-SQL:
DECLARE @g geometry = geometry::STGeomFromText('POINT(3 4)', 0);
-- Only call the mutator AFTER initialization
EXEC @g.STBuffer(5); 
  • Do not declare the variable and immediately invoke a mutator without assigning a valid spatial or CLR value first.

Step 3: Audit Application-Side ORM/Data Access Layers

  • If the error originates from an application (e.g., Entity Framework or a custom C# data layer) running on Windows Server 2025, check the data mapping logic.
  • Verify that null-checking logic (if (object != null)) exists in the C# or VB.NET code before serializing data to a CLR UDT column.
  • Look specifically in Program.cs or repository classes where SqlGeography or SqlGeometry objects are populated.

Step 4: Update CLR Assembly and Driver Versions

  • Navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn (adjust version number as needed) and verify the SQL Server CLR integration files are up to date.
  • Apply the latest Cumulative Update (CU) for SQL Server 2025 to rule out a known engine bug in CLR type handling.

Alternative or Verification Steps

  • Verify the Fix: Re-run the specific stored procedure or query in SQL Server Management Studio (SSMS) with SET STATISTICS IO ON to confirm the mutator executes without throwing Error 5302.
  • Alternative Check: If the error persists despite proper initialization, use SELECT @g.IsNull to double-check the state of the variable immediately prior to the mutator call, ensuring no intermediate logic is resetting the object to NULL.

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

Troubleshooting Guide: Error 5296 — Operation Not Supported with Memory Optimized Tables

Why This Error Happens

This error occurs when a maintenance operation such as DBCC CHECKDB, a consistency check, or an index/statistics maintenance task attempts to process a memory-optimized table using a code path that only supports disk-based tables. SQL Server 2025 skips these objects because operations like certain CHECKTABLE validations, physical-only scans, or specific index rebuild commands are not architecturally compatible with the in-memory OLTP engine. This is typically not a failure but an expected limitation, though it can also surface if a maintenance plan or third-party script was not written to filter out memory-optimized objects before execution.

Step-by-Step Resolution Guide

Step 1: Identify the Memory-Optimized Objects Being Skipped

  • Run the following query to list all memory-optimized tables in the affected database:
SELECT name, object_id, is_memory_optimized 
FROM sys.tables 
WHERE is_memory_optimized = 1;
  • Cross-reference the object_id from Error 5296 with this result set to confirm the skipped object is indeed memory-optimized.

Step 2: Adjust DBCC CHECKDB or Maintenance Scripts to Exclude Memory-Optimized Tables

  • If running DBCC CHECKDB, understand that memory-optimized tables are validated separately and automatically; no WITH option is needed to “include” them, but you also cannot force deep physical checks (like PHYSICAL_ONLY) on them.
  • Modify custom maintenance scripts, SQL Agent Jobs, or Ola Hallengren-style scripts to explicitly exclude is_memory_optimized = 1 tables from any index reorganize/rebuild logic, since these commands do not apply to hash or range indexes on memory-optimized tables.
  • For index maintenance, replace ALTER INDEX REBUILD on memory-optimized tables with native memory-optimized maintenance (which is handled internally by the Hekaton engine and garbage collection, not manual rebuilds).

Step 3: Validate Memory-Optimized Filegroup Health Separately

  • Since standard CHECKDB logic skips deep integrity checks on these objects, verify the underlying memory-optimized filegroup container files directly via Windows File Explorer or PowerShell:
Get-ChildItem "C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Data\XTP\" -Recurse
  • Ensure the storage path has sufficient disk space and that Windows Server 2025 permissions grant the SQL Server service account full control over this directory.

Step 4: Update SQL Server 2025 Cumulative Updates

  • Verify you are on the latest Cumulative Update (CU) for SQL Server 2025, as early releases occasionally mis-flag hybrid objects (tables with both disk-based and memory-optimized filegroup dependencies) during maintenance tasks.
  • Check version via:
SELECT @@VERSION;
  • Apply the latest CU from the Microsoft Update Catalog if you are behind, then re-run the maintenance job.

Alternative or Verification Steps

  • Re-run DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; and confirm Error 5296 only appears as an informational skip message (not accompanied by actual corruption errors) for the identified memory-optimized objects.
  • If using a third-party backup/maintenance tool (e.g., for index optimization), check the vendor’s compatibility matrix for SQL Server 2025 In-Memory OLTP and update the tool or exclude the Hekaton-based tables from its scope entirely.

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

Troubleshooting Guide: SQL Server Error 5297 – Cross Rowset Check Failure

Why This Error Happens

Error 5297 occurs when SQL Server’s DBCC CHECKDB detects a consistency mismatch between the clustered columnstore index and a nonclustered index built on the same table, meaning the two structures disagree on which rows exist in the rowset. This typically stems from corrupted index pages caused by abrupt shutdowns, storage subsystem failures, or bugs triggered during concurrent DML operations on columnstore tables. It can also surface after an improper upgrade or migration process where index metadata was not correctly rebuilt for the new SQL Server 2025 columnstore engine.

Step-by-Step Resolution Guide

Step 1: Confirm and Isolate the Corruption

  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to capture the full scope of corruption.
  • Note the specific object ID referenced in the error (%d) using SELECT OBJECT_NAME(object_id) FROM sys.objects WHERE object_id = <ID>;.
  • Check the SQL Server Error Log (default path: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\) for accompanying I/O or storage warnings.

Step 2: Rebuild the Affected Indexes

  • Drop and recreate the nonclustered index rather than using a standard ALTER INDEX REBUILD, since the metadata mismatch often persists through a standard rebuild.
  • Execute: DROP INDEX [IndexName] ON [SchemaName].[TableName];
  • Recreate it: CREATE NONCLUSTERED INDEX [IndexName] ON [SchemaName].[TableName] (ColumnName);
  • If the clustered columnstore index itself is flagged, rebuild it using ALTER INDEX [CCI_Name] ON [TableName] REBUILD;.

Step 3: Run Repair if Rebuild Fails

  • Place the database in single-user mode via SSMS or ALTER DATABASE [YourDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;.
  • Run DBCC CHECKDB ('YourDatabaseName', REPAIR_REBUILD); first, as this is non-destructive.
  • Only escalate to REPAIR_ALLOW_DATA_LOSS if REPAIR_REBUILD does not resolve the Cross Rowset check failure, and ensure a full backup exists beforehand.
  • Return the database to multi-user mode: ALTER DATABASE [YourDatabaseName] SET MULTI_USER;.

Step 4: Validate Underlying Storage Health

  • On Windows Server 2025 / Windows 11, open Event Viewer (eventvwr.msc) and check the System log under “Disk” and “Ntfs” sources for hardware-level I/O errors.
  • Run chkdsk C: /f /r (or the relevant data drive) during a maintenance window to rule out physical disk corruption as the root cause.

Alternative or Verification Steps

  • Re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; after remediation to confirm Error 5297 no longer appears and the index structures report zero allocation errors.
  • If corruption recurs frequently on the same table, restore from the most recent clean backup instead of repeated repairs, as this indicates an unresolved underlying storage or memory hardware issue.

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

Troubleshooting Guide: SQL Server Error 5298 – Tombstone State Rowset

Why This Error Happens

This error occurs when a page in a database is tied to a rowset that has been marked for deletion (tombstoned) but has not yet been physically removed by the ghost cleanup or deallocation process. It typically results from an interrupted or corrupted deallocation transaction, often triggered by abrupt server shutdowns, storage-level corruption, or concurrent DDL operations (like index drops or truncates) conflicting with active transactions. In rare cases, it indicates underlying disk corruption or an inconsistency in the allocation metadata (IAM/PFS pages).

Step-by-Step Resolution Guide

Step 1: Verify Database Consistency

  • Open SQL Server Management Studio (SSMS) or a query window connected via sqlcmd.
  • Run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; to identify the scope of corruption.
  • Note the specific Page ID (%S_PGID) and Object ID referenced in the error output to confirm which table or index is affected.

Step 2: Isolate and Clear the Ghost Cleanup Backlog

  • Check if the Ghost Cleanup task is stalled by querying sys.dm_db_index_physical_stats for high ghost_record_count values.
  • Restart the SQL Server service to force a re-initialization of the background cleanup tasks:
  • Open Services.msc on Windows Server 2025/Windows 11.
  • Locate SQL Server (MSSQLSERVER), right-click, and select Restart.
  • If the issue persists, manually trigger cleanup by running DBCC FORCEGHOSTCLEANUP (YourDatabaseID); (use with caution in production).

Step 3: Repair the Corrupted Table or Index

  • If DBCC CHECKDB confirms the tombstone state is linked to physical corruption, take the specific table offline if possible.
  • Run DBCC CHECKTABLE ('TableName', REPAIR_REBUILD); to attempt a non-destructive repair.
  • If the rowset remains inaccessible, drop and recreate the specific non-clustered index associated with the Page ID using DROP INDEX followed by CREATE INDEX.

Step 4: Restore From a Clean Backup (If Repair Fails)

  • Navigate to your backup storage location (e.g., C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Backup\).
  • Perform a RESTORE DATABASE [YourDatabaseName] FROM DISK = 'BackupPath.bak' WITH REPLACE; using the last known good backup prior to the error.
  • Apply transaction log backups sequentially to minimize data loss up to the point of failure.

Alternative or Verification Steps

  • Verification: Re-run DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS; after the repair; a clean result with “0 allocation errors and 0 consistency errors” confirms the fix.
  • Alternative: If corruption recurs frequently, run the Windows Memory Diagnostic Tool and check the Event Viewer’s System logs for underlying Disk I/O errors (Event ID 51 or 153), as faulty storage hardware is a common root cause of recurring tombstone errors.