EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE;
--如果执行一下代码 首先必须安装WinRar 然后 在环境变量中---系统环境变量 Path 中 把Rar.exe 的路径加进去 (如:C:/Program Files/WinRar/) 这样就可以了,看好了 只需要加路径。。。不需要Rar.exe;我们之前干的这些步骤是为了 下面红色地方,因为要执行Rar.exe 不然会报 不是内部程序 或者不是内部命令 。。。
--备份数据库
DECLARE @strSql VARCHAR(1000)
,@strSqlCmd VARCHAR(1000)
,@timeDateDiff INT
SET @timeDateDiff = DATEDIFF(week,0,GETDATE())
SET @timeDateDiff = CASE DATEPART(WEEKDAY,GETDATE())
WHEN 1 THEN @timeDateDiff -1
ELSE @timeDateDiff END
SET @strSql='H:/BackUpCost/Costing/CostDB_' -- 备份目录及备份的文件头
+replace(replace(replace(CONVERT(varchar(16), getdate(), 120 ),'-',''),' ',''),':',''); --数据路径及 当前时间文件名
SET @strSqlCmd= @strSql+'.BAK' --备份文件的扩展名
BACKUP DATABASE [Costing] --要备份的数据库名称
TO DISK = @strSqlCmd WITH INIT
,NOUNLOAD
,NAME = N'MyDb 备份'
,NOSKIP
,STATS = 10
,NOFORMAT
go
--压缩数据库
Declare @TimeNow nvarchar(500)
set @TimeNow=replace(replace(replace(CONVERT(varchar(16), getdate(), 120 ),'-',''),' ',''),':','');
DECLARE @strSqlTo VARCHAR(1000)
DECLARE @strSqlFrom VARCHAR(1000)
,@strSqlCmd VARCHAR(1000)
,@timeDateDiff INT
,@strWeekDay VARCHAR(20)
SET @timeDateDiff= DATEDIFF(week,0,GETDATE())
SET @timeDateDiff= CASE DATEPART(WEEKDAY,GETDATE())
WHEN 1 THEN @timeDateDiff-1
ELSE @timeDateDiff END
SET @strSqlFrom='H:/BackUpCost/Costing/CostDB_' -- 备份目录及备份的文件头 从那个目录备份及原始文件在哪
+ @TimeNow
SET @strSqlTo='H:/BackUpCost/CostingRAR/CostDB_' -- 备份目录及备份的文件头 备份到那个目录下
+@TimeNow
SET @strWeekDay= CASE DATEPART(WEEKDAY,GETDATE()) WHEN 1 THEN '星期天'
WHEN 2 THEN '星期一'
WHEN 3 THEN '星期二'
WHEN 4 THEN '星期三'
WHEN 5 THEN '星期四'
WHEN 6 THEN '星期五'
WHEN 7 THEN '星期六' END
SET @strSqlCmd= 'ECHO 压缩开始日期: '+CONVERT(VARCHAR(20),GETDATE(),120)+' '+@strWeekDay+' >> H:/BackUpCost/Costing/CostDB_'+CONVERT(CHAR(6),DATEADD(week,@timeDateDiff,0),112)+'.txt'
EXEC master.dbo.XP_CMDSHELL @strSqlCmd
SET @strSqlCmd= 'Rar.exe A -R '+@strSqlTo+'.RAR '+@strSqlFrom+'.BAK >> H:/BackUpCost/Costing/CostDB_'+CONVERT(CHAR(6),DATEADD(week,@timeDateDiff,0),112)+'.txt'
PRINT LEN(@strSqlCmd)
PRINT (@strSqlCmd)
EXEC master.dbo.XP_CMDSHELL @strSqlCmd --这个是真正备份的语句
SET @strSqlCmd= 'ECHO 压缩日期: '+CONVERT(VARCHAR(20),GETDATE(),120)+' '+@strWeekDay+' >> H:/BackUpCost/Costing/CostDB_'+CONVERT(CHAR(6),DATEADD(week,@timeDateDiff,0),112)+'.txt'
EXEC master.dbo.XP_CMDSHELL @strSqlCmd