Tuesday, August 22, 2017

SQL Server database size growth using backup history

DECLARE @endDate datetime, @months smallint;
SET @endDate = GetDate();
SET @months = 6;          

WITH cte AS
(
SELECT
DatabaseName = bs.database_name,
YearMonth = YEAR(bs.backup_start_date) * 100 + MONTH(bs.backup_start_date),
MinSizeMB = CONVERT(numeric(10, 1), MIN(bf.file_size / 1048576.0)),
MaxSizeMB = CONVERT(numeric(10, 1), MAX(bf.file_size / 1048576.0)),
AvgSizeMB = CONVERT(numeric(10, 1), AVG(bf.file_size / 1048576.0))
FROM msdb.dbo.backupset AS bs
JOIN msdb.dbo.backupfile AS bf ON bs.backup_set_id = bf.backup_set_id
WHERE not bs.database_name IN ('master', 'msdb', 'model', 'tempdb')
and bf.file_type = 'D'
and bs.[Type] = 'D'
and bs.backup_start_date BETWEEN DATEADD(mm, - @months, @endDate) and @endDate
GROUP BY bs.database_name, YEAR(bs.backup_start_date), MONTH(bs.backup_start_date))
SELECT
main.DatabaseName,
main.YearMonth,
main.MinSizeMB,
main.MaxSizeMB,
GrowthMB =
main.AvgSizeMB
- (SELECT TOP 1 sub.AvgSizeMB
FROM cte AS sub
WHERE sub.DatabaseName = main.DatabaseName
and sub.YearMonth < main.YearMonth
ORDER BY sub.YearMonth DESC)
FROM cte AS main
ORDER BY 5 desc, main.DatabaseName, main.YearMonth

No comments: