June 15, 2023 at 4:46 pm
Below script is not working .Not sure what is wrong in it. Any suggessions pls.
--get the last backup file name and path
Declare @FileName varChar(255)
Declare @cmdText varChar(255)
Declare @BKFolder varchar(255)
Declare @DT datetime
set @FileName = null
set @cmdText = null
set @BKFolder = '\\xxxxx\xxxxx\'
set @DT = getdate()
create table #FileList (
FileName varchar(255),
DepthFlag int,
FileFlag int
)
--get all the files and folders in the backup folder and put them in temporary table
insert into #FileList exec xp_dirtree @BKFolder,0,1
--select * from #filelist
--get the latest backup file name
select top 1 @FileName = @BKFolder + FileName from #FileList where Filename like '%.bak' order by filename desc
select @filename
--execute the restore
exec('
RESTORE DATABASE [xxxxx] FROM DISK = ''' + @filename + '''
WITH MOVE N''xxxx'' TO N''F:\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\''' + @DT + '''.mdf'',
MOVE N''xxxx_Log'' TO N''L:\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\LOG\''' + @DT + '''.ldf'', NOUNLOAD, REPLACE, STATS = 10')
drop table #FileList
June 15, 2023 at 6:41 pm
It is a lot easier to get recent backups from the tables in msdb:
June 16, 2023 at 4:19 pm
You're trying to concatenate a date with a varchar which doesn't end up well unless you specify the format of the date that you want.
Also you have too many quotes I think.
Change the restore part to something like this:
--execute the restore
declare @dt2 varchar(100)=CONVERT(varchar, @dt, 112)
EXEC ('
RESTORE DATABASE [xxxxx] FROM DISK = ''' + @filename + '''
WITH MOVE N''xxxx'' TO N''F:\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\' + @dt2 + '.mdf'',
MOVE N''xxxx_Log'' TO N''L:\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\LOG\'+ @dt2 + '.ldf'', NOUNLOAD, REPLACE, STATS = 10'
)
That should hopefully get you working but as mentioned previously, there are better ways of scripting it
June 16, 2023 at 7:07 pm
Thank you! It works.
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy