Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
--- Restore a database from MDF and LDF to a new name.
--- Before you execute this script rename the files to the new name and move them to the
--- destination folder.
USE master
GO
DECLARE @OldDatabaseName nvarchar(50) = N'' --- insert old database name
DECLARE @NewDatabaseName nvarchar(50) = N'' --- insert new database name
DECLARE @OldLogFileName nvarchar(50) = N'' --- insert old log file name
DECLARE @NewLogFileName nvarchar(50) = N'' --- insert new log file name
DECLARE @PathToMDF nvarchar(256) = N'' --- insert path to MDF
DECLARE @PathToLDF nvarchar(256) = N'' --- insert path to LDF
DECLARE @SQLString nvarchar(MAX) --- SQL statement to alter database
--- Must use dynamic SQL to execute the alter statements
set @SQLString = '
CREATE DATABASE ' + @NewDatabaseName + '
ON (FILENAME = ''' + @PathToMDF + '''),
(FILENAME = ''' + @PathToLDF + ''')
FOR ATTACH;
ALTER DATABASE ' + @NewDatabaseName + ' MODIFY FILE (NAME = ''' +
@OldDatabaseName + ''', NEWNAME = ''' + @NewDatabaseName + ''')
ALTER DATABASE ' + @NewDatabaseName + ' MODIFY FILE (NAME = ''' +
@OldLogFileName + ''', NEWNAME = ''' + @NewLogFileName + ''')'
--- Execute @SQLString to alter the file names.
EXECUTE(@SQLString)
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.