When we copy a database down from production, we make a backup of the database, zip it up and copy the backup down. Then we have to restore using the SQL Server GUI, which involves navigating through several menus and windows. As far as I know, you can not do this with SQL Server’s built in stored procedures because you may not know the logical filename of the database (which is required to restore). So doing this via query consists of the following:
RESTORE FILELISTONLY
FROM DISK = 'C:\backup_of_production_database.bak'
GO
The above provides the logical file names from the backup file, you then have to use these logical names in the next query…
RESTORE DATABASE NewDevelopmentDatabase
FROM DISK = 'C:\backup_of_production_database.bak'
WITH MOVE 'YourMDFLogicalName' TO 'C:\mssql\data\DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'C:\mssql\data\DataYourLDFFile.mdf'
As you can see this seems inefficient because you must manually enter the logical file names into the next query.
You can find my solution to this problem as an answer below.
The solution:
Using various resources I came up with the below stored procedure that lets you cut down this restore into one step. I hope it proves as useful to others as it has been to myself.
I’m sure a few things about this query can be improved, however I already wasted enough time just trying to come to this solution. Regardless I’d love to hear some feedback. I hope that others find this useful!