declare @mybackup sysname = 'F:\testbak\test.bak'
declare @major int = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS NVARCHAR(128)),4) as int)
declare @build int = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS NVARCHAR(128)),2) as int)
declare @AcceptableDaysOld int = 7
IF OBJECT_ID('tempdb..#Header') IS NOT NULL DROP TABLE #Header
if ( @major >= 10 ) --must be equal or newer than 2008 to meet this criteria!
create table #Header
(
BackupName varchar(256),
BackupDescription varchar(256),
BackupType varchar(256),
ExpirationDate varchar(256),
Compressed varchar(256),
Position varchar(256),
DeviceType varchar(256),
UserName varchar(256),
ServerName varchar(256),
DatabaseName varchar(256),
DatabaseVersion varchar(256),
DatabaseCreationDate varchar(256),
BackupSize varchar(256),
FirstLSN varchar(256),
LastLSN varchar(256),
CheckpointLSN varchar(256),
DatabaseBackupLSN varchar(256),
BackupStartDate varchar(256),
BackupFinishDate varchar(256),
SortOrder varchar(256),
CodePage varchar(256),
UnicodeLocaleId varchar(256),
UnicodeComparisonStyle varchar(256),
CompatibilityLevel varchar(256),
SoftwareVendorId varchar(256),
SoftwareVersionMajor varchar(256),
SoftwareVersionMinor varchar(256),
SoftwareVersionBuild varchar(256),
MachineName varchar(256),
Flags varchar(256),
BindingID varchar(256),
RecoveryForkID varchar(256),
Collation varchar(256),
FamilyGUID varchar(256),
HasBulkLoggedData varchar(256),
IsSnapshot varchar(256),
IsReadOnly varchar(256),
IsSingleUser varchar(256),
HasBackupChecksums varchar(256),
IsDamaged varchar(256),
BeginsLogChain varchar(256),
HasIncompleteMetaData varchar(256),
IsForceOffline varchar(256),
IsCopyOnly varchar(256),
FirstRecoveryForkID varchar(256),
ForkPointLSN varchar(256),
RecoveryModel varchar(256),
DifferentialBaseLSN varchar(256),
DifferentialBaseGUID varchar(256),
BackupTypeDescription varchar(256),
BackupSetGUID varchar(256),
CompressedBackupSize varchar(256)
)
if ( @major >= 11 ) --ADD TO ACCOMODATE SQL 2012
ALTER TABLE #Header add Containment varchar(256)
if ( @major = 12 and @build >= 4100 ) OR (@major >= 13) --ADD TO ACCOMODATE SQL 2014 SP1 through SQL 2019
ALTER TABLE #Header add
KeyAlgorithm nvarchar(32),
EncryptorThumbprint varbinary(20),
EncryptorType nvarchar(32)
--All versions (This field added to retain order by)
ALTER TABLE #Header add
Seq int NOT NULL identity(1,1)
insert into #Header
EXEC('RESTORE HEADERONLY FROM DISK=''' +@mybackup+ '''')
IF (select TOP 1 BackupStartDate from #Header order by BackupStartDate DESC) < GETDATE()-@AcceptableDaysOld
print 'This is an old backup!'
ELSE
print 'This is a recent backup'
IF OBJECT_ID('tempdb..#Header') IS NOT NULL DROP TABLE #Header