需求分析:因為公司遵從正版軟件的許可,本著節約成本的優良傳統,故沒有使用什麼盜版軟件,用的是微軟的SQL Server 2005 Express。因為對數據十分的重視,故需要每天對數據庫進行備份,而又要刪除兩個星期之前的備份數據,經查閱資料,得出如下一套方案,還望各路大俠指點一二:
現在的環境是一台安裝SQL Server 2005 Express和Microsoft SQLServer 2005 Management Studio Express 圖形化管理工具的服務器。
現在在C盤下創建如下兩個文件夾:C:\Script和C:\DB_Backup,Script下用於存放腳本文件,而DB_Backup下用於存放備份數據。
1、C:\Script文件夾下有下面三個文件:Schedule.cmd,DeleteDB.vbs 和BackupDB.sql
2、BackupDB.sql 有如下內容:
DECLARE @dateString CHAR(12), @dayStr CHAR(2), @monthStr CHAR(2), @hourStr CHAR(2), @minStr CHAR(2)
--定義月變量
IF (SELECT LEN(CAST(MONTH(GETDATE()) AS CHAR(2))))=2
SET @monthSTR=CAST(MONTH(GETDATE()) AS CHAR(2))
ELSE
SET @monthSTR= '0' + CAST(MONTH(GETDATE()) AS CHAR(2))
--定義天變量
IF (SELECT LEN(CAST(DAY(GETDATE()) AS CHAR(2))))=2
SET @daySTR=CAST(DAY(GETDATE()) AS CHAR(2))
ELSE
SET @daySTR='0' + CAST(DAY(GETDATE()) AS CHAR(2))
--定義小時變量
IF (SELECT LEN(DATEPART(hh, GETDATE())))=2
SET @hourStr=CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
ELSE
SET @hourStr= '0' + CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
--定義分變量
IF (SELECT LEN(DATEPART(mi, GETDATE())))=2
SET @minStr=CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
ELSE
SET @minStr= '0' + CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
--定義基於當前時間戳變量
SET @dateString=CAST(YEAR(GETDATE()) AS CHAR(4)) + @monthStr + @dayStr + @hourStr + @minStr
--=================================================================
DECLARE @IDENT INT, @sql VARCHAR(1000), @DBNAME VARCHAR(200)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND NAME = 'master'
BEGIN
SELECT @DBNAME = NAME FROM SYS.DATABASES WHERE database_id = @IDENT
SELECT @SQL = 'BACKUP DATABASE '+@DBNAME+' TO DISK = ''D:\SQLTEST\'+@DBNAME+'_db_' + @dateString +'.BAK'' WITH INIT'
EXEC (@SQL)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND database_id>@IDENT AND NAME NOT IN ('TEMPDB')
END
3、DeleteDB.vbs下有如下內容:
On Error Resume Next
Dim fso, folder, files, sFolder, sFolderTarget
Set fso = CreateObject("Scripting.FileSystemObject")
'保存數據庫備份文件路徑
sFolder = "D:\SQLTEST\"
Set folder = fso.GetFolder(sFolder)
Set files = folder.Files
'用於寫入文本文件,並生成刪除數據庫備份報告
Const ForAppending = 8
'在scripts下創建一個空txt文件:Log.txt
Set objFile = fso.OpenTextFile(sFolder & "\Log.txt", ForAppending)
objFile.Write "================================================================" &
VBCRLF & VBCRLF
objFile.Write " 數據庫備文件報告 " & VBCRLF
objFile.Write " 日期: " & FormatDateTime(Now(),1) & "" &
VBCRLF
查看本欄目
objFile.Write "