sql-servermdf

How to attach a database by mdf file that has not been detached


Issue:

OS hard disk was broke before DB backing up, the original .mdf and .ldf files can be transferred but those .mdf and .ldf files can not be attached by SQL Server Management Studio directly.


Solution

  • Solution:

    Assuming the DB name is ‘Sample’ and DB files path is ‘D:\DB’

    Step 1: Open Microsoft SQL Server Management Studio to create a New Database with Database name: Sample Path: D:\DB

    Step2: Stop the DB Server

    Step3: Delete Sample.mdf and Sample.ldf files from folder D:\DB

    Step4: Copy the old Sample.mdf to the folder D:\DB

    Step5: Start the DB Server

    Step6: execute the following sql to detach DB

    exec sp_detach_db Sample,'true'

    Step7: execute the following sql to attach DB and then refresh

    exec sp_attach_single_file_db 'Sample','D:/DB/Sample.mdf'