Created
October 26, 2021 10:39
-
-
Save cemerson/675e280a6da04b7193580aebbcd4eb13 to your computer and use it in GitHub Desktop.
Script to copy entire database in MS SQL Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Script to copy entire database in MS SQL Server | |
-- (Source: https://stackoverflow.com/a/79691/826308) | |
-- VARIABLES | |
DECLARE @dbSrcName as nvarchar(max) = 'Northwind'; | |
DECLARE @dbCopyName as nvarchar(max) = 'Northwind_20211026'; | |
DECLARE @dbCopyFilesPath as nvarchar(max) = 'E:\\Backups\\'; | |
-- (change if needed) | |
DECLARE @dbSrcLogicalName as nvarchar(max) = @dbSrcName; | |
DECLARE @dbSrcLogicalLogName as nvarchar(max) = @dbSrcName + '_log'; | |
DECLARE @dbCopyBakPath as nvarchar(max) = @dbCopyFilesPath + @dbCopyName + '.bak'; | |
DECLARE @dbCopyMDFPath as nvarchar(max) = @dbCopyFilesPath + @dbCopyName + '.mdf'; | |
DECLARE @dbCopyLDFPath as nvarchar(max) = @dbCopyFilesPath + @dbCopyName + '.ldf'; | |
-- SOURCE SERVER DB TO BAK | |
BACKUP DATABASE @dbSrcName | |
TO DISK = @dbCopyBakPath | |
-- TARGET SERVER | |
RESTORE FILELISTONLY | |
FROM DISK = @dbCopyBakPath | |
-- RESTORE DEVICE NAMES, MDF/LDF | |
RESTORE DATABASE @dbCopyName | |
FROM DISK = @dbCopyBakPath | |
WITH MOVE @dbSrcLogicalName TO @dbCopyMDFPath, | |
MOVE @dbSrcLogicalLogName TO @dbCopyLDFPath | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment