Script to check that backup files still exist for SQL Server
By: Thomas LaRock | Updated: 2009-07-23 | Comments (1) | Related: More > Scripts
You have configured your database backup jobs without any problems. The backups themselves seem to be working, but are the files still where you think they are? How do you know they have not been moved, or worse, deleted to free up some space on your server? And when would you find out that the files were no longer there? If you are looking for the file to do a restore, and cannot find it, then it is too late. In this tip, I will show you a simple way to check through the backup history to find the last full backup for each database and also to check that the file still exists where it is supposed to exist.
The database backup file information is readily available inside the msdb database, making the solution as easy as a few lines of T-SQL. The code below will work for SQL2005/8 by going into the msdb database, extracting the file name, and using the undocumented system stored procedure xp_fileexist. Yes, I said undocumented, which means you need to use at your own risk as Microsoft does not support the undocumented stored procedures and they are subject to change. This system stored procedure is used in a lot of places, so don't be frightened by its undocumented nature.
The code will return the backup file details for each active database on the instance at the moment the code is executed. It will read some tables in the msdb database and return the filename for the last full backup of each database. It will then use xp_fileexist to determine if the file still exists where it was originally created. If it does not, then it will print out a brief error message that includes the name of the missing file and the database.
Returning the details
The script will not return a result set, it will only return a brief message regarding any files not found.
Here is a screenshot of a sample result set returned by the script.
- Take the above code and execute against your instance. You could also put this into a SQL Agent job and automate the task to alert you of missing files.
- The code as written only looks at missing full backups. You can extend this script to look for all backup types to make sure that all files for the entire backup set still exist.
Last Updated: 2009-07-23
About the author
View all my tips