SQL Server, How to automate a database restore
Hi Guys,
Today a little but (i hope) useful post!
Automate a database restore
RESTORE DATABASE database FROM DISK = 'nomefile' WITH REPLACE
However, sometimes the backup is created by adding the date, for example, to the name. Suppose having a production database (product_db) and a test database (test_db)
We want to align the data into the test database with the data in the production database.
What we need is the name of the last backup we have done in the production database.
Et voilà!
Now we are ready to create our script.
I will store the name of the backup in the backup_name variable:
I use the following query to retrieve the backup_name:DECLARE @backup_name varchar(80)
Now we can execute the restore command (on the test_db)SELECT top 1 @backup_name = mf.physical_device_name FROM msdb.dbo.backupset b JOIN msdb.dbo.backupmediafamily mf ON b.media_set_id = mf.media_set_id WHERE b.database_name = 'product_db' AND b.type = 'D' AND device_type = 2 ORDER BY backup_set_id DESC
ALTER DATABASE [test_db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE test_db FROM DISK = @backup_name WITH REPLACE
ALTER DATABASE [test_db] SET MULTI_USER
CREATE PROCEDURE AutoRestore AS BEGIN DECLARE @backup_name varchar(80) SELECT top 1 @backup_name = mf.physical_device_name FROM msdb.dbo.backupset b JOIN msdb.dbo.backupmediafamily mf ON b.media_set_id = mf.media_set_id WHERE b.database_name = 'production_db' AND b.type = 'D' AND device_type = 2 ORDER BY backup_set_id DESC ALTER DATABASE [test_db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE RESTORE DATABASE test_db FROM DISK = @backup_name WITH REPLACE ALTER DATABASE [test_db] SET MULTI_USER END
Now it is very simple to schedule a SQL Server JOB that will execute out procedure...
And remember, if you find an advertisement that genuinely interests you simply click it from on my blog, please. You will help me to contine writing more and more interesting content.
~Luke

Comments
Post a Comment