Troubleshooting Guide: SQL Server Error 5159
Why This Error Happens
Error 5159 occurs when the SQL Server service account lacks the necessary file system permissions to read, write, or create a database file (MDF, NDF, or LDF) at the specified path. This can also result from the underlying disk or volume being offline, disconnected, or experiencing a hardware-level I/O failure. Additionally, antivirus software or Windows file locking mechanisms may be intercepting the operating system call before SQL Server can complete the operation.
Step-by-Step Resolution Guide
Step 1: Verify File and Folder Permissions
- Navigate to the folder containing the database file (commonly
C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\). - Right-click the folder, select Properties > Security, and confirm the SQL Server service account (e.g.,
NT Service\MSSQLSERVER) has Full Control. - If missing, click Edit, add the service account, and grant Full Control permissions, then click Apply.
Step 2: Confirm the Disk Volume Is Online and Healthy
- Open Disk Management (
diskmgmt.msc) on Windows Server 2025 / Windows 11. - Check that the volume hosting the database file shows a status of Online and Healthy.
- If the disk shows Offline or Unknown, right-click the disk and select Online, then run
chkdsk C: /ffrom an elevated Command Prompt to repair file system errors.
Step 3: Exclude SQL Server Directories from Antivirus Scanning
- Open Windows Security or your third-party antivirus console.
- Add exclusions for the SQL Server data, log, and backup directories (e.g.,
C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\*.mdf,*.ldf,*.ndf). - Restart the SQL Server (MSSQLSERVER) service via
services.mscto apply the changes.
Step 4: Check for File Locks or Orphaned Handles
- Use Process Explorer (Sysinternals) to search for any process holding a lock on the affected
.mdfor.ldffile. - Terminate any non-SQL process holding the handle, or reboot the server if the lock cannot be released safely.
- Attempt to bring the database back online using
ALTER DATABASE [YourDB] SET ONLINE;in SQL Server Management Studio (SSMS).
Step 5: Validate SQL Server Service Account Configuration
- Open SQL Server Configuration Manager, select SQL Server Services, and confirm the correct service account is configured under the Log On tab.
- If the account was recently changed (e.g., from Local System to a domain account), ensure it has been re-granted NTFS permissions on the data/log directories as described in Step 1.
- Restart the SQL Server service for changes to take effect.
Alternative or Verification Steps
- Run
sqlcmd -S localhost -Q "DBCC CHECKDB('YourDatabase')"to confirm the database is accessible and free of corruption after applying the fix. - If the issue persists, restore the affected database file from the most recent backup to a healthy volume and reattach it using
CREATE DATABASE [YourDB] ON (FILENAME = 'NewPath\YourDB.mdf') FOR ATTACH;.