曾經遇到過一個使用者MSDB資料庫非常大,讓我幫忙查查是什麼原因。使用sp_spaceused找出了所有表的資料大小,發現問題是SQL Server備份與還原曆史表資料太大。使用者經常會做記錄備份,但是從來沒有清除過記錄。後來在設定了維護計劃定期清除備份記錄,問題就不在發生了。
這裡列出了查詢SQL Server備份還原記錄的語句以及如何清理Database Backup還原的指令碼:
--查詢SQL Server備份曆史
SELECT
CONVERT(CHAR(100),SERVERPROPERTY('Servername'))ASServer,
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_start_date,
msdb.dbo.backupset.backup_finish_date,
msdb.dbo.backupset.expiration_date,
CASE
msdb..backupset.type
WHEN
'D' THEN 'Database'
WHEN
'L' THEN 'Log'
END ASbackup_type,
msdb.dbo.backupset.backup_size,
msdb.dbo.backupmediafamily.logical_device_name,
msdb.dbo.backupmediafamily.physical_device_name,
msdb.dbo.backupset.nameASbackupset_name,
msdb.dbo.backupset.description
FROM msdb.dbo.backupmediafamily
INNER
JOIN msdb.dbo.backupsetONmsdb.dbo.backupmediafamily.media_set_id=msdb.dbo.backupset.media_set_id
ORDER BY
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_finish_date
-----查詢SQLServer還原曆史
select bus.server_nameas'server',rh.restore_date,bus.database_nameas'database',
CAST(bus.first_lsnASVARCHAR(50))asLSN_First,
CAST(bus.last_lsnASVARCHAR(50))asLSN_Last,
CASE rh.[restore_type]
WHEN 'D'THEN'Database'
WHEN 'F'THEN'File'
WHEN 'G'THEN'Filegroup'
WHEN 'I'THEN'Differential'
WHEN 'L'THEN'Log'
WHEN 'V'THEN'Verifyonly'
END ASrhType
FROM msdb.dbo.backupsetbus
INNER JOINmsdb.dbo.restorehistoryrhON
rh.backup_set_id=bus.backup_set_id
---清除20120101之前所有的備份還原記錄(沒有參數指定只刪除備份或者歡迎記錄)
use msdb
go
exec sp_delete_backuphistory@oldest_date='20121010'
--刪除'AdventureWorks2012'資料庫的備份還原記錄(沒有參數指定保留日期,All或者None)
USE msdb;
GO
EXEC sp_delete_database_backuphistory@database_name='AdventureWorks2012';