异地数据库备份(可做成作业)

--异地数据库备份作业语句

--显示高级选项(仅需执行一次) 
EXEC sp_configure 'show advanced options', 1 
GO

RECONFIGURE  WITH OVERRIDE;
GO

--允许执行xp_cmdshell 
EXEC sp_configure 'xp_cmdshell', 1 
GO

RECONFIGURE WITH OVERRIDE;
GO
 

--添加映射驱动器 
declare @string nvarchar(200)
set @string = 'net use z: \\192.168.0.102\服务器备份 "2961989" /user:192.168.0.102\administrator' 
exec master..xp_cmdshell @string
 
--其中192.168.0.180为文件服务器的地址,db_backup为该服务器的共享文件夹,administrator(sql2005 用户名前一定要加机器名或ip地址) 2961989分别为共享时设置的用户名密码。

--1.备份数据库至本地 原来没有数据库备份作业的 
/*declare @date datetime 
set @date = GetDate() 
declare @str nvarchar(100) 
set @str = 'e:\backup\生产库'+ convert(nvarchar(12), @date, 112) +'.bak' 
backup database hydee_fyt to disk=@str with init
*/

--2.已有数据库备份作业的 用下面这段是数据库备份文件的存放路径和文件名
declare @str nvarchar(100) 
set @str = 'E:\bakdata\'+convert(char(8),getdate(),112)+'.rar' 

--With init为覆盖同名文件(本例设计为1天执行一次,不会出现覆盖的情况)。

--拷贝到文件服务器 
declare @str1 nvarchar(100)

set @str1 = 'copy '+ @str +' z:'

exec master..xp_cmdshell @str1
 
--如果是每次都覆盖的话可以在z:后面加 /y 参数

--删除映射以及本地备份 
exec master..xp_cmdshell 'net use z: /delete' 
--declare @str2 nvarchar(100) 
--set @str2 = 'del '+@str+'' 
--exec master..xp_cmdshell @str2
 

--关闭允许执行cmdshell 
EXEC sp_configure 'xp_cmdshell', 0 
GO 
RECONFIGURE WITH OVERRIDE;
GO

猜你喜欢

转载自www.cnblogs.com/binghou/p/9100058.html