Monday, April 6, 2020

Restoring multiple databases via script

Hi Guys,
Hope you are having fun with SQL as usual.
I have developed a script which I thought may be useful to the community least they need to restore huge number of databases from backups without using any enteprise restore software.

Script is broken into two major parts
1. Getting the names of the databases that needs to be restored.
2. Getting the restore script for the databases in question

Now let's delve into the Scripts.
1. Names of the Databases 
Here in this example I am restoring the databases in offline mode. Just a scenario we can use this to be any scenario.

DECLARE @db_row INT
SELECT @db_row=COUNT(name) FROM sys.databases where state_desc<>'online';
DECLARE @res_script varchar(max)

SELECT TOP (@db_row) b.database_name,physical_device_name,b.type,b.backup_start_date
INTO #backup_tab
FROM msdb..backupset b
join msdb..backupmediafamily f on f.media_set_id=b.media_set_id and type ='d'
AND database_name IN (select name from sys.databases where state_desc<>'online')
order by b.backup_start_date DESC

Now we have the information of the backup set of the databases in question. Now let's move on to the next part of the query.

2. Restore Script
Here we use a cursor. I personally do not like them but for this time I thought it will be easy to use a cursor. I will try in future to write it without a cursor.

DECLARE @dbname sysname, @backpath nvarchar(260)
DECLARE rest_cur CURSOR FOR
SELECT database_name FROM #backup_tab ORDER BY 1

OPEN rest_cur
FETCH NEXT FROM rest_cur INTO @dbname
WHILE @@FETCH_STATUS=0
BEGIN
SELECT @backpath=physical_device_name FROM #backup_tab WHERE database_name=@dbname
SELECT @res_script=''

SELECT @res_script= 'RESTORE database [' + @dbname + '] from disk ='+'''' + @backpath+''''

SELECT  @res_script=@res_script+ ' WITH '

SELECT @res_script=@res_script+' move '''+name+''' ' + 'to ''' +physical_name+''','
FROM sys.master_files
WHERE 1=1
AND database_id=DB_ID(@dbname)

SELECT @res_script=@res_script+ 'stats=1 ,replace'

print @res_script
--EXEC(@res_script)
FETCH NEXT FROM rest_cur INTO @dbname

END
CLOSE rest_cur
DEALLOCATE rest_cur

DROP TABLE #backup_tab

It's one of my hot favourite scripts in a disaster recovery scenario. Hope you guys liked it.

Here is the link to the script file


Thanks,
Tushar

No comments:

Post a Comment