My colleague who is a developer usually comes up with requests for little bits and pieces of database related information. This time, it was a request for the latest date that a particular database had been restored from a backup. T’was nothing but 10 minutes of BOL and coding, but lot of people out there might find it quite useful on some occasions. So here we go, the first in the series of Not-So-Hip-Snippets-Yet-Useful-At-Times…
A list of database on your instance are stored in the sys.databases table in the master database, while the backup and restore information is stored in the msdb database on several tables:
- For backups: dbo.backupset, dbo.backupmediaset, dbo.backupmediafamily
- For restores: dbo.restorehistory, dbo.restorefile, dbo.restorefilegroup
The database ID is not maintained in the listed tables, hence we would need to join the the sys.databases table with the required tables using the database names. This is the code to get a list of the latest backups performed against your databases:
While this is the code to get a list of the latest restore operations performed against your databases:
You could stuff more details into this code, from the tables listed above to suit your requirements.