Thursday, November 13, 2008

Sql Server (Differential Backup)

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
Create PROCEDURE [dbo].[DBA_Backup_DIFFERENTIAL]
as
/*
Table Used :- master.dbo.sysdatabases
*/
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----Create Backup of Specified Database and Delete Backup files older than two days
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
begin
Set NoCount On
Declare
@vCount Int,
@vNumDBs Int,
@vDBName Varchar(255),
@vBackupPath Varchar(255),
@vFileName Varchar(100),
@vBackupString Varchar(1000),
@vDeleteString Varchar(1000),
@vNewPath Varchar(1000),
@vErrorString Varchar(1000),
@vDate varchar(10),
@vTime varchar(5) ;
select @vTime = replace(convert(varchar(5), getdate(),114),':','_');
select @vDate = convert(varchar(10), getdate(),112) ;

Set @vBackupPath = 'S:\TempBackup\Diff_Backup' --path where Backup file is going to be Created

Declare
@vDBList Table(
DBID INT NOT NULL IDENTITY(1, 1),
DatabaseName Varchar(256)
)
Insert Into @vDBList
Select Name From master.dbo.SysDatabases where dbid in (7) --List of Backup Database IDS
Set @vNumDBs = @@RowCount
Set @vCount = 1
While @vCount <= @vNumDBs
Begin
Select @vDBName = DatabaseName From @vDBList Where DBID = @vCount
Set @vNewpath = @vBackupPath --+ '\' --+ @vDBName
Set @vDeleteString = 'Del "' + @vNewPath + '\'+ @vDBName + '_' + Convert(Varchar(8), DateAdd(Day, -1, GetDate()), 112) + '_' + @vTime + '_Diff' + '.bak"' + ' /F /Q'
print @vDeleteString
Exec xp_CMDShell @vDeleteString, NO_OUTPUT
Set @vFileName = @vDBName + '_' + @vDate + '_' + @vTime + '_Diff' +'.bak'
Set @vBackupString = 'BACKUP DATABASE [' + @vDBName + '] TO DISK = ''' + @vNewPath + '\'+@vFileName +
''' WITH DIFFERENTIAL , NOFORMAT , NAME = N''' + @vDBName + ''', SKIP, REWIND, NOUNLOAD, STATS = 10'
Print @vBackupString
Exec (@vBackupString)
-- If @@Error <> 0
-- Begin
-- Set @vCount = @vNumDBs
-- Set @vErrorString = 'net send * SQL Backup failed on (' + @vDBName + ')! Please view event log!'
-- ---Exec XP_CMDShell @vErrorString
-- End
Set @vCount = @vCount + 1
End
END

No comments: