Skip to content

Instantly share code, notes, and snippets.

@SteveByerly
Created September 24, 2020 22:16
Show Gist options
  • Save SteveByerly/c5cd8d28ba6261c38c8ed6e3a672fb79 to your computer and use it in GitHub Desktop.
Save SteveByerly/c5cd8d28ba6261c38c8ed6e3a672fb79 to your computer and use it in GitHub Desktop.
MS Sql Server script for restoring a backup with unknown file contents
USE master;
GO
DECLARE @BackupDir NVARCHAR(260);
SET @BackupDir = CAST(ServerProperty(N'InstanceDefaultDataPath') AS NVARCHAR(260));
DECLARE @NewDataPath NVARCHAR(260);
DECLARE @NewLogPath NVARCHAR(260);
SET @NewDataPath = CONCAT(@BackupDir, N'$(DatabaseName)', '_DATA.MDF');
SET @NewLogPath = CONCAT(@BackupDir, N'$(DatabaseName)', '_LOG.LDF');
DECLARE @OldDataPath NVARCHAR(260);
DECLARE @OldLogPath NVARCHAR(260);
DECLARE @BackupFiles TABLE (
[LogicalName] NVARCHAR(128)
, [PhysicalName] NVARCHAR(260)
, [Type] CHAR(1)
, [FileGroupName] NVARCHAR(128)
, [Size] NUMERIC(20,0)
, [MaxSize] NUMERIC(20,0)
, [FileId] BIGINT
, [CreateLSN] NUMERIC(25,0)
, [DropLSN] NUMERIC(25,0)
, [UniqueId] UNIQUEIDENTIFIER
, [ReadOnlyLSN] NUMERIC(25,0)
, [ReadWriteLSN] NUMERIC(25,0)
, [BackupSizeInBytes] BIGINT
, [SourceBlockSize] INT
, [FilegroupId] INT
, [LogGroupGUID] UNIQUEIDENTIFIER
, [DifferentialBaseLSN] NUMERIC(25)
, [DifferentialBaseGUID] UNIQUEIDENTIFIER
, [IsReadOnly] BIT
, [IsPresent] BIT
, [TDEThumbprint] VARBINARY(32)
, [SnapshotUrl] NVARCHAR(360)
);
INSERT INTO @BackupFiles
EXEC('RESTORE FILELISTONLY FROM DISK = N''$(RestoreFilepath)''');
SET @OldDataPath = (
SELECT TOP 1
[LogicalName]
FROM @BackupFiles
WHERE [Type] = 'D'
);
SET @OldLogPath = (
SELECT TOP 1
[LogicalName]
FROM @BackupFiles
WHERE [Type] = 'L'
);
RESTORE DATABASE [$(DatabaseName)]
FROM DISK = N'$(RestoreFilepath)'
WITH
FILE = 1
, MOVE @OldDataPath TO @NewDataPath
, MOVE @OldLogPath TO @NewLogPath
, REPLACE
, STATS = 5;
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment