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

Troubleshooting Guide: SQL Server Error 5002 – Database Does Not Exist

Why This Error Happens

Error 5002 occurs when SQL Server cannot locate the specified database within the sys.databases system catalog, typically because the database name was misspelled, the database was detached or dropped, or the connection context is pointing to the wrong SQL Server instance. This can also happen if the database exists but is in a suspect, offline, or restoring state, which can cause it to momentarily disappear from accessible catalog views. In some cases, case-sensitivity settings on the server collation cause a correctly-spelled name to fail validation.

Step-by-Step Resolution Guide

Step 1: Verify the Database Name and Instance Context

  • Open SQL Server Management Studio (SSMS) or Azure Data Studio and connect to the correct instance (e.g., SERVERNAME\INSTANCENAME).
  • Run the query: SELECT name, state_desc FROM sys.databases; to get the exact, case-sensitive name and current status.
  • Check your connection string or application config file (e.g., web.config or appsettings.json) for typos in the Initial Catalog or Database parameter.

Step 2: Check Database State and File Integrity

  • If the database appears in the list but shows SUSPECT or RECOVERY_PENDING, navigate to C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\DATA\ to confirm the .mdf and .ldf files exist and are not zero-byte.
  • Run DBCC CHECKDB('YourDatabaseName') to check for corruption if the database is online but inaccessible.
  • If the files are missing, restore the latest backup using RESTORE DATABASE [YourDB] FROM DISK = 'C:\Backups\YourDB.bak' WITH RECOVERY;.

Step 3: Re-attach or Restore the Database

  • If the database was accidentally detached, use CREATE DATABASE [YourDB] ON (FILENAME = 'C:\Data\YourDB.mdf') FOR ATTACH; to bring it back online.
  • Ensure the SQL Server service account (e.g., NT Service\MSSQLSERVER) has Read/Write permissions on the folder via Windows 11/Server 2025 File Explorer security tab.
  • Restart the SQL Server service using services.msc or net start MSSQLSERVER to refresh the metadata cache.

Alternative or Verification Steps

  • Verify: Re-run the original query or application request; if successful, check sys.databases again to ensure the state_desc column reads ONLINE.
  • Alternative: If the database is permanently lost, restore the full backup chain (Full + Differential + Log) onto a new instance to recover the data and re-point the application connection string.