Tuesday, March 24, 2026

How to create a database using an MDF file in SQL Server?

 We can create (attach) a database from an .mdf file using this SQL query:

CREATE DATABASE YourDatabaseName
ON (FILENAME = 'D:\p\App_Data\aspnet-test-20260324025607.mdf')
FOR ATTACH_REBUILD_LOG;

Alternative (using SSMS)

  1. Open SSMS
  2. Right click Databases
  3. Click Attach
  4. Select the .mdf file
  5. Click OK
Error: Msg 5120, Level 16, State 101, Line 1 Unable to open the physical file "D:\p\App_Data\aspnet-test-20260324025607.mdf". Operating system error 5: "5(Access is denied.)". Msg 1802, Level 16, State 7, Line 1 CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

Solution: 

Fix (100% working solution)

Step 1: Give folder permissions

Go to:

D:\p\App_Data

Do this:

  1. Right click → Properties
  2. Go to Security tab
  3. Click Edit
  4. Click Add

Add this user:

Everyone
  1. Select Everyone
  2. Enable:
    • Full Control (Check)
  3. Click Apply → OK