SQL code
----
以下代码放在作业里做调度,自动备份、自动删除4天前备份
--创建映射
exec master..xp_cmdshell 'net use w: \DatabaseBackup$ "password"/user:Roy',NO_OUTPUT
go
-----2000用游标:
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()-4,112)+'.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 w: /delete'
go
--2005用max支持2G的字符串
declare @s nvarchar(max),@del nvarchar(max)
select @s='',@del=''
select
@s=@s+
char(13)+'backup database '+quotename(Name)+' to disk =''w:'+Name+'_'+convert(varchar(8),getdate(),112)+'.bak'' with init',
@del=@del+
char(13)+'exec master..xp_cmdshell '' del w:'+Name+'_'+convert(varchar(8),getdate()-4,112)+'.bak'', no_output'
from master..sysdatabases where dbid>4 order by dbid asc
exec (@del)
exec(@s)
阅读(754) | 评论(0) | 转发(1) |