itsource

SQL Server 2008 Express에서 동일한 서버에 SQL Server 데이터베이스를 복제하려면 어떻게 해야 합니까?

mycopycode 2023. 4. 7. 21:15
반응형

SQL Server 2008 Express에서 동일한 서버에 SQL Server 데이터베이스를 복제하려면 어떻게 해야 합니까?

MS SQL Server 2008 Express 시스템은 (테스트를 위해) '복사 및 이름 변경'을 원하는 데이터베이스를 포함하고 있지만, 이를 실현하는 간단한 방법을 알지 못합니다.

SQL Server의 R2 버전에는 데이터베이스 복사 마법사가 있지만 업그레이드할 수 없습니다.

문제의 데이터베이스는 긱에 관한 것입니다.복사할 데이터베이스의 백업을 새 데이터베이스로 복원하려고 했지만 잘 되지 않았습니다.

  1. Microsoft SQL Management Studio를 설치합니다. Microsoft SQL Management Studio는 Microsoft 웹 사이트에서 무료로 다운로드할 수 있습니다.

    버전 2008

    Microsoft SQL Management Studio 2008은 고급 서비스를 갖춘 SQL Server 2008 Express의 일부입니다.

    버전 2012

    다운로드 버튼을 클릭하여 확인합니다.ENU\x64\SQLManagementStudio_x64_ENU.exe

    버전 2014

    다운로드 버튼을 클릭하여 Mgmt Studio를 확인합니다.64BIT\SQLManagementStudio_x64_ENU.exe

  2. Microsoft SQL Management Studio를 엽니다.

  3. 원래 데이터베이스를 에 백업합니다.BAK 파일(db -> 태스크 -> 백업).
  4. 새 이름(복제)으로 빈 데이터베이스를 만듭니다.이것은 옵션이기 때문에, 이하의 코멘트에 주의해 주세요.
  5. 를 열려면 하십시오(이미지).복원 대화 상자
  6. Device(디바이스)를 선택하고 스텝3부터 백업파일을 추가합니다. 백업 파일 추가
  7. database로 합니다.수신처를 변경하다
  8. 데이터베이스 파일의 위치를 변경합니다. 원본과 달라야 합니다.텍스트 상자에 직접 입력할 수 있습니다.postfix만 추가하면 됩니다.(주의: 순서는 중요합니다.체크박스를 켜고 파일 이름을 변경합니다.) 장소를 변경하다
  9. WITH 및 WITH KEEP_REPLICATION을 합니다.교환하여

하여 [ ]을 클릭합니다.Tasks을 클릭합니다.Copy Database...이치노

데이터베이스를 분리하고 명령 프롬프트에서 파일을 새 이름으로 복사한 다음 두 DB를 모두 첨부할 수 있습니다.

SQL의 경우:

USE master;
GO 
EXEC sp_detach_db
    @dbname = N'OriginalDB';
GO

명령 프롬프트에서 (이 예시를 위해 파일 경로를 단순화했습니다)

copy c:\OriginalDB.mdf c:\NewDB.mdf
copy c:\OriginalDB.ldf c:\NewDB.ldf

SQL에서 다시:

USE master;
GO
CREATE DATABASE OriginalDB
    ON (FILENAME = 'C:\OriginalDB.mdf'),
       (FILENAME = 'C:\OriginalDB.ldf')
    FOR ATTACH;
GO
CREATE DATABASE NewDB
    ON (FILENAME = 'C:\NewDB.mdf'),
       (FILENAME = 'C:\NewDB.ldf')
    FOR ATTACH;
GO

백업에서 복원을 잘못 시도했음이 판명되었습니다.

처음에 새 데이터베이스를 만들고 여기서 백업을 복원하려고 했습니다.복원 대화 상자를 열고 대상 필드에 새 데이터베이스 이름을 입력해야 했습니다.

즉, 백업에서 복원하면 효과가 있었습니다.

여러분의 피드백과 제안에 감사드립니다.

이게 제가 쓰는 대본이에요.조금 까다롭지만 효과가 있다.SQL Server 2012에서 테스트 완료.

DECLARE @backupPath nvarchar(400);
DECLARE @sourceDb nvarchar(50);
DECLARE @sourceDb_log nvarchar(50);
DECLARE @destDb nvarchar(50);
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);

SET @sourceDb = 'db1'
SET @sourceDb_log = @sourceDb + '_log'
SET @backupPath = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\Backup\' + @sourceDb + '.bak'    --ATTENTION: file must already exist and SQL Server must have access to it
SET @sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET @destDb = 'db2'
SET @destMdf = @sqlServerDbFolder + @destDb + '.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + '_log' + '.ldf'

BACKUP DATABASE @sourceDb TO DISK = @backupPath

RESTORE DATABASE @destDb FROM DISK = @backupPath
WITH REPLACE,
   MOVE @sourceDb     TO @destMdf,
   MOVE @sourceDb_log TO @destLdf

SSMS에서:

1 - 원래 데이터베이스를 에 백업합니다.BAK 파일(your_source_db -> 태스크 -> 백업).

2 - '데이터베이스' 및 '데이터베이스 복원' 오른쪽 클릭

3 - [Device]> [ ... ( button ) ]> [ Add ]> [ your _ source _ db ]를 선택합니다.밧테루

4 - '일반' 탭의 '대상' 섹션에서 '데이터베이스'에서 your_source_db의 이름을 new_name_db로 변경합니다.

5 - '파일' 탭에서 '모든 파일을 폴더로 재배치합니다',

  • new_name_db(.mdf, _log.ldf)와의 일관성을 유지하기 위해 '다른 이름으로 복원' 열의 이름을 변경합니다.

6 - '옵션' 탭의 '복원 옵션' 섹션에서 두 개의 첫 번째 옵션('덮어쓰기...', '저장...')을 선택하고 '복구 상태'를 선택합니다.

  • 또한 'Tail-Log backup' 섹션의 옵션이 선택 해제되어 소스 DB가 'restoring state'로 유지되지 않도록 하십시오.

여기에 이미지 설명 입력

여기서 설명한 솔루션 중 어느 것도 효과가 없었습니다.SQL Server Management Studio 2014를 사용하고 있습니다.

대신 옵션 화면에서 Take tail-log backup before restore 체크박스를 꺼야 했습니다.내 버전에서는 이 체크박스가 기본적으로 켜져 있어 복원 작업이 완료되지 않습니다.이 체크박스를 끄면 복원 작업은 문제없이 진행되었습니다.

여기에 이미지 설명 입력

MS SQL Server 2012를 사용하려면 다음 3가지 기본 단계를 수행해야 합니다.

  1. " " " 를 생성합니다..sql

    • 소스 DB에서 마우스 오른쪽 단추를 누른 후 작업, 스크립트 생성
    • , 「」를 합니다..sql로 제출하다
  2. DB를 원본 DB의 ..sql

    • 대상 파일을 마우스 오른쪽 버튼으로 클릭하고 새 쿼리를 선택한 후 또는 (편집 - 찾기 및 바꾸기 - 빠른 바꾸기)
  3. 마지막으로 데이터 입력

    • 대상 DB에서 마우스 오른쪽 단추를 누른 다음 작업 및 데이터 가져오기선택합니다.
    • 데이터 원본 드롭다운이 ".net framework data provider for SQL server"로 설정됨 + DATA ex: 아래의 연결 문자열 텍스트 필드를 설정합니다.Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
    • 목적지에 대해서도 같은 일을 하다
    • 전송할 테이블을 선택하거나 "source: ..." 옆에 있는 체크박스를 켜고 모두 체크합니다.

이제 끝입니다.

데이터베이스의 크기가 크지 않은 경우 탐색기에서 데이터베이스 항목 자체의 컨텍스트 메뉴에 있는 SQL Server Management Studio Express의 '스크립트 데이터베이스' 명령을 볼 수 있습니다.

스크립팅할 모든 것을 선택할 수 있습니다.물론 오브젝트와 데이터가 필요합니다.그런 다음 스크립트 전체를 단일 파일에 저장합니다.그런 다음 이 파일을 사용하여 데이터베이스를 다시 만들 수 있습니다.USE명령어는 적절한 데이터베이스로 설정되어 있습니다.

SQL Server 2008 R2에서 데이터베이스를 파일로 폴더에 백업합니다.그런 다음 "데이터베이스" 폴더에 나타나는 복원 옵션을 선택합니다.마법사에서 대상 데이터베이스에 원하는 새 이름을 입력하십시오.restore frrom file을 선택하고 방금 작성한 파일을 사용합니다.저는 그것을 했고 매우 빨랐습니다(데이터베이스는 작았지만 그래도).

이 코멘트를 기반으로 한 솔루션: https://stackoverflow.com/a/22409447/2399045. DB name, temp folder, db files folder를 설정하기만 하면 됩니다.실행 후 "sourceDBName_yyy-mm-dd" 형식의 DB 복사본이 생성됩니다.

-- Settings --
-- New DB name will have name = sourceDB_yyyy-mm-dd
declare @sourceDbName nvarchar(50) = 'MyDbName';
declare @tmpFolder nvarchar(50) = 'C:\Temp\'
declare @sqlServerDbFolder nvarchar(100) = 'C:\Databases\'

--  Execution --
declare @sourceDbFile nvarchar(50);
declare @sourceDbFileLog nvarchar(50);
declare @destinationDbName nvarchar(50) = @sourceDbName + '_' + (select convert(varchar(10),getdate(), 121))
declare @backupPath nvarchar(400) = @tmpFolder + @destinationDbName + '.bak'
declare @destMdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '.mdf'
declare @destLdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '_log' + '.ldf'

SET @sourceDbFile = (SELECT top 1 files.name 
                    FROM sys.databases dbs 
                    INNER JOIN sys.master_files files 
                        ON dbs.database_id = files.database_id 
                    WHERE dbs.name = @sourceDbName
                        AND files.[type] = 0)

SET @sourceDbFileLog = (SELECT top 1 files.name 
                    FROM sys.databases dbs 
                    INNER JOIN sys.master_files files 
                        ON dbs.database_id = files.database_id 
                    WHERE dbs.name = @sourceDbName
                        AND files.[type] = 1)

BACKUP DATABASE @sourceDbName TO DISK = @backupPath

RESTORE DATABASE @destinationDbName FROM DISK = @backupPath
WITH REPLACE,
   MOVE @sourceDbFile     TO @destMdf,
   MOVE @sourceDbFileLog  TO @destLdf

Import/export 마법사를 사용하여 문제를 해결하는 다른 방법으로는 먼저 빈 데이터베이스를 작성한 후 소스 데이터베이스를 가진 서버를 선택한 후 대상 데이터베이스와 동일한 서버를 선택한 후(처음 작성한 빈 데이터베이스를 사용하여) 마침을 누릅니다.

모든 테이블을 만들고 모든 데이터를 새 데이터베이스로 전송합니다.

Joe 응답에 근거한 스크립트(파일의 삭제, 카피, 양쪽 모두 첨부)

  1. Administrator 계정으로 Management Studio를 실행합니다.

필수는 아니지만 실행 시 액세스 거부 오류가 발생할 수 있습니다.

  1. execute xp_cmdshel을 위한 SQL 서버 구성
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
  1. 스크립트를 실행하지만 db 이름을 입력합니다.@dbName그리고.@copyDBName를 참조해 주세요.
USE master;
GO 

DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'

-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
    INSERT INTO ##DBFileNames([FileName])
    SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')

-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')

EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')

-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')

-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE 
    @oldAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @dbName + ' ON ', 
    @newAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @copyDBName + ' ON '

DECLARE curs CURSOR FOR 
SELECT [filename] FROM ##DBFileNames
OPEN curs  
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0  
BEGIN
    SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
    SET @ext = RIGHT(@filename,4)
    SET @copyFileName = @path + @copyDBName + @ext

    SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
    PRINT @command
    EXEC(@command);

    SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
    SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'

    FETCH NEXT FROM curs INTO @filename
END
CLOSE curs 
DEALLOCATE curs

-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'

-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)

-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)

DROP TABLE ##DBFileNames

새 데이터베이스를 작성한 다음 태스크로 이동하여 데이터를 가져오고 복제하려는 데이터베이스에서 방금 작성한 데이터베이스로 모든 데이터를 가져올 수 있습니다.

이 프로그램은 데이터베이스를 다른 이름으로 동일한 서버에 복사합니다.저는 이 사이트에 나와 있는 몇 가지 개선 예에 의존했습니다.

-- Copies a database to the same server
-- Copying the database is based on backing up the original database and restoring with a different name

DECLARE @sourceDb nvarchar(50);    
DECLARE @destDb nvarchar(50);
DECLARE @backupTempDir nvarchar(200)

SET @sourceDb =  N'Northwind'         -- The name of the source database
SET @destDb =    N'Northwind_copy'    -- The name of the target database
SET @backupTempDir = N'c:\temp'       -- The name of the temporary directory in which the temporary backup file will be saved
-- --------- ---

DECLARE @sourceDb_ROWS nvarchar(50);  
DECLARE @sourceDb_LOG nvarchar(50);
DECLARE @backupPath nvarchar(400); 
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);

Declare @Ret as int = -1
Declare @RetDescription nvarchar(200) = ''

-- Temporary backup file name
SET @backupPath = @backupTempDir+ '\TempDb_' + @sourceDb + '.bak'    

-- Finds the physical location of the files on the disk
set @sqlServerDbFolder = (SELECT top(1) physical_name as dir
                           FROM sys.master_files where DB_NAME(database_id) = @sourceDb  );

-- Clears the file name and leaves the directory name
set @sqlServerDbFolder = REVERSE(SUBSTRING(REVERSE(@sqlServerDbFolder), CHARINDEX('\', REVERSE(@sqlServerDbFolder)) + 1, LEN(@sqlServerDbFolder))) + '\'

-- Finds the logical name for the .mdf file
set @sourceDb_ROWS = (SELECT f.name LogicalName FROM sys.master_files f INNER JOIN sys.databases d ON d.database_id = f.database_id
                      where d.name = @sourceDb  and   f.type_desc = 'ROWS' )

-- Finds the logical name for the .ldf file
set @sourceDb_LOG = (SELECT f.name LogicalName FROM sys.master_files f INNER JOIN sys.databases d ON d.database_id = f.database_id
                      where d.name = @sourceDb  and   f.type_desc = 'LOG' )

-- Composes the names of the physical files for the new database  
SET @destMdf = @sqlServerDbFolder + @destDb + N'.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + N'_log' + N'.ldf'

-- If the source name is the same as the target name does not perform the operation
if @sourceDb <> @destDb      
    begin 

    -- Checks if the target database already exists
    IF Not EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = @destDb)
    begin 
        -- Checks if the source database exists
        IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = @sourceDb) and (@sqlServerDbFolder is not null)
        begin 

            -- Opens the permission to run xp_cmdshell
            EXEC master.dbo.sp_configure 'show advanced options', 1
            RECONFIGURE WITH OVERRIDE
            EXEC master.dbo.sp_configure 'xp_cmdshell', 1
            RECONFIGURE WITH OVERRIDE
         
            -- If the temporary backup directory does not exist it creates it
            declare @md as nvarchar(100) = N'if not exist ' + @backupTempDir + N' md ' +@backupTempDir  
            exec xp_cmdshell  @md,  no_output

            -- Creates a backup to the source database to the temporary file
            BACKUP DATABASE @sourceDb TO DISK = @backupPath 

            -- Restores the database with a new name
            RESTORE DATABASE @destDb FROM DISK = @backupPath
            WITH REPLACE, 
            MOVE @sourceDb_ROWS TO @destMdf, 
            MOVE @sourceDb_LOG TO  @destLdf

            -- Deletes the temporary backup file
            declare @del as varchar(100) = 'if exist ' + @backupPath +' del ' +@backupPath 
            exec xp_cmdshell  @del ,  no_output

            -- Close the permission to run xp_cmdshell
            EXEC master.dbo.sp_configure 'xp_cmdshell', 0
            RECONFIGURE WITH OVERRIDE
            EXEC master.dbo.sp_configure 'show advanced options', 0
            RECONFIGURE WITH OVERRIDE
         
            set @ret = 1
            set @RetDescription = 'The ' +@sourceDb + ' database was successfully copied to ' + @destDb 
        
        end
        else
        begin
          set @RetDescription = 'The source database '''+ @sourceDb + ''' is not exists.'
          set @ret = -3
        end

    end
    else
    begin
      set @RetDescription = 'The target database '''+ @destDb + ''' already exists.'
      set @ret = -4
    end
end
else
begin
  set @RetDescription = 'The target database ''' +@destDb + ''' and the source database '''+ @sourceDb + ''' have the same name.'
  set @ret = -5
end

select @ret as Ret, @RetDescription as RetDescription

<!doctpe html>

<head>
    <title>Copy Database</title>
</head>

<body>
    
    <?php
    
    $servername = "localhost:xxxx";
    $user1 = "user1";
    $pw1 = "pw1";
    $db1 = "db1";
    
    $conn1 = new mysqli($servername,$user1,$pw1,$db1);
    
    if($conn1->connect_error) {
        die("Conn1 failed: " . $conn1->connect_error);
    }
    
    $user2 = "user2";
    $pw2 = "pw2";
    $db2 = "db2";
    
    $conn2 = new mysqli($servername,$user2,$pw2,$db2);
    
    if($conn2->connect_error) {
        die("Conn2 failed: " . $conn2->connect_error);
    }
    
    $sqlDB1 = "SELECT * FROM table1";
    $resultDB1 = $conn1->query($sqlDB1);
    
    if($resultDB1->num_rows > 0) {
        while($row = $resultDB1->fetch_assoc()) {
            $sqlDB2 = "INSERT INTO table2 (col1, col2) VALUES ('" . $row["tableRow1"] . "','" . $row["tableRow2"] . "')";
            $resultDB2 = $conn2->query($sqlDB2);
        }
    }else{
        echo "0 results";
    }
    
    $conn1->close();
    $conn2->close();
    
    ?>
    
</body>

MS SQL 2014 이후인 경우

DBCC CLONEDATABASE (CurrentDBName, NewDBName)
GO

상세

언급URL : https://stackoverflow.com/questions/3829271/how-can-i-clone-an-sql-server-database-on-the-same-server-in-sql-server-2008-exp

반응형