Wednesday, 12 July 2017

SQL SERVER DBA - Cleanup job


SQL SERVER DBA -  Cleanup job
-------------------------------------------


For Full backup files:
--------------------------
declare
@ServerName nvarchar(256)  = @@SERVERNAME,
@RoleDesc nvarchar(60)

declare
@RetentionDay smallint = 7,
@FolderToCleanup nvarchar(100),
@FileType nvarchar(5) = 'BAK',
@RetentionDate datetime,
--@DB_Name varchar(100) = 'SQL',
@BackupDay varchar(100),
@BackupType varchar(5) = 'FULL'

--set @RetentionDate = dateadd(day, -@RetentionDay, GETDATE())

--set @BackupDay = LEFT(UPPER(datename(dw, getdate())), 3)
set @BackupDay = LEFT(UPPER(datename(dw, (DateAdd(dd,-@RetentionDay,getdate())))), 3)

set @FolderToCleanup = 'C:\Server02\Backup\' +  @BackupType + '\' + @BackupDay + '\'
exec master.dbo.xp_delete_file 0, @FolderToCleanup, @FileType, @RetentionDate, 0

------------
For Log backup files:
---------------------------

declare
@ServerName nvarchar(256)  = @@SERVERNAME,
@RoleDesc nvarchar(60)

declare
@RetentionDay smallint = 7,
@FolderToCleanup nvarchar(100),
@FileType nvarchar(5) = 'TRN',
@RetentionDate datetime,
--@DB_Name varchar(100) = 'SQL',
@BackupDay varchar(100),
@BackupType varchar(5) = 'TLOG'

--set @RetentionDate = dateadd(day, -@RetentionDay, GETDATE())

--set @BackupDay = LEFT(UPPER(datename(dw, getdate())), 3)
set @BackupDay = LEFT(UPPER(datename(dw, (DateAdd(dd,-@RetentionDay,getdate())))), 3)

set @FolderToCleanup = 'C:\Server02\Backup\' +  @BackupType + '\' + @BackupDay + '\'
exec master.dbo.xp_delete_file 0, @FolderToCleanup, @FileType, @RetentionDate, 1
----------------------------------

No comments:

Post a Comment