--显示高级选项(仅需执行一次) EXEC sp_configure 'show advanced options', 1 GO RECONFIGURE GO --允许执行xp_cmdshell EXEC sp_configure 'xp_cmdshell', 1 GO RECONFIGURE GO --添加映射驱动器 declare @string nvarchar(200) set @string = 'net use
--•显示高级选项(仅需执行一次)
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
--•允许执行xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
--•添加映射驱动器
declare @string nvarchar(200)
set @string = 'net use m: \\200.31.154.47\mis_backup "helloMIS555" /user:cfets-zfj60i4jl\LocalAdmin'
exec master..xp_cmdshell @string
--其中192.168.1.2为文件服务器的地址,db_backup为该服务器的共享文件夹,administrator 123456 分别为共享时设置的用户名密码。
--•备份数据库至本地
declare @date datetime
set @date = GetDate()
declare @str nvarchar(100)
set @str = 'E:\DatabaseBackup\ManagementInformation_backup_'+ convert(nvarchar(12), @date, 112) +'.bak'
backup database ManagementInformation to disk=@str WITH init
declare @strh nvarchar(100)
set @strh = 'E:\DatabaseBackup\Portal_backup_'+ convert(nvarchar(12), @date, 112) +'.bak'
backup database ManagementInformation to disk=@strh WITH init
--
--
--With init为覆盖同名文件(本例设计为1天执行一次,不会出现覆盖的情况)。
--
--•拷贝到文件服务器
declare @str1 nvarchar(100)
set @str1 = 'copy '+ @str +' m:'
exec master..xp_cmdshell @str1
set @str1 = 'copy '+ @strh +' m:'
exec master..xp_cmdshell @str1
declare @datecount int
set @datecount=1
declare @delstr nvarchar(100)
declare @deldate datetime
set @deldate=dateadd(dd,-30,getdate())
while @datecount
Begin
set @deldate=dateadd(dd,-1,@deldate)
Set @delstr='del m:\ManagementInformation_backup_'+ convert(nvarchar(12),@deldate, 112) +'.bak'
exec master..xp_cmdshell @delstr
Set @delstr='del m:\Portal_backup_'+ convert(nvarchar(12), @deldate, 112) +'.bak'
exec master..xp_cmdshell @delstr
set @datecount=@datecount+1
End
--•删除映射以及本地备份
exec master..xp_cmdshell 'net use m: /delete'
declare @str2 nvarchar(100)
set @str2 = 'del '+@str+''
exec master..xp_cmdshell @str2
set @str2 = 'del '+@strh+''
exec master..xp_cmdshell @str2
--7关闭允许执行cmdshell
EXEC sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE
GO