Generate Restoration Script For Multiple Databases 1709698444

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Srinivas Merugu

www.linkedin.com/in/srinivas-merugu-dba-azure

Script to generate Restoration script for multiple databases


1. Take the database backups & file name as DBNAME.bak and note the location.
2. Open new query window in source server and generate restoration script.
It will generate script only and it will not any harmful.
We need modify the script as per our requirement.
a. Provide backup path where you want restore from
b. Update target server data and Log file locations to keep the files (Source and target
server drive letters may or may not be same.)
c. In target server, If database exist then keep database is in single_user statement
d. If Databases are not exist in target server then remove below code from main script.

SELECT 'Alter database ['+ name+'] set Single_User with rollback immediate;'+

e. Script will generate restoration script for all Database except system Databases.
f. If need to generate restoration script for specific databases then mention database name
in last line code.
WHERE d.name in ('DBName1’,’DBName2’,………) --LIKE '%DatabaseName%'

Use master
go
DECLARE @date CHAR(8)
SET @date = (SELECT CONVERT(char(8), GETDATE(), 112))

DECLARE @path VARCHAR(125)


SET @path = '\\Backup_Path\' -- Provide the backup path here

;WITH MoveCmdCTE ( DatabaseName, MoveCmd )


AS ( SELECT DISTINCT
DB_NAME(database_id) ,
STUFF((SELECT ' ' + CHAR(13)+', MOVE ''' + name + ''''
+ CASE Type
WHEN 0 THEN ' TO ''M:\SQLData\' -- Provide SQL Data File Path here
ELSE ' TO ''N:\SQLLogs\' ---- Provide SQL Log File Path here
END
+ REVERSE(LEFT(REVERSE(physical_name),
CHARINDEX('\',
REVERSE(physical_name),
1) - 1)) + ''''
FROM sys.master_files sm1
WHERE sm1.database_id = sm2.database_ID
FOR XML PATH('') ,
TYPE).value('.', 'varchar(max)'), 1, 1, '') AS MoveCmd
FROM sys.master_files sm2
)

SELECT 'Alter database ['+ name+'] set Single_User with rollback immediate;'+
Srinivas Merugu
www.linkedin.com/in/srinivas-merugu-dba-azure

' RESTORE DATABASE ['+ name + '] FROM DISK = ''' + @path + '' + name + '.bak'' WITH FILE
= 1 '+movecmdCTE.MoveCmd
+', RECOVERY, REPLACE, STATS=5,buffercount=600;'+
'Alter database ['+ name+'] set Multi_User ;'

FROM sys.databases d
INNER JOIN MoveCMDCTE ON d.name = movecmdcte.databasename
WHERE d.name not in ('master','model','msdb','tempdb','distribution') --LIKE
'%DatabaseName%'
GO

3. Run generated script in target server.

You might also like