如何编写具有唯一名称格式的每日备份脚本:Demo_YYYYMMDD_XX 其中XX是基于备份历史记录的增量编号。
示例如下。
XX将增加+1。
管理下面的脚本。需要改进吗?感谢
DECLARE @path VARCHAR(500)
DECLARE @name VARCHAR(500)
DECLARE @pathwithname VARCHAR(500)
DECLARE @time DATETIME
DECLARE @year VARCHAR(4)
DECLARE @month VARCHAR(2)
DECLARE @day VARCHAR(2)
DECLARE @counter varchar(10)
SET @path = 'C:\Backup Path\'
SELECT @time = GETDATE()
SELECT @year = (SELECT CONVERT(VARCHAR(4), DATEPART(yy, @time)))
SELECT @month = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(mm,@time),'00')))
SELECT @day = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(dd,@time),'00')))
SELECT @counter = (
select format(count(A.database_name),'000')
from msdb.dbo.backupset A join msdb.dbo.backupmediafamily B
on A.media_set_id = B.media_set_id
where A.database_name = 'Demo'
and (select convert(date,A.backup_start_date, 120)) = (select convert(date,getdate(), 120))
)
SELECT @name ='Demo' + '_' + @year + @month + @day + '_' + @counter
SET @pathwithname = @path + @name + '.bak'
BACKUP DATABASE Demo
TO DISK = @pathwithname WITH NOFORMAT, NOINIT, SKIP, REWIND, NOUNLOAD, STATS = 10
答案 0 :(得分:0)
你有两个选择。
由于你有一个数据库并且正在备份该数据库,为什么不做后者呢?并将您的每日备份记录到具有
的表中create table backups (
dbback DATE NOT NULL DEFAULT GETDATE()
,dbname varchar(99) NOT NULL
,name varchar(99) NOT NULL
,index int NOT NULL
,primary key(db,backdb)
) ;
您可以记录对(db,backdb)以记录多个数据库(dbname,dbback)的条目。
WITH t as ( select (backups.index+1) as nextnum
from backups where dbname = 'database_name' and dbback = CAST(GETDATE() AS DATE)
union select 1 as nextnum from dual )
insert into backups (dbback,dbname,name,index)
values (CAST(GETDATE() AS DATE),'database_name','yourname',t.nextnum) ;
请注意,通过使用union,您可以确保获得临时表中的基(第一行)