SQL Server Restore Database Script with MOVE

Restoring a SQL Server database to a different server or folder fails when the file paths recorded in the backup do not exist on the target. The MOVE option of RESTORE DATABASE redirects each data and log file to a path you choose, and this script builds that statement from four variables so it can be previewed before it runs.

Purpose and Overview

A production backup carries the physical paths of every file it contains. Restore it onto a development box, a rebuilt server or an instance installed on another drive, and SQL Server tries to write the files back to paths that are not there. The restore stops before any data is written. MOVE fixes this by mapping each logical file name in the backup to a new physical path on the target.

This script wraps RESTORE DATABASE in dynamic SQL. The database name, the backup file and the target folder are set once at the top, and placeholder tokens in a statement template are replaced with those values. A debug flag prints the finished statement instead of running it, so the paths can be read and checked before SQL Server touches a file.

The output is either the printed RESTORE statement (debug on) or the restore itself, with a progress message every 5 percent.

Code Breakdown

The complete script is below, followed by an explanation of each part.

 1USE master;
 2GO
 3
 4DECLARE @restoreStatement NVARCHAR(4000) = N'';
 5DECLARE @databaseName     SYSNAME        = N'YourDatabaseName';      -- Set your database name
 6DECLARE @backupFilePath   NVARCHAR(2000) = N'C:\Backups\YourDatabaseName.bak'; -- Set your backup file path
 7DECLARE @serverPath       NVARCHAR(2000) = N'C:\Program Files\Microsoft SQL Server\MSSQL\DATA\'; -- Set target data folder
 8DECLARE @debug            BIT = 1; -- Set to 0 to execute, 1 to preview only
 9
10SET @restoreStatement = N'
11RESTORE DATABASE [@databaseName] FROM DISK = N''@backupFilePath''
12WITH  FILE = 1,
13      MOVE N''@databaseName_Data'' TO N''@serverPath@databaseName_Data.mdf'',
14      MOVE N''@databaseName_Log''  TO N''@serverPath@databaseName_Log.ldf'',
15      NOUNLOAD,
16      STATS = 5';
17
18SET @restoreStatement = REPLACE(@restoreStatement, '@databaseName',   @databaseName);
19SET @restoreStatement = REPLACE(@restoreStatement, '@backupFilePath', @backupFilePath);
20SET @restoreStatement = REPLACE(@restoreStatement, '@serverPath',     @serverPath);
21
22IF @debug = 1 PRINT(@restoreStatement)
23ELSE EXEC sp_executesql @restoreStatement;
24GO

USE master

The script switches to master first. A database cannot be restored while a session is using it, and running the restore from master keeps the current connection out of the way.

Variable Declarations

Four variables control the restore:

  • @databaseName is the database to restore. It also forms the logical file names in the MOVE clauses.
  • @backupFilePath is the full path to the .bak file.
  • @serverPath is the folder the data and log files will be written to. It must exist, and the SQL Server service account must be able to write to it.
  • @debug set to 1 prints the generated statement; set to 0 it runs the restore.

Building the Restore Statement

The statement is held as a template in @restoreStatement, with tokens (@databaseName, @backupFilePath, @serverPath) in place of real values. FILE = 1 restores the first backup set in the file, which matters when several backups were appended to the same .bak.

The two MOVE clauses assume logical names of <database>_Data and <database>_Log. That is the pattern of the AdventureWorks sample backups the script was first written against. Many databases use other logical names, so the MOVE lines usually need editing after a look at RESTORE FILELISTONLY (see Practical Tips).

STATS = 5 prints a progress message every 5 percent, which shows a long restore is still moving.

Token Replacement

Three REPLACE calls swap the tokens for the variable values. @databaseName appears several times in the template, in the database name and inside each logical and physical file name, and a single REPLACE changes every occurrence.

Debug Flag and Execution

With @debug = 1, PRINT writes the finished statement to the Messages tab. With @debug = 0, sp_executesql runs it. Because every value comes from the DBA running the script rather than from user input, string building is acceptable here; the same pattern must never be fed values from an application.

Key Benefits and Use Cases

  • Cross-server restores — move a production backup onto a development or staging server whose drive layout is different.
  • Non-default installations — restore onto an instance installed to another drive or a named-instance folder, where the original data path does not exist.
  • Separating data and log drives — point the .mdf and .ldf at different volumes as you restore.
  • Repeatable refreshes — keep one script per environment and change only the variables for each refresh.
  • Safe review — the debug flag shows the exact statement before anything is written, which catches a wrong path or database name early.

Performance Considerations

  • Disk throughput sets the pace: reading the .bak and writing the data and log files are the bulk of the work, so a backup on a slow network share restores more slowly than one on local disk.
  • Free space on the target: the restored files are created at the size they had in the source database, so check the target volumes have room before starting.
  • Progress messages in jobs: in a SQL Server Agent job, STATS = 5 writes twenty messages to the job history; STATS = 10 halves that.
  • Recovery at the end: without NORECOVERY, the restore recovers the database and brings it online. If differential or log backups still need to be applied, add NORECOVERY to the WITH list.

Practical Tips

  • Read the logical names first — run RESTORE FILELISTONLY against the backup and copy the LogicalName values into the MOVE clauses:
1-- Discover the logical file names stored in the backup
2RESTORE FILELISTONLY
3FROM DISK = N'C:\Backups\YourDatabaseName.bak';
  • One MOVE per file — a database with secondary .ndf files or more than one log file needs a MOVE line for every row RESTORE FILELISTONLY returns.
  • Preview before running — leave @debug = 1 for the first run and read the printed statement before switching to 0.
  • Create the folder in advance — make sure the @serverPath folder exists and the service account has write permission on it.
  • Restore a copy under a new name — set @databaseName to the new name only if the logical names in the MOVE lines are edited to the names in the backup; the logical names come from the backup, while the database name and the physical file names are whatever you choose. This is how a second copy of a database is made on the same instance without touching the original.
  • Overwriting an existing database — RESTORE refuses to overwrite a database that differs from the one in the backup unless REPLACE is added to the WITH list. Add it only when the database being replaced is definitely no longer needed.
  • Named instances — the default data folder on a named instance includes the instance folder, for example C:\Program Files\Microsoft SQL Server\MSSQL16.INSTANCENAME\MSSQL\DATA\; set @serverPath to match.

Conclusion

MOVE is what makes a backup portable between servers whose folder layouts differ. Wrapping it in dynamic SQL with a preview flag turns a one-off restore into a repeatable step: check the logical names with RESTORE FILELISTONLY, set four variables, read the printed statement, then run it. It belongs next to the backup and restore-chain scripts in any DBA toolkit.

References

Posts in this series