If you have both .MDF and .LDF files and these files are shutdown properly, then you can attach the .MDF/.LDF files to SQL Server easily, as follows:
-
- Attach using SQL Server Management Studio:
- Start SQL Server Management Studio and connect to the server.
- Expand the instance, right-click Databases and click Attach.
- Follow the instructions in the Attach Databases dialog box to attach the .MDF/.LDF files to SQL Server.
You can get more detailed info at :
https://docs.microsoft.com/en-us/sql/relational-databases/databases/attach-a-database?view=sql-server-ver15 - Attach using SQL query:
- Start SQL Server Management Studio and connect to the server.
- Click New Query.
- Input the following command:
sp_attach_db 'MyDB', 'C:MyDB_Data.mdf', 'C:MyDB_Log.ldf' or CREATE DATABASE MyDB ON (FILENAME = 'C:MyDB_Data.mdf'), (FILENAME = 'C:MyDB_Log.ldf') FOR ATTACH;
Here, MyDB is the database name, C:MyDB_Data.mdf is the mdf file path, and C:MyDB_Log.ldf is the ldf file path.
Microsoft recommends to use the second methods as the first method may retire in the new SQL Server versions.
- Click Execute to execute the query.
You can also get more detailed info at :
https://docs.microsoft.com/en-us/sql/relational-databases/databases/attach-a-database?view=sql-server-ver15
- Attach using SQL Server Management Studio:
However, if your .MDF file and .LDF file is not shutdown properly. Or in other word, they are corrupt, then you need to use another method to attach them.