以下脚本实现SQL server多个数据库的完整备份,备份文件名为:数据库_sqldb_日期.bak,并将所有备份文件进行压缩,压缩文件名为:wz_sqldb_日期.bak.rar,压缩完毕后自动删除原备份文件,并ftp上传至另一台服务器。整个脚本的运行过程自动写入tkblbackup.log中,方便进行错误分析。
@echo off
color 27
title backupdb
rem andyxu
rem http://andyxu.blog.51cto.com
set svr=sqldb
set svrrole=wz
set nowtime=%date:~0,10% %time%
set today=%date:~0,10%
if "%time:~0,1%" == " " (set nowh=%time:~1,1%) else (set nowh=%time:~0,2%)
set rar="c:\Program Files\WinRAR\rar.exe"
set rarlist="D:\script\rarlst.txt"
set ftplist="D:\script\ftplst.txt"
set baklog=D:\script\tkblbackup.log
set FtpSrv=xxx.xxx.xxx.xxx
set FtpPort=21
set FtpUser=ftpuser
set FtpPwd=ftppassword
@echo. >> %baklog%
@echo -------------------------------------------------- >> %baklog%
@echo %nowtime% BackupScript is starting....... >> %baklog%
::数据库备份语句,可添加多个数据库
for %%a in (sql1db sql2db log) do (
@echo %nowtime% BackupDB %%a is beginning....... >> %baklog%
@osql -s localhost -d master -E -Q "backup database %%a to disk='D:\backupdb\%%a_%svr%_%today%.bak' with init" >> %baklog%
echo D:\backupdb\%%a_%svr%_%today%.bak >> %rarlist%
)
::Rar files
%rar% a D:\backupdb\%svrrole%_%svr%_%today%.bak.rar @%rarlist% >> %baklog%
cd /d D:\backupdb
del *.bak
::Upload files by ftp
echo open %FtpSrv% %FtpPort% > %ftplist%
echo user %FtpUser% >> %ftplist%
echo %FtpPwd% >> %ftplist%
echo cd %svr% >>%ftplist%
echo bin >> %ftplist%
echo prompt >> %ftplist%
echo lcd E:\OSS\backupdb >>%ftplist%
echo put %svrrole%_%svr%_%today%.bak.rar >> %ftplist%
echo quit >> %ftplist%
echo bye >> %ftplist%
ftp -n -s:%ftplist% >> %baklog%
echo. > %rarlist%
@echo -------------------------------------------------- >> %baklog%
@echo. >> %baklog%
说明:
1. 由于我的备份策略是每天进行一次完整备份,每2个小时进行一次差异备份,故备份文件名只加了日期而没有加时间,并且需与差异备份分开写成两个脚本,至于差异备份和恢复脚本请看后面的文章。
2. 需将此脚本保存为bat文件,并放入到sql server的计划任务中,并根据需要调整运行的时间。