What I am trying to do is get the last database backup for each of the databases. I want the results set to have is the database name and the path + file name of the backup. bs.database_name is the database name and bms.physical_device_name is the path + file name of the backup. bs.backup_finish_date is the date and time that the backup completed.If you've got any SQL Servers out there with multiple database backups for each of the databases, then you can run this code.The below query gives me all of the backups for each of the databases. I just want the most current.SELECT bs.database_name, bms.physical_device_nameFROM msdb.dbo.backupset bsINNER JOIN msdb.dbo.backupmediafamily bms ON bs.media_set_id = bms.media_set_idINNER JOIN master.dbo.sysdatabases s ON bs.database_name = s.nameWHERE s.name NOT IN ('master', 'msdb', 'model', 'pubs', 'Northwind')ORDER BY bs.database_name, bs.backup_finish_date DESCThis query just gives me one backup per database, but it isn't necessarily the most current one.SELECT bs.database_name, MAX(bms.physical_device_name) AS Backup_FileFROM msdb.dbo.backupset bsINNER JOIN msdb.dbo.backupmediafamily bms ON bs.media_set_id = bms.media_set_idINNER JOIN master.dbo.sysdatabases s ON bs.database_name = s.nameWHERE s.name NOT IN ('master', 'msdb', 'model', 'pubs', 'Northwind')GROUP BY bs.database_nameThis query gives me the most current backup that occurred TODAY for each of the databases. The problem with this one is that I could be running the query on a particular day before the backups have run, so I'll get 0 records returned.SELECT bs.database_name, MAX(bms.physical_device_name) AS Backup_FileFROM msdb.dbo.backupset bsINNER JOIN msdb.dbo.backupmediafamily bms ON bs.media_set_id = bms.media_set_idINNER JOIN master.dbo.sysdatabases s ON bs.database_name = s.nameWHERE CONVERT(VARCHAR(20), bs.backup_finish_date, 101) = CONVERT(VARCHAR(20), GETDATE(), 101) AND s.name NOT IN ('master', 'msdb', 'model', 'pubs', 'Northwind')GROUP BY bs.database_nameExample result set of the first query above (there are only two columns in the result, but I included sample dates to the right):DB1 E:\MSSQL\BACKUP\DB1_20030510.bak ----(backup occurred May 10, 2003)DB1 E:\MSSQL\BACKUP\DB1_20030401.bak ----(backup occurred Apr. 1, 2003)DB1 E:\DB1_Full.bak ----(backup occurred Dec. 31, 2002)DB2 F:\Backup\DB2.bak ----(backup occurred Jan. 5, 2003)DB3 E:\DB3_20030612.bak ----(backup occurred June 12, 2003)DB3 E:\DB3_20030611.bak ----(backup occurred June 11, 2003)
Desired result set for the above data:DB1 E:\MSSQL\BACKUP\DB1_20030510.bakDB2 F:\Backup\DB2.bakDB3 E:\DB3_20030612.bak
TaraEdited by - tduggan on 06/12/2003 14:29:45