12 Aug 2024

How I attach the non detach sql data file and restore my database?

 To attach a non-detached SQL Server data file (.mdf) and restore your database, you can use SQL Server Management Studio (SSMS) or T-SQL commands. Here’s how you can do it:

Using SQL Server Management Studio (SSMS)

  1. Open SSMS: Connect to your SQL Server instance.
  2. Attach Database:
    • Right-click on Databases in the Object Explorer.
    • Select Attach.
    • In the Attach Databases dialog, click Add.
    • Browse and select your .mdf file.
    • If there is no .ldf (log file), SQL Server will create a new one.
    • Click OK to attach the database.

Using T-SQL

If you want to do it via a script, you can use the CREATE DATABASE ... FOR ATTACH statement. Here’s a basic example:

sql

CREATE DATABASE [YourDatabaseName] ON (FILENAME = 'C:\Path\To\Your\file.mdf') FOR ATTACH;

If you don’t have the .ldf file, you can attach the database with the FOR ATTACH_REBUILD_LOG option, which will create a new log file:

sql

CREATE DATABASE [YourDatabaseName] ON (FILENAME = 'C:\Path\To\Your\file.mdf') FOR ATTACH_REBUILD_LOG;

Considerations

  • Ensure that the SQL Server service account has the necessary permissions to access the .mdf file.
  • Attaching a non-detached database might cause data loss if the .ldf file is missing or corrupted, as a new log file will be generated.

No comments:

Post a Comment

SQL Server Copilot AI

 Here are some of the latest tips and advanced concepts for Microsoft SQL Server (MS SQL) in 2024: 1. SQL Server Copilot AI Microsoft has in...