SQL Server 미 러 자동 생 성 스 크 립 트

107120 단어
SQL Server 미 러 자동 생 성 스 크 립 트
 
거울의 구축 은 매우 번 거 로 워 서 약간의 시간 을 들 여 이 각본 을 써 서 모두 가 거울의 구축 을 편리 하 게 했다
이 미 러 스 크 립 트 를 실행 한 후, 모든 기계 에 hosts 파일 을 연결 하 는 것 이 좋 습 니 다. 그렇지 않 으 면 미 러 가 작 동 하지 않 을 수도 있 습 니 다.
192.168.1.1 WSQL01192.168.1.2 WSQL02192.168.1.3 WWEB03
 
SQL 2008 R2 를 SQL 2014 로 업그레이드 하기 전에 데이터 베 이 스 를 완전 하고 로그 백업 하여 업그레이드 에 실패 하지 않도록 합 니 다.
 
주의: - ★ Do 부분 은 모두 작성 해 야 합 니 다.
-- =============================================
-- Author:      
-- Blog:        
-- Create date: <2013/8/18>
-- Description: 
-- =============================================


--



DECLARE @DBName NVARCHAR(255)
DECLARE @masterip NVARCHAR(255)
DECLARE @mirrorip NVARCHAR(255)
DECLARE @witness NVARCHAR(255)
DECLARE @masteriptail NVARCHAR(255)
DECLARE @mirroriptail NVARCHAR(255)
DECLARE @witnesstail NVARCHAR(255)
DECLARE @certpath NVARCHAR(MAX)
DECLARE @Restorepath NVARCHAR(MAX)
DECLARE @Restorepath1 NVARCHAR(MAX)
DECLARE @Restorepath2 NVARCHAR(MAX)
DECLARE @MKPASSWORD NVARCHAR(500)
DECLARE @LOGINPWD NVARCHAR(500)
DECLARE @LISTENER_PORT  NVARCHAR(500)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @MASTERHOST_NAME NVARCHAR(50)
DECLARE @SLAVEHOST_NAME NVARCHAR(50)
DECLARE @WITNESSHOST_NAME NVARCHAR(50)


if OBJECT_ID ('tempdb..#temp')is not null 
BEGIN 
 DROP TABLE #BackupFileList
END

CREATE TABLE #BackupFileList 
    (
      LogicalName NVARCHAR(100) ,
      PhysicalName NVARCHAR(100) ,
      BackupType CHAR(1) ,
      FileGroupName NVARCHAR(50) ,
      SIZE BIGINT ,
      MaxSize BIGINT ,
      FileID BIGINT ,
      CreateLSN BIGINT ,
      DropLSN BIGINT NULL ,
      UniqueID UNIQUEIDENTIFIER ,
      ReadOnlyLSN BIGINT NULL ,
      ReadWriteLSN BIGINT NULL ,
      BackupSizeInBytes BIGINT ,
      SourceBlockSize INT ,
      FileGroupID INT ,
      LogGroupGUID UNIQUEIDENTIFIER NULL ,
      DifferentialBaseLSN BIGINT NULL ,
      DifferentialBaseGUID UNIQUEIDENTIFIER ,
      IsReadOnly BIT ,
      IsPresent BIT ,
      TDEThumbprint NVARCHAR(100)
    )


SET NOCOUNT ON

SET @masterip='172.16.198.254'  --★Do
SET @mirrorip='172.16.198.253'   --★Do
SET @witness='999999'   --★Do
--          : \
SET @certpath='D:\DBBackup'   --★Do
SET @Restorepath='D:\DBBackup'   --★Do
SET @DBName='testmirror'               --★Do
SET @MKPASSWORD='master@2015key123' --★Do
SET @LOGINPWD='User_Pass@2015key123'  --★Do
SET @LISTENER_PORT='5022'  --★Do
SET @MASTERHOST_NAME='A'  --★Do
SET @SLAVEHOST_NAME='B'  --★Do
SET @WITNESSHOST_NAME='C'  --★Do






select @masteriptail= PARSENAME(@masterip,2)+'_'+PARSENAME(@masterip,1) 
select @mirroriptail= PARSENAME(@mirrorip,2)+'_'+PARSENAME(@mirrorip,1) 
select @witnesstail= PARSENAME(@witness,2)+'_'+PARSENAME(@witness,1) 


--------------------------------------------------------------------------------
DECLARE @stat NVARCHAR(MAX)

SET  @stat='--        V1 By huazai'
PRINT @stat
PRINT CHAR(13)+CHAR(13)




SET  @stat='--0、                  ,   sql     '+CHAR(13)
+'--  '+CHAR(13)
+'SELECT [name], [recovery_model_desc] FROM sys.[databases]'+CHAR(13)+CHAR(13)+CHAR(13)

PRINT '-- :'+@masterip
PRINT '-- :'+@mirrorip
PRINT '--  :'+@witness
PRINT CHAR(13)+CHAR(13)
PRINT @stat

--------------------------------------------------------------------
PRINT '-- ============================================='

SET  @stat='--1、                      Master Key 、     '+CHAR(13)
+'--  '+CHAR(13)
+'USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '''+@MKPASSWORD+''';'
+'CREATE CERTIFICATE HOST_'
+@masteriptail
+'_cert  WITH SUBJECT = ''HOST_'
+@masteriptail
+'_certificate'','+CHAR(13)
+'START_DATE = ''09/20/2010'',EXPIRY_DATE = ''01/01/2099'';'+CHAR(13)

PRINT @stat


SET  @stat='--  '+CHAR(13)
+'USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '''+@MKPASSWORD+''';'
+'CREATE CERTIFICATE HOST_'
+@mirroriptail
+'_cert  WITH SUBJECT = ''HOST_'
+@mirroriptail
+'_certificate'','+CHAR(13)
+'START_DATE = ''09/20/2010'',EXPIRY_DATE = ''01/01/2099'';'+CHAR(13)

PRINT @stat


SET  @stat='--  '+CHAR(13)
+'USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '''+@MKPASSWORD+''';'
+'CREATE CERTIFICATE HOST_'
+@witnesstail
+'_cert  WITH SUBJECT = ''HOST_'
+@witnesstail
+'_certificate'','+CHAR(13)
+'START_DATE = ''09/20/2010'',EXPIRY_DATE = ''01/01/2099'';'+CHAR(13)+CHAR(13)+CHAR(13)+CHAR(13)

PRINT @stat

-----------------------------------------------------------

PRINT '-- ============================================='


SET  @stat='--2、      ,                  '+CHAR(13)
+'--  '+CHAR(13)
+'CREATE ENDPOINT Endpoint_Mirroring 
STATE = STARTED 
AS 
TCP ( LISTENER_PORT='+@LISTENER_PORT+' , LISTENER_IP = ALL ) 
FOR 
DATABASE_MIRRORING 
( AUTHENTICATION = CERTIFICATE HOST_'
+@masteriptail
+'_cert  , ENCRYPTION = REQUIRED ALGORITHM AES , ROLE = ALL );'+CHAR(13)

PRINT @stat

SET  @stat='--  '+CHAR(13)
+'CREATE ENDPOINT Endpoint_Mirroring 
STATE = STARTED 
AS 
TCP ( LISTENER_PORT='+@LISTENER_PORT+' , LISTENER_IP = ALL ) 
FOR 
DATABASE_MIRRORING 
( AUTHENTICATION = CERTIFICATE HOST_'
+@mirroriptail
+'_cert  , ENCRYPTION = REQUIRED ALGORITHM AES , ROLE = ALL );'+CHAR(13)

PRINT @stat


SET  @stat='--  '+CHAR(13)
+'CREATE ENDPOINT Endpoint_Mirroring
STATE = STARTED
AS
TCP ( LISTENER_PORT='+@LISTENER_PORT+' , LISTENER_IP = ALL )
FOR
DATABASE_MIRRORING
( AUTHENTICATION = CERTIFICATE HOST_'
+@witnesstail
+'_cert  , ENCRYPTION = REQUIRED ALGORITHM AES , ROLE = ALL );'+CHAR(13)+CHAR(13)+CHAR(13)

PRINT @stat

----------------------------------------------------------------------------------------

PRINT '-- ============================================='


SET  @stat='--3、    ,      '+CHAR(13)
+'--  '+CHAR(13)
+'BACKUP CERTIFICATE HOST_'
+@masteriptail
+'_cert TO FILE = '+''''+@certpath+'\HOST_'+@masteriptail+'_cert.cer'';'+CHAR(13)

PRINT @stat

SET  @stat='--  '+CHAR(13)
+'BACKUP CERTIFICATE HOST_'
+@mirroriptail
+'_cert TO FILE = '+''''+@certpath+'\HOST_'+@mirroriptail+'_cert.cer'';'+CHAR(13)

PRINT @stat


SET  @stat='--  '+CHAR(13)
+'BACKUP CERTIFICATE HOST_'
+@witnesstail
+'_cert TO FILE = '+''''+@certpath+'\HOST_'+@witnesstail+'_cert.cer'';'+CHAR(13)+CHAR(13)+CHAR(13)

PRINT @stat


----------------------------------------------------------------------------------

PRINT '-- ============================================='


SET  @stat='--4、          '+CHAR(13)
+'--  '+CHAR(13)
+'CREATE LOGIN ['+@SLAVEHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@SLAVEHOST_NAME+'User] FOR LOGIN ['+@SLAVEHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@mirroriptail
+'_cert AUTHORIZATION ['+@SLAVEHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@mirroriptail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@SLAVEHOST_NAME+'LoginUser];'+CHAR(13)

PRINT @stat






SET  @stat='CREATE LOGIN ['+@WITNESSHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@WITNESSHOST_NAME+'User] FOR LOGIN ['+@WITNESSHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@witnesstail+
+'_cert AUTHORIZATION ['+@WITNESSHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@witnesstail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@WITNESSHOST_NAME+'LoginUser];'+CHAR(13)

PRINT @stat





SET  @stat='--  '+CHAR(13)
+'CREATE LOGIN ['+@MASTERHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@MASTERHOST_NAME+'User] FOR LOGIN ['+@MASTERHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@masteriptail
+'_cert AUTHORIZATION ['+@MASTERHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@masteriptail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@MASTERHOST_NAME+'LoginUser];'+CHAR(13)

PRINT @stat



SET  @stat='CREATE LOGIN ['+@WITNESSHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@WITNESSHOST_NAME+'User] FOR LOGIN ['+@WITNESSHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@witnesstail+
+'_cert AUTHORIZATION ['+@WITNESSHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@witnesstail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@WITNESSHOST_NAME+'LoginUser];'+CHAR(13)


PRINT @stat




SET  @stat='--  '+CHAR(13)
+'CREATE LOGIN ['+@MASTERHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@MASTERHOST_NAME+'User] FOR LOGIN ['+@MASTERHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@masteriptail
+'_cert AUTHORIZATION ['+@MASTERHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@masteriptail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@MASTERHOST_NAME+'LoginUser];'+CHAR(13)

PRINT @stat






SET  @stat='CREATE LOGIN ['+@SLAVEHOST_NAME+'LoginUser] WITH PASSWORD = '''+@LOGINPWD+'''; 
CREATE USER ['+@SLAVEHOST_NAME+'User] FOR LOGIN ['+@SLAVEHOST_NAME+'LoginUser]; 
CREATE CERTIFICATE HOST_'
+@mirroriptail
+'_cert AUTHORIZATION ['+@SLAVEHOST_NAME+'User] FROM FILE ='''+@certpath+'\HOST_'+@mirroriptail+'_cert.cer'';'+CHAR(13)
+'GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO ['+@SLAVEHOST_NAME+'LoginUser];'+CHAR(13)

PRINT @stat

------------------------------------------------------------------------------

PRINT '-- ============================================='



SET  @stat='--5、       5022  ,   telnet  5022                   bat   '+CHAR(13)
PRINT @stat

SET  @stat='echo   '+CHAR(13)
+'telnet '+@mirrorip+' 5022'+CHAR(13)
+'telnet '+@witness+' 5022'+CHAR(13)
+'pause'

PRINT @stat+CHAR(13)+CHAR(13)

SET  @stat='echo    '+CHAR(13)
+'telnet '+@masterip+' 5022'+CHAR(13)
+'telnet '+@witness+' 5022'+CHAR(13)
+'pause'

PRINT @stat+CHAR(13)+CHAR(13)

SET  @stat='echo   '+CHAR(13)
+'telnet '+@masterip+' 5022'+CHAR(13)
+'telnet '+@mirrorip+' 5022'+CHAR(13)
+'pause'

PRINT @stat+CHAR(13)+CHAR(13)+CHAR(13)


--------------------------------------------------------------

PRINT '-- ============================================='



SET  @stat='--6、     (    +      )     '+CHAR(13)
PRINT @stat

SET  @stat='DECLARE @FileName NVARCHAR(MAX)'+CHAR(13)+CHAR(13)

PRINT @stat


SET  @stat='--('+@DBName+'       )     '+CHAR(13)
+'SET @FileName = ''D:\DBBackup\'+@DBName+'_FullBackup_1.bak''
BACKUP DATABASE ['+@DBName+']
TO DISK=@FileName WITH FORMAT ,COMPRESSION'+CHAR(13)+CHAR(13)

PRINT @stat


SET  @stat='--('+@DBName+'       )     '+CHAR(13)
+'SET @FileName = ''D:\DBBackup\'+@DBName+'_logBackup_2.bak''
BACKUP LOG ['+@DBName+']
TO DISK=@FileName WITH FORMAT ,COMPRESSION'

PRINT @stat+CHAR(13)+CHAR(13)+CHAR(13)

------------------------------------------------------------------------------

PRINT '-- ============================================='


SET  @stat='--7、     (  norecovery    )     '+CHAR(13)
PRINT @stat

SET  @Restorepath1=''

SET @Restorepath2=@Restorepath+@DBName+'_FullBackup_1.bak'
SET @SQL = 'RESTORE FILELISTONLY  FROM DISK = '''+@Restorepath2+''''  

INSERT INTO #BackupFileList EXEC (@SQL);

 DECLARE @LNAME NVARCHAR(2000)
  DECLARE @PNAME NVARCHAR(2000)


        DECLARE CurTBName CURSOR
        FOR
            SELECT LogicalName,PhysicalName
            FROM    #BackupFileList  

        OPEN CurTBName
        FETCH NEXT FROM CurTBName INTO @LNAME,@PNAME

        WHILE @@FETCH_STATUS = 0
            BEGIN  
             SET  @Restorepath1=' MOVE N'''+@LNAME+''' TO N'''+@PNAME+''', '+CHAR(13)+@Restorepath1


                FETCH NEXT FROM CurTBName INTO  @LNAME,@PNAME
            END
        CLOSE CurTBName
        DEALLOCATE CurTBName




SET  @stat='USE [master]
RESTORE DATABASE '+@DBName+' FROM  DISK = N'''+@Restorepath+@DBName+'_FullBackup_1.bak'' WITH  FILE = 1,'+CHAR(13)
+@Restorepath1
+'NOUNLOAD,NORECOVERY,  REPLACE,  STATS = 5
GO'

SET  @stat='USE [master]
RESTORE LOG '+@DBName+' FROM  DISK = N'''+@Restorepath+@DBName+'_logBackup_2.bak'' WITH  FILE = 1,'+CHAR(13)
+'NOUNLOAD,NORECOVERY,  REPLACE,  STATS = 5
GO'



PRINT @stat+CHAR(13)+CHAR(13)

DROP TABLE #BackupFileList

--------------------------------------------------------------------------------

PRINT '-- ============================================='



SET  @stat='--8、      ,         ,     ,      ,          FULL'+CHAR(13)
PRINT @stat




SET  @stat='--     '+CHAR(13)
+'USE [master]
GO

ALTER DATABASE ['+@DBName+'] SET PARTNER = '''+'TCP://'+@masterip+':5022'';  --      ip'+CHAR(13)+CHAR(13)

PRINT @stat


SET  @stat='--     '+CHAR(13)
+'USE [master]
GO

ALTER DATABASE ['+@DBName+'] SET PARTNER = '''+'TCP://'+@mirrorip+':5022'';  --      ip'+CHAR(13)+CHAR(13)

PRINT @stat

SET  @stat='ALTER DATABASE ['+@DBName+'] SET WITNESS = '''+'TCP://'+@witness+':5022'';  --      ip'+CHAR(13)+CHAR(13)

PRINT @stat

도움 이 됐 으 면 좋 겠 습 니 다.
 
 
마지막 으로 미 러 관련 스 크 립 트 를 첨부 합 니 다.
--=================================
--    

SELECT  DB_NAME([database_id]) as 'dbname',* FROM sys.[database_mirroring]
GO

ALTER DATABASE [test] SET PARTNER OFF
ALTER DATABASE [test] SET WITNESS OFF

--=================================
--    
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER RESUME
GO

--=================================
--      
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER SUSPEND 
GO


--===================================================
--               
WITH tmp AS(
SELECT
DB_NAME(Database_id) AS DatabaseName,
ROW_NUMBER()OVER(PARTITION BY Database_id ORDER BY local_time DESC) AS RID,
*
FROM msdb.dbo.dbm_monitor_data
)
SELECT *  FROM tmp
WHERE RID=1

--   redo_queue  send_queue



--=================================
--    
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER OFF
GO
 
--=================================
--       
USE [master]
GO
ALTER DATABASE [Demo1] SET WITNESS OFF
GO
 
--=================================
--        
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER SAFETY OFF
GO
 
--=================================
--        
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER SAFETY FULL
GO
 
--=================================
--           (      )
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER FAILOVER
GO
 
--=================================
--           (      ),         
--       
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS
GO
 
--=================================
--             
--             ,         ,    SQL     
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER RESUME
GO
 
--=================================
--                
USE [master]
GO
RESTORE DATABASE [Demo1] WITH RECOVERY
GO
 

--=================================
--        
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER SAFETY FULL
GO


--=================================
--           (      ),         
--       
USE [master]
GO
ALTER DATABASE [Demo1] SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS
GO

 
레벨 업 후
USE [master]
GO


ALTER DATABASE [testmirror] SET COMPATIBILITY_LEVEL = 120
GO


/****** Object:  Endpoint [Endpoint_Mirroring]    Script Date: 2016/12/29 9:23:18 ******/
DROP ENDPOINT [Endpoint_Mirroring]
GO

 
 
관련 보기
https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-mirroring-transact-sql
 
 
잘못된 점 이 있 으 면 벽돌 을 찍 는 것 을 환영 합 니 다 o (∩ ∩) o 
본 논문 의 판권 은 작가 의 소유 이 며, 작가 의 동의 없 이 전재 할 수 없다.

좋은 웹페이지 즐겨찾기