Backup & Restore Script with a Move

Ok, I’ll admit it. I like scripts that are handy and do things.  Especially if the scripts make my life easier.

Now, not every environment is the same.  Instances get configured differently or things change just due to the nature of the business.  In a previous life I would routinely have to backup a database and restore it to another server.  However, the server I was using to restore to had a different drive configuration.  It happens.  Anyway, I wanted a script that would give me

  • A backup statement
  • A restore statement with the appropriate MOVE switch

This would allow me to easily execute the backup statement and then on the target server execute the restore statement.  Since the restore statement already had the appropriate MOVE switch provided, I didn’t have to manually compose the statement.

First, we will declare some variables just to make things a little cleaner and easier

Next, we’ll use a CTE to get the database name(s) and the file paths.  The CTE is what does the work to create the MOVE switch.

The CTE is now populated with the statement that has the MOVE switch.  We can now do another SELECT from sys.databases with an INNER JOIN to the CTE.

You can adjust the WHERE clause for just a single database or multiple.  Of course, you would want to adjust all of the UNC path statements for your particular environment.

You can download the entire script here.

Enjoy!

© 2018, John Morehouse. All rights reserved.

One Reply to “Backup & Restore Script with a Move”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.