MSSQL Server2012备份所有数据库到网络共享盘上面,并自动删除几天前的备份。。
1备份当前MSQL所有数据库
--要备份到哪一服务的IP网络位置,要提前打开文件夹共享.这里还要输入用户名和密码,下面这一行是建立共享 exec master..xp_cmdshell 'net use \\192.168.8.108\DBBak Password /user:192.168.1.108\administrator',NO_OUTPUT go declare @s nvarchar(200),@del nvarchar(200) select @s='',@del='' --自动备份,并删除4天前的备份。可以随意改数字. declare datebak cursor for select [bak]='backup database '+quotename(Name)+' to disk =''\\192.168.8.108\DBBak\'+Name+'('+convert(varchar(10),getdate(),120)+')'+'.bak'' with init', [del]='exec master..xp_cmdshell '' del \\192.168.8.108\DBBak\'+Name+'('+convert(varchar(10),getdate()-4,120)+')'+'.bak'', no_output' from master..sysdatabases where dbid>4 --不备份系统数据库 open datebak fetch next from datebak into @s,@del while @@fetch_status=0 begin exec (@del) exec(@s) fetch next from datebak into @s,@del end close datebak deallocate datebak go --删除共享链接 exec master..xp_cmdshell 'net use \\192.168.8.108\DBBak/delete' go
2.备份指定的几个数据到网络盘
declare @DBName nvarchar(max) declare @BakName nvarchar(max) --建立(打开)共享目录 exec master..xp_cmdshell 'net use \\192.168.1.100\MSSQLDBBak Password /user:192.168.1.100\administrator' Declare DBCursor CURSOR FORWARD_ONLY READ_ONLY
--要删除的指定数据库名称在下面用union select拼接 For ( select '[DB1]' as DBName
union select '[DB2]' as DBName ) open DBCursor fetch next from DBCursor into @DBName while (@@fetch_status=0) begin --print @DBName --select @DBName='[LFBMP.PO]' --指定保存路径本地目录 --select @BakName='D:\MSSQLDBBak\BC_'+REPLACE(@DBName,'.','_')+Convert(char(10),getdate(),120)+'.bak'
--指定保存到网络共享目录 select @BakName='\\192.168.1.100\MSSQLDBBak\'+REPLACE(@DBName,'.','_')+Convert(char(10),getdate(),120)+'.bak' declare @BakSQL nvarchar(max) --select @BakSQL='Backup Database '+@DBName+' To disk='''+@BakName+'''' select @BakSQL='Backup Database '+@DBName+' To disk='''+@BakName+''' with init,nounload ' print @BakSQL exec (@BakSQL) fetch next from DBCursor into @DBName end close DBCursor deallocate DBCursor --删除(关闭)共享目录 exec master..xp_cmdshell 'net use \\192.168.1.100\MSSQLDBBak /delete' --修改密码,重新执行以下代码 --exec master..xp_cmdshell 'net use \\192.168.1.100\MSSQLDBBak Password /user:192.168.1.100\administrator' --删除(关闭)共享目录 --exec master..xp_cmdshell 'net use \\192.168.1.100\R910MSSQLDBBak /delete'
欢迎加入JAVA技术交流QQ群:179945282
欢迎加入ASP.NET(C#)交流QQ群:17534377