T-SQL: Clear msdb backup history

After a while,the msdb database can be overloaded with backup history, and clearing that history can be a pain. You can use the t-sql code below to clear the msdb backup history, in incremental steps of 1 week.

use msdb
go
declare @retentionDate datetime = DATEADD(MONTH, -3, getdate())
declare @oldest_date datetime = (select min(backup_start_date) from msdb.dbo.backupset)
while (@oldest_date  < @retentionDate)
begin
    print 'sp_delete_backuphistory ' + CAST(@oldest_date AS varchar)
    exec msdb.dbo.sp_delete_backuphistory @oldest_date
    --  Delete by 1 week increments
    set @oldest_date = DATEADD(WEEK, 1, @oldest_date)
    checkpoint
end
exec msdb.dbo.sp_delete_backuphistory @retentionDate
go
Share your love