다음은 물리적 위치를 수정하기 위해 이동 및 백업을 사용하여 데이터베이스를 복사하고 논리적 이름을 수정하기 위해 추가 SQL을 사용하여 다양한 게시물에서 함께 모은 것입니다.
/**
* Creates (or resets) a Database to a copy of the template database using backup and restore.
*
* Usage: Update the @NewDatabase value to the database name to create or reset.
*/
DECLARE @NewDatabase SYSNAME = 'new_db';
-- Set up
USE tempdb;
DECLARE @TemplateBackups SYSNAME = 'TemplateBackups';
DECLARE @TemplateDatabase SYSNAME = 'template_db';
DECLARE @TemplateDatabaseLog SYSNAME = @TemplateDatabase + '_log';
-- Create a backup of the template database
BACKUP DATABASE @TemplateDatabase TO DISK = @TemplateBackups WITH CHECKSUM, COPY_ONLY, FORMAT, INIT, STATS = 100;
-- Get the backup file list as a table variable
DECLARE @BackupFiles TABLE(LogicalName nvarchar(128),PhysicalName nvarchar(260),Type char(1),FileGroupName nvarchar(128),Size numeric(20,0),MaxSize numeric(20,0),FileId tinyint,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,0),DifferentialBaseGUID uniqueidentifier,IsReadOnly bit,IsPresent bit,TDEThumbprint varbinary(32));
INSERT @BackupFiles EXEC('RESTORE FILELISTONLY FROM DISK = ''' + @TemplateBackups + '''');
-- Create the backup file list as a table variable
DECLARE @NewDatabaseData VARCHAR(MAX);
DECLARE @NewDatabaseLog VARCHAR(MAX);
SELECT @NewDatabaseData = PhysicalName FROM @BackupFiles WHERE Type = 'D';
SELECT @NewDatabaseLog = PhysicalName FROM @BackupFiles WHERE Type = 'L';
SET @NewDatabaseData = REPLACE(@NewDatabaseData, @TemplateDatabase, @NewDatabase);
SET @NewDatabaseLog = REPLACE(@NewDatabaseLog, @TemplateDatabase, @NewDatabase);
RESTORE DATABASE @NewDatabase FROM DISK = @TemplateBackups WITH CHECKSUM, RECOVERY, REPLACE, STATS = 100,
MOVE @TemplateDatabase TO @NewDatabaseData,
MOVE @TemplateDatabaseLog TO @NewDatabaseLog;
-- Change Logical File Name
DECLARE @SQL_SCRIPT VARCHAR(MAX)='
ALTER DATABASE [{NewDatabase}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [{NewDatabase}] MODIFY FILE (NAME=N''{TemplateDatabase}'', NEWNAME=N''{NewDatabase}'');
ALTER DATABASE [{NewDatabase}] MODIFY FILE (NAME=N''{TemplateDatabase}_log'', NEWNAME=N''{NewDatabase}_log'');
ALTER DATABASE [{NewDatabase}] SET MULTI_USER WITH ROLLBACK IMMEDIATE;
SELECT name AS logical_name, physical_name FROM SYS.MASTER_FILES WHERE database_id = DB_ID(N''{NewDatabase}'');
';
SET @SQL_SCRIPT = REPLACE(@SQL_SCRIPT, '{TemplateDatabase}', @TemplateDatabase);
SET @SQL_SCRIPT = REPLACE(@SQL_SCRIPT, '{NewDatabase}', @NewDatabase);
EXECUTE (@SQL_SCRIPT);
backkup set holds a backup of a database other than existing "tmp" database
합니다. 이해합니다.to
문구가 실제 물리적 경로 여야합니까MyTempCopy
?