/*********************************************************************************** |
* FielName : backup.sql |
* Function : 自动备份 |
* Author : Yahong<Yahongq111@163.com> |
* Date : 2005-5-10 2005-5-19 2006-8-1 2007-09-18 |
* Version : 00 01 02 03 |
* |
* Remark : |
* 2006-08-01 增加差异备份和完全备份两种情况,生成多个备份副本 |
* 2008-09-18 增加备份一个实例中的所有数据库的情况,并在备份后清除日志 |
* |
*********************************************************************************/ |
use master |
declare @DbName varchar (255),@dir varchar (256),@dir_db varchar (256), |
@verb varchar (256),@cmd varchar (256), |
@backup_name varchar (256),@dynamic_name varchar (10), |
@disk_name varchar (256),@copy nvarchar(100), |
@today datetime,@weekday int |
--建立网络连接 |
exec xp_cmdshell 'net use K: /delete' |
exec xp_cmdshell 'net use I: /delete' |
exec xp_cmdshell 'net use K: \\193.254.40.118\backup backup /user:Web\backup ' |
exec xp_cmdshell 'net use I: \\172.16.8.48\databackup backup /user:QA-SERVER-TEST\backup' |
--设定名字 |
set @today=getdate() |
set @dynamic_name= convert ( varchar (10),@today,120) |
set @dir= 'K:\'+@dynamic_name |
set @dir_db=@dir+' Database ' |
set @verb=' mkdir ' |
--建立目录 |
set @cmd=@verb+@dir_db |
exec xp_cmdshell @cmd |
declare cur_database cursor forward_only read_only for |
select name from sysdatabases |
where dbid>4--系统数据库的dbid<=4 |
open cur_database |
fetch next from cur_database |
into @DbName |
while @@fetch_status=0 |
begin |
set @backup_name= @DbName+' _ '+@dynamic_name |
set @disk_name=@dir_db+' \ '+@backup_name+' .bak ' |
|
--添加备份设备 |
EXEC sp_addumpdevice ' disk ',@backup_name, @disk_name |
|
set @weekday= datepart(dw,@today) |
if (@weekday=6) --如果是周五,则进行完全备份 |
BACKUP DATABASE @DbName TO @backup_name |
else--其他时候进行差异备份 |
BACKUP DATABASE @DbName TO @backup_namewith differential |
|
--清理日志 |
backup log @DbName with no_log |
|
--释放设备 |
exec sp_dropdevice @backup_name |
|
--复制备份副本到其他地方 |
set @copy=' copy '+@disk_name+' I: ' |
exec xp_cmdshell @copy |
|
--备份下一个数据库 |
fetch next from cur_database |
into @DbName |
end |
close cur_database |
deallocate cur_database |
|
--删除网络连接 |
exec xp_cmdshell ' net use K: / delete ' |
exec xp_cmdshell ' net use I: / delete ' |