Pages

Friday, August 10, 2012

Delete Old backups with Code

How to Delete the old backups or log files using TSQL code

declare @DeleteDate nvarchar(50)


declare @DeleteDateTime datetime 

set @DeleteDateTime = DateAdd(dd, -28, GetDate()) 

set @DeleteDate = (Select Replace(Convert(nvarchar, @DeleteDateTime, 111), '/', '-') + 'T' + Convert(nvarchar, @DeleteDateTime, 108)) 

--select @DeleteDate 

EXECUTE master.dbo.xp_delete_file 0,N'D:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup',N'bak',@DeleteDate,1

/* Above script will delete the files with "bak" as extension and older than 28 days.

If you want to change the file extension please change it in the last line of code.

If you want to change the date from when you want to delete the data, please change it at line 3. Before executing the code please uncheck the "select @deletedate and check from when you are going to delete the data"

*/

Hope the above helps

Thanks