Search code examples
sql-serverdatabaserestoredetach

SQL Server restore a detach database


Is it possible to restore a detached database (no re-attachement)?

There is a big database, but no diskspace is available to create a backup. So, I was thinking to detach the database, copy it to another server.

This other server uses powershell scripts to restore the database. Will this work with a detached database? I cannot re-attach it with this script. Just restore.

Restore-SqlDatabase -ServerInstance $serverInstance -Database $myDb -BackupFile "detachedFile" -Credential $Cred


Solution

  • Backup of a database is different format (.bak). The files you get in the detach operation: mdf, ndf data file format , ldf log file format are different formats.

    You can read about the formats. I have put the content below from the site for easier reference.

    Usually, database backup files with .bak extension contain data in the standard Microsoft Tape Format (MTF) used by Microsoft itself as well as many backup tools for the Microsoft Windows platform.

    Microsoft Tape Format is used while writing and reading data to and from removable storage devices during storage management or data protection operations such as data transfers, copies, backup and restore. In the case of SQL Server, MTF files contain data and log information (MDF and LDF files) necessary for restoring the database. The MDF file is the Main Data File or primary database data file, that binds all other files in that database together. The LDF is the Log Data File and it contains all log information and is crucial for a database restore process.

    You cannot use Restore database command against mdf,ldf files. You need to use attach, detach approach for them to be available in another environment. As @Peter Smith suggested, you can use the powershell scripts to do the same.