주요 편집
이것은이 답변을 완전히 재 작성한 것입니다 (이전 버전은 오류가 발생하기 쉬웠으며 문제가 발생할 수 있다는 유효한 비판을 받았습니다)
Youtube-SQL Server Replication : 스냅 샷을 작성하지 않고 기사를 추가하는 방법에 이것을 적용하는 방법에 대한 데모도 게시했습니다 .
중요 : 이것은 NOT 당신이 그것을 수행 작업 받고 관련하여 자신에있을 것입니다 때문에, Microsoft에서 권장되는 접근 하지 중요한 고립 테스트없이 프로덕션 환경에 직접 적용하고 단계를 자신이 편안 받고!
따라야 할 단계 :
Planning steps:
* Choose Publication that article will be added to
* Gather information about the publication
exec sp_helppublication '[Name of Publication]'
https://msdn.microsoft.com/en-us/library/ms189782(v=sql.105).aspx
- replication frequency = 0 - this is Transactional replication (THIS IS A REQUIREMENT FOR THIS METHOD)
- replicate_ddl = 1 - means ALTER TABLES will apply SQL Server generated repl procs
- independent_agent = 1 - means that you will only affect tables in this publication when deploying
* Identify which subscribers are going to be affected
Pre-deployment steps (can be done at any time)
1. Create table on subscribers
2. Create custom replication procs on subscribers
(Customisation will ignore if the IUD has already been applied to subscriber - because you have manually sync'd the data)
Deployment/Potential impact:
3. Stop Distribution Agents to all subscribers for this publication
4. Add article to publication on publisher
5. Sync data from publisher to subscriber
6. Start Distribution Agents to all subscribers for this publication
7. Monitor/Verify all data has arrived
Optional follow on:
8. Apply standard repl procs (removing if not exists checks)
This is optional as the generated repl scripts should be fine for the most part
Note: When ALTER table scripts are applied on the Publisher (when replicate_ddl = 1) repl procs will automatically be recreated by the Distribution Agent (so any customisation will be lost)
확인하려면 :
- 게시자에 삽입 수행-구독자에 행이 도착하는지 확인
- 게시자 업데이트 수행-구독자에게 변경 사항이 도착했는지 확인
- 게시자에서 삭제 수행-구독자에서 삭제 된 행 확인
- 마지막 n 개의 행이 도착했는지와 게시자와 구독자간에 일치하는지 확인하십시오.
예 프로세스
A) 게시자에게 테이블을 만드십시오.
/* Deliberately applying IDENTITY, DEFAULT & INDEX to demonstrate usage on subscriber */
CREATE TABLE [dbo].[TableNotUsingSnap](
[Id] [int] NOT NULL IDENTITY(1,1),
[Note_Text] [varchar](4096) NOT NULL,
[CreatedDate] [datetime] NULL,
[LoggedDate] [datetime] NOT NULL CONSTRAINT DF_TableNotUsingSnap_LoggedDate DEFAUlT GETUTCDATE(),
CONSTRAINT [PK_TableNotUsingSnap] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_NC_TableNotUsingSnap_LoggedDate] ON [dbo].[TableNotUsingSnap]
(
[LoggedDate] ASC
) INCLUDE ([Note_Text])
GO
B) [TableNotUsingSnap]에서 일부 삽입 / 업데이트 / 삭제를 수행하는 작업 / 프로세스 / 스크립트를 작성하십시오 (이 메소드를 사용하여 구독자가 올바르게 동기화되는 방법을 유효성 검증 할 수 있음).
사전 단계 :
1. 구독자에 테이블 만들기
/* example script to add a table to a publication without running the snapshot agent
Steps:
Pre steps:
1. Create table on subscribers
2. Create replication procs on subscribers
Deployment/Potential impact:
3. Stop Distribution Agents to all subscribers for this publication
4. Add article to publication on publisher
5. DTS data from publisher to subscriber
6. Start Distribution Agents to all subscribers for this publication
7. Monitor/Verify all data has arrived
=========================================================
Notes:
* Drop unnecessary FK's, Indexes
* Do NOT have IDENTITY(1,1), DEFAULTS
* Do have a Clustered PK
* Create appropriate indexes for your subscribers use case */
-- RUN ON SUBSCRIBER
IF OBJECT_ID('dbo.TableNotUsingSnap') IS NOT NULL
exec sp_rename 'dbo.TableNotUsingSnap', 'TableNotUsingSnap_20170127'
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TableNotUsingSnap](
[Id] [int] NOT NULL,
[Note_Text] [varchar](4096) NOT NULL,
[CreatedDate] [datetime] NULL,
[LoggedDate] [datetime] NOT NULL,
CONSTRAINT [PK_TableNotUsingSnap] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
2. 구독자에서 복제 저장 프로 시저 만들기 (업데이트 / 삽입 / 삭제)
repl procs를 만들 수 있습니다 :
- 수동 (실수하기가 매우 쉽습니다)
- Dev 시스템에서 MS Snapshot 방법을 사용하여 기사를 추가하고 repl procs를 스크립트로 작성하십시오 (트윅을 추가 할 준비가되었습니다).
- 일종의 발전기 생성 / 찾기
적용해야 할 변경 사항 :
- sp_MSins_ [Schema] [TableName]-
IF NOT EXISTS (SELECT 'row already exists' FROM [Schema].[TableName] dest WITH (NOLOCK) WHERE dest.Id = @c1)
삽입되어 있지 않으면 추가하십시오.
- sp_MSupd_ [Schema] [TableName]-
IF @@rowcount = 0 ... exec sp_MSreplraiserror ...
적용되지 않은 업데이트를 무시하도록 주석 처리 (데이터를 동기화하기 전에 게시자에서 레코드가 삭제되었을 수 있음)
- sp_MSdel_ [Schema] [TableName]-
IF @@rowcount = 0 ... exec sp_MSreplraiserror ...
적용되지 않은 삭제를 무시하도록 주석 처리 (데이터를 동기화하기 전에 게시자에서 레코드가 삭제되었을 수 있음)
sp_MSins_dboTableNotUsingSnap :
/* Customised Replication insert proc utilized to support adding to replication without a snapshot. */
create procedure [dbo].[sp_MSins_dboTableNotUsingSnap]
@c1 int,
@c2 varchar(4096),
@c3 datetime
AS
BEGIN
IF NOT EXISTS (SELECT 'row already exists' FROM [dbo].[TableNotUsingSnap] dest WITH (NOLOCK) WHERE dest.Id = @c1)
BEGIN
insert into [dbo].[TableNotUsingSnap]
([Id],
[Note_Text],
[Repl_Upsert_UTC])
values
(@c1,
@c2,
@c3)
END
END
GO
sp_MSupd_dboTableNotUsingSnap :
/* Customised Replication insert proc utilized to support adding to replication without a snapshot. */
create procedure [dbo].[sp_MSupd_dboTableNotUsingSnap]
@c1 int = NULL,
@c2 varchar(4096) = NULL,
@c3 datetime = NULL,
@pkc1 int = NULL,
@bitmap binary(1)
AS
BEGIN
declare @primarykey_text nvarchar(100) = ''
if (substring(@bitmap,1,1) & 1 = 1)
begin
update [dbo].[TableNotUsingSnap]
set [Id] = case substring(@bitmap,1,1) & 1 when 1 then @c1 else [Id] end,
[Note_Text] = case substring(@bitmap,1,1) & 2 when 2 then @c2 else [Note_Text] end,
[Repl_Upsert_UTC] = case substring(@bitmap,1,1) & 4 when 4 then @c3 else [Repl_Upsert_UTC] END
WHERE [Id] = @pkc1
/* Commented out while adding to publication
if @@rowcount = 0
if @@microsoftversion>0x07320000
Begin
set @primarykey_text = @primarykey_text + '[id] = ' + convert(nvarchar(100),@pkc1,1)
exec sp_MSreplraiserror @errorid=20598, @param1=N'[dbo].[TableNotUsingSnap]', @param2=@primarykey_text, @param3=13233
End */
END
ELSE
BEGIN
update [dbo].[TableNotUsingSnap]
set [Note_Text] = case substring(@bitmap,1,1) & 2 when 2 then @c2 else [Note_Text] end,
[Repl_Upsert_UTC] = case substring(@bitmap,1,1) & 4 when 4 then @c3 else [Repl_Upsert_UTC] END
WHERE [Id] = @pkc1
/* Commented out while adding to publication
if @@rowcount = 0
if @@microsoftversion>0x07320000
Begin
set @primarykey_text = @primarykey_text + '[id] = ' + convert(nvarchar(100),@pkc1,1)
exec sp_MSreplraiserror @errorid=20598, @param1=N'[dbo].[TableNotUsingSnap]', @param2=@primarykey_text, @param3=13233
End */
end
END
GO
sp_MSdel_dboTableNotUsingSnap :
/* Customised Replication insert proc utilized to support adding to replication without a snapshot. */
create procedure [dbo].[sp_MSdel_dboTableNotUsingSnap]
@pkc1 int
as
begin
declare @primarykey_text nvarchar(100) = ''
delete [dbo].[TableNotUsingSnap]
where [Id] = @pkc1
/* ignore if the record doesn't exist when deleting it
if @@rowcount = 0
if @@microsoftversion>0x07320000
Begin
set @primarykey_text = @primarykey_text + '[Id] = ' + convert(nvarchar(100),@pkc1,1)
exec sp_MSreplraiserror @errorid=20598, @param1=N'[dbo].[TableNotUsingSnap]', @param2=@primarykey_text, @param3=13234
End */
end
GO
배포 단계
3. 배포 에이전트 중지-배포자 (푸시) 또는 구독자 (풀)
/* example script to add a table to a publication without running the snapshot agent
Steps:
Pre steps:
1. Create table on subscribers
2. Create replication procs on subscribers
Deployment/Potential impact:
** 3. Stop Distribution Agents to all subscribers for this publication
4. Add article to publication on publisher
5. DTS data from publisher to subscriber
6. Start Distribution Agents to all subscribers for this publication
7. Monitor/Verify all data has arrived
=========================================================
Note: check your publication settings:
if @independent_agent = N'false'
you will need to stop the distribution agent which will affect ALL
publications going to that subscriber
if @independent_agent = N'true'
you will need to stop the publication specific distribution agent
(to each subscriber)
Plan your live release around that knowledge!
*/
-- IF PUSH REPLICATION: RUN ON DISTRIBUTION SERVER
-- IF PULL REPLICATION: RUN ON SUBSCRIBER SERVER
/* disable the Job first */
exec msdb..sp_update_job @job_name = '[Distribution agent job]', @enabled = 0
GO
/* wait for 10 seconds - precaution ONLY */
WAITFOR DELAY '00:00:10.000'
GO
/* now stop the job */
exec msdb..sp_stop_job @job_name = '[Distribution agent job]'
GO
/*
NOTE: You might recieve an error about stopping a job that is already stopped. You can ignore that error.
It is up to you to verify that the job has been stopped correctly!
*/
4. 이제 출판물에 기사를 추가하십시오-출판사
주요 매개 변수 :
sp_addarticle
- @pre_creation_cmd = N'none'
배포 에이전트가 자체 개체를 삭제 및 생성하지 않도록 지시하는 데 사용
sp_addsubscription
- @sync_type = N'none'
배포자에게 새 스냅 샷을 만들 필요가 없음을 알리는 데 사용되며 IUD 명령을 대기열에 넣을 수 있습니다.
sp_addarticle :
exec sp_addarticle
@publication = N'Publication Name',
@article = N'TableNotUsingSnap',
@source_owner = N'dbo',
@source_object = N'TableNotUsingSnap',
@type = N'logbased',
@description = N'',
@creation_script = N'',
@pre_creation_cmd = N'none', /* this is a critical flag - tells SQL Server to not drop/recreate the repl procs/object on the subscriber */
@schema_option = 0x0000000008004093,
@identityrangemanagementoption = N'none',
@destination_table = N'TableNotUsingSnap',
@destination_owner = N'dbo',
@status = 16,
@vertical_partition = N'false',
@ins_cmd = N'CALL [sp_MSins_dboTableNotUsingSnap]',
@del_cmd = N'CALL [sp_MSdel_dboTableNotUsingSnap]',
@upd_cmd = N'SCALL [sp_MSupd_dboTableNotUsingSnap]'
GO
-- Adding the transactional subscriptions
exec sp_addsubscription @publication = N'Publication Name',
@subscriber = N'Subscriber Server',
@destination_db = N'Subscriber DB',
@subscription_type = N'Push',
@sync_type = N'none', /* tell SQL Server not to sync/snapshot this change to the publication */
@article = N'all',
@update_mode = N'read only',
@subscriber_type = 0
GO
5. 데이터 동기화
이제 데이터를 가입자에게 복사해야합니다.
- 연결된 서버를 만들어서 복사
- 내보내기 / 가져 오기 마법사 사용
- 백업 복원 및 차이점 적용
- SSMS 툴팩 'Generate Insert Statements ...'를 사용하여 테이블을 추출하십시오.
내가 사용하는 정확한 방법은 독자에게 맡기고 배포 에이전트를 얼마나 오래 기꺼이 중단 하느냐에 달려 있습니다.
EXTRA : 테스트의 추가 단계로서, (Table NotUsingSnap)에서 IUD 작업을 생성하기 위해 스크립트를 실행하는 단계 (B)에서이 방법에 대한 신뢰를 얻을 수있는 좋은 곳입니다.
6. 배포 에이전트 다시 시작-배포자 (푸시) 또는 구독자 (풀)
/* example script to add a table to a publication without running the snapshot agent
Steps:
Pre steps:
1. Create table on subscribers
2. Create replication procs on subscribers
Deployment/Potential impact:
3. Stop Distribution Agents to all subscribers for this publication
4. Add article to publication on publisher
5. DTS data from publisher to subscriber
** 6. Start Distribution Agents to all subscribers for this publication
7. Monitor/Verify all data has arrived
=========================================================
Note: check your publication settings:
if @independent_agent = N'false'
you will need to stop the distribution agent which will affect ALL
publications going to that subscriber
if @independent_agent = N'true'
you will need to stop the publication specific distribution agent
(to each subscriber)
Plan your live release around that knowledge!
*/
-- IF PUSH REPLICATION: RUN ON DISTRIBUTION SERVER
-- IF PULL REPLICATION: RUN ON SUBSCRIBER SERVER
/* disable the Job first */
exec msdb..sp_update_job @job_name = 'Distribution agent job', @enabled = 1
GO
/* wait for 10 seconds - precaution ONLY */
WAITFOR DELAY '00:00:10.000'
GO
/* now stop the job */
exec msdb..sp_start_job @job_name = 'Distribution agent job'
GO
/*
Now go and make sure everything is working ok!
*/