SQL2016 自动备份数据库并压缩

主要四个步骤

第一步备份出BAK数据库文件,
第二步开启 XP_CMDSHLL,
第三步打包压缩数据库备份文件后并删除原备份文件
第二步关闭 XP_CMDSHLL,

一、执行备份的命令:

declare @filename varchar(200)

set @filename='D:\'+convert(char(10),getdate(),120)+'.bak'  --设置备份文件的路径和文件名

print @filename

backup database[DatabaseName] to disk=@filename with NOINIT,NOUNLOAD,NAME='backup',NOSKIP,STATS=10,NOFORMAT  --执行备份

二、开启 xp_cmdshell (SQL 2012为安全默认不开启的)

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO

-- To update the currently configured value for advanced options.
RECONFIGURE
GO

-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO

-- To update the currently configured value for this feature.
RECONFIGURE
GO

三、压缩并删除源文件的命令:(winrar不能放在有空格的文件夹)

declare @file varchar(200)

set @file='c:\winrar.exe a -ep -df D:\DatebaseName_'+convert(char(10),getdate(),120)+'.rar D:\'+convert(char(10),getdate(),120)+'.bak'  --将压缩备份文件并删除源文件的winrar命令行命令

exec master..xp_cmdshell @file  --执行命令

四、为了安全可以备份完成后关闭xp_cmdshell

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO

-- To update the currently configured value for advanced options.
RECONFIGURE
GO

-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 0
GO

-- To update the currently configured value for this feature.
RECONFIGURE
GO

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容