简体   繁体   English

使用文件名变量日期脚本还原数据库

[英]Restore database with file name variable date script

I want to write a script that will restore the database by database name + today's date. 我想写一个脚本,它将按数据库名称+今天的日期恢复数据库。 Example: (test_01.05.2018.bak) 示例:(test_01.05.2018.bak)

DECLARE @BackupFile as nvarchar(128);
SET @BackupFile = N'C:\backup\test1' + convert(varchar(12),Day(GETDATE()) -1) + (month(GETDATE()) * 100) + (year(GETDATE()) * 10000) + N'test1.bak'
USE master;
RESTORE DATABASE [TEST] FROM DISK = @BackupFile WITH FILE = 1,
MOVE N'test1' TO N'C:\db\TEST.mdf',  
MOVE N'test1_log' TO N'C:\db\TEST_log.ldf',
NOUNLOAD, REPLACE, STATS = 10

Your query would have had date in YYYYMMDD and yesterdays date. 您的查询的日期将在YYYYMMDD和昨天的日期。 It errors because of converion. 由于收敛而导致错误。

It could be rewritten with something like 它可以用类似的东西重写

DECLARE @BackupFile as nvarchar(128);
SET @BackupFile = N'C:\backup\test1' + CONVERT(NVARCHAR(8), DATEADD(DAY, -1, GETDATE()), 112) + N'test1.bak'

You'll still have to edit the other parts of the string as I couldn't make sense of it but this will get your there. 你仍然需要编辑字符串的其他部分,因为我无法理解它,但这会让你在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM