主要四个步骤
第一步备份出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