SQL script to “copy” a database

后端 未结 7 612
名媛妹妹
名媛妹妹 2020-12-14 20:46

I want to write a SQL script that will copy a database on the same server. I could do a backup/restore, but I think it might be faster to just \"copy\" somehow. Does anyon

7条回答
  •  死守一世寂寞
    2020-12-14 21:35

    @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:\Temp\backup.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!'
    

提交回复
热议问题