-----sqlserver 數據異地備份 默認刪除 七天前的數據 -----該代碼可配置成SQLServer作業里做調度,或者配置成任務計划進行執行 ----掛載異地盤符 exec master..xp_cmdshell 'net use w: "\\172.16.30.34\D$" "726" "/user:172.16.30.34\administrator"', no_output /*--說明: w: 是映射網絡路徑對應本機的盤符,與下面的備份對應 \\172.16.30.34\D$ 是要映射的網絡路徑 172.16.30.34\administrator 172.16.30.34是遠程的計算機名,administrator是登陸的用戶名 726 上面指定的administrator用戶的密碼 --*/ go go -----用游標: declare @s nvarchar(200),@del nvarchar(200) select @s='',@del='' declare datebak cursor for select [bak]='backup database '+quotename(Name)+' to disk =''w:'+Name+'_'+convert(varchar(8),getdate(),112)+'.bak'' with init', -----自動刪除七天前的備份文件 [del]='exec master..xp_cmdshell '' del w:'+Name+'_'+convert(varchar(8),getdate()-7,112)+'.bak'', no_output' from master..sysdatabases where dbid=37 --這里查詢出需要備份的數據庫,可以一次性備份多個數據庫 open datebak fetch next from datebak into @s,@del while @@fetch_status=0 begin ----對於要刪除的備份文件進行一場捕獲(解決第一次部分的時候,執行失敗的情況) begin try exec (@del) end try begin catch if @@TRANCOUNT >0 BEGIN print @del END end catch exec(@s) fetch next from datebak into @s,@del end close datebak deallocate datebak go --刪除映射 exec master..xp_cmdshell 'net use w: /delete' go