@Tony the Lion:
Hi - I experienced some problems using your script, so I came up with a hybrid of your script and this post:
link
USE master;
GO
-- the original database (use 'SET @DB = NULL' to disable backup)
DECLARE @SourceDatabaseName varchar(200)
DECLARE @SourceDatabaseLogicalName varchar(200)
DECLARE @SourceDatabaseLogicalNameForLog varchar(200)
DECLARE @query varchar(2000)
DECLARE @DataFile varchar(2000)
DECLARE @LogFile varchar(2000)
DECLARE @BackupFile varchar(2000)
DECLARE @TargetDatabaseName varchar(200)
DECLARE @TargetDatbaseFolder varchar(2000)
-- ****************************************************************
SET @SourceDatabaseName = '[Source.DB]' -- Name of the source database
SET @SourceDatabaseLogicalName = 'Source_DB' -- Logical name of the DB ( check DB properties / Files tab )
SET @SourceDatabaseLogicalNameForLog = 'Source_DB_log' -- Logical name of the DB ( check DB properties / Files tab )
SET @BackupFile = 'C:Tempackup.dat' -- FileName of the backup file
SET @TargetDatabaseName = 'TargetDBName' -- Name of the target database
SET @TargetDatbaseFolder = 'C:Temp'
-- ****************************************************************
SET @DataFile = @TargetDatbaseFolder + @TargetDatabaseName + '.mdf';
SET @LogFile = @TargetDatbaseFolder + @TargetDatabaseName + '.ldf';
-- Backup the @SourceDatabase to @BackupFile location
IF @SourceDatabaseName IS NOT NULL
BEGIN
SET @query = 'BACKUP DATABASE ' + @SourceDatabaseName + ' TO DISK = ' + QUOTENAME(@BackupFile,'''')
PRINT 'Executing query : ' + @query;
EXEC (@query)
END
PRINT 'OK!';
-- Drop @TargetDatabaseName if exists
IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TargetDatabaseName)
BEGIN
SET @query = 'DROP DATABASE ' + @TargetDatabaseName
PRINT 'Executing query : ' + @query;
EXEC (@query)
END
PRINT 'OK!'
-- Restore database from @BackupFile into @DataFile and @LogFile
SET @query = 'RESTORE DATABASE ' + @TargetDatabaseName + ' FROM DISK = ' + QUOTENAME(@BackupFile,'''')
SET @query = @query + ' WITH MOVE ' + QUOTENAME(@SourceDatabaseLogicalName,'''') + ' TO ' + QUOTENAME(@DataFile ,'''')
SET @query = @query + ' , MOVE ' + QUOTENAME(@SourceDatabaseLogicalNameForLog,'''') + ' TO ' + QUOTENAME(@LogFile,'''')
PRINT 'Executing query : ' + @query
EXEC (@query)
PRINT 'OK!'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…