June 23, 2015 08:13 by
Peter
On one of my servers we had to recover ten databases using last night's full backup and all subsequent log backups. Therefore within the middle of the night it had been about to be huge challenge to manually choose each log backup file to restore. So wrote this script to create commands to restore log backup files which can be then run in an exceedingly query window. Please follow the steps below to use the script.
1. Set the database name to the variable @dbname
2. Copy all the transaction log backups to a new directory. You'll prefer to begin copying the files. That were taken a couple of minutes before the full backup was taken. You'll choose to copy the last file you wish to be restored based on the recovery point of your time.
3. In the following line set the directory where you copied the log backup files to.
insert into #dir
exec xp_cmdshell 'dir "C:\Backup\Adventure*.trn" /b'
4. The below code will set the directory to where the log backup files have been copied.
SET @cmd='use master; RESTORE LOG ['+@dbname+'] FROM DISK =
N''C:\Backup\'+@filename+''' WITH FILE = 1, NORECOVERY, NOUNLOAD, STATS = 10'
select (@cmd)
5. Now, Copy the output which should have the RESTORE commands and run them in a new query window.
6. Run the following command to bring the database out of restoring state.
RESTORE DATABASE dbname WITH RECOVERY
############################################################################
use master
set nocount on
DECLARE @filename varchar(2000), @cmd varchar(8000), @dbname varchar(100)
-----------------------Enter the Database name in the next line
SET @dbname='New'
IF EXISTS (SELECT name FROM tempdb.sys.tables WHERE name like '#dir%')
begin
DROP table #dir
end
create table #dir (filename varchar(1000))
-----------------------Enter the path to TRN File in the xp_cmdshell line
insert into #dir
exec xp_cmdshell 'dir "C:\Backup\Adventure*.trn" /b'
delete from #dir where filename is null
DECLARE filecursor CURSOR FOR
select * from #dir order by filename asc
OPEN filecursor
FETCH NEXT FROM filecursor INTO @filename
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd='use master; RESTORE LOG ['+@dbname+'] FROM DISK = N''C:\Backup\'+@filename+''' WITH FILE = 1, NORECOVERY, NOUNLOAD, STATS = 10'
print @cmd
FETCH NEXT FROM filecursor INTO @filename
END
CLOSE filecursor
DEALLOCATE filecursor
drop table #dir
############################################################################
HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.