-1

I need help to write the sql script to find the latest backup file from the windows folder to restore the database. filename is like:-

dbnm_2019_4_5_11_30_613.bak
dbnm_2019_4_18_11_32_234.bak
dbnm_2019_4_11_11_37_34.bak

... name is made up using dbnm_year_month_date_hr_min_sec format.

used below script:-

CREATE TABLE #File
     ( FileName    SYSNAME,
        Depth       TINYINT,
        IsFile      TINYINT
        );
 INSERT INTO #File
        (FileName, Depth, IsFile)
 EXEC xp_DirTree '[file location]',1,1;

is there anyway that I can insert date filed from the network folder to show when the backup file created and do the order by on that field to find the latest file.

when I am using top 1 in select statement, it is showing me 2019_4_5_11_30_613.bak as latest file which is incorrect.

Daniel
  • 10,641
  • 12
  • 47
  • 85

1 Answers1

0

Is there anyway that I can insert date filed from the network folder to show when the backup file created and do the order by on that field to find the latest file.

SQL Server recovery databases from files only from computer unitys (c: d: ).

To get the backup sets I use this statment:

SELECT
    database_name as DataBaseName,
    physical_device_name as PhysicalDeviceName,
    backup_start_date as BackupStartDate,
    backup_finish_date as BackupFinishDate,
    cast(backup_size/1024.0 as decimal(19,2)) AS BackupSizeKB,
    cast(backup_size/1024.0/1024.0 as decimal(19,2)) AS BackupSizeMB,
    cast(backup_size/1024.0/1024/1024.0 as decimal(19,2))  AS BackupSizeGB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
where cast(b.backup_finish_date as date)= (cast(getdate() -1 as date))

ORDER BY backup_finish_date

Pay attention to the clauses: WHERE and ORDER BY.

There is another way to get from windows folders the last file using powershell. Take a look into Keith Hill answer here: Finding modified date of a file/folder