Troubleshooting Guide: SQL Server Error 5172 — Invalid Database File Header
Why This Error Happens
Error 5172 occurs when SQL Server reads the header of a .mdf or .ndf file and finds that it does not match the expected database file structure, typically because the file was truncated, copied incorrectly, or corrupted due to a storage failure or improper shutdown. This can also happen if the file was renamed, edited outside of SQL Server, or affected by antivirus/backup software locking or modifying it mid-write. In some cases, the header mismatch results from attempting to attach a file created by an incompatible or newer version of SQL Server.
Step-by-Step Resolution Guide
Step 1: Verify the File Integrity and Source
- Confirm the
.mdf/.ndffile was not copied while SQL Server was still writing to it (use a clean copy taken after a graceful shutdown). - Check the file size in File Explorer or via
Get-ItemPropertyin PowerShell — a 0 KB or unusually small file indicates truncation/corruption. - Review Windows Event Viewer (Windows Logs > Application) for related disk or storage errors (Event ID 7, 9, or 51) that may indicate hardware-level corruption.
Step 2: Attempt to Reattach the Database Using T-SQL
- Open SQL Server Management Studio (SSMS) and run:
EXEC sp_detach_db 'YourDatabaseName';
- Then try reattaching with:
CREATE DATABASE YourDatabaseName
ON (FILENAME = 'C:\SQLData\YourDatabaseName.mdf')
FOR ATTACH;
- If the error persists, this confirms the header is genuinely unreadable rather than a locking issue.
Step 3: Restore From the Last Known Good Backup
- Navigate to your backup repository (commonly
C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Backup\). - Run a restore using:
RESTORE DATABASE YourDatabaseName
FROM DISK = 'C:\SQLData\Backup\YourDatabaseName.bak'
WITH REPLACE;
- Ensure the SQL Server Service Account has Read/Write permissions on the backup folder (right-click folder > Properties > Security tab).
Step 4: Rebuild Database Using Emergency Mode (If No Backup Exists)
- Set the database to emergency mode to attempt data recovery:
ALTER DATABASE YourDatabaseName SET EMERGENCY;
DBCC CHECKDB('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);
- Note this step is a last resort, as
REPAIR_ALLOW_DATA_LOSSmay result in permanent loss of unrecoverable pages.
Alternative or Verification Steps
- After reattaching or restoring, run
DBCC CHECKDB('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;to confirm there are no further consistency errors. - If corruption persists, use a disk-level tool (e.g., CHKDSK on Windows Server 2025) to rule out underlying storage/filesystem issues before retrying the SQL Server attach process.