다음을 통해 공유


매개 변수가 있는 필터로 병합 게시에 대한 스냅샷 만들기

이 항목에서는 SQL Server Management Studio, Transact-SQL 또는 RMO(복제 관리 개체)를 사용하여 2014년 SQL Server 매개 변수가 있는 필터를 사용하여 병합 게시에 대한 스냅샷 만드는 방법을 설명합니다.

시작하기 전에

권장 사항

  • 매개 변수가 있는 필터를 사용하여 병합 게시에 대한 스냅샷을 만들 때는 게시된 데이터 및 구독에 대한 구독자 메타데이터를 모두 포함하는 표준(스키마) 스냅샷을 먼저 생성해야 합니다. 자세한 내용은 Create and Apply the Initial Snapshot을 참조하세요. 스키마 스냅샷을 만든 다음에는 게시된 데이터의 구독자별 파티션을 포함하는 스냅샷을 만들 수 있습니다.

  • 게시에 있는 여러 아티클에 대한 필터링 시 각 구독에 고유하면서도 겹치지 않는 파티션이 생성될 경우 메타데이터는 병합 에이전트가 실행될 때마다 정리됩니다. 따라서 분할된 스냅샷은 더 빨리 만료됩니다. 이 옵션을 사용할 경우 구독자가 스냅샷 생성 및 배달을 시작하도록 허용하는 것을 고려해야 합니다. 필터링 옵션에 대한 자세한 내용은 매개 변수가 있는 필터를 사용하는 병합 게시의 스냅샷에서 "'partition options' 설정" 섹션을 참조하세요.

SQL Server Management Studio 사용

게시 속성 - <게시 대화 상자의 데이터 파티션 페이지에서 파티션에 대한 스냅샷을> 생성합니다. 이 대화 상자에 액세스하는 방법은 게시 속성 보기 및 수정을 참조하세요. 구독자가 스냅샷 생성 및 배달을 시작하고 스냅샷을 생성하도록 허용할 수 있습니다.

하나 이상의 파티션에 대한 스냅샷을 생성하기 전에 다음을 수행해야 합니다.

  1. 새 게시 마법사를 사용하여 병합 게시를 만들고 마법사의 필터 추가 페이지에서 매개 변수가 있는 행 필터를 하나 이상 지정합니다. 자세한 내용은 병합 아티클에 대한 매개 변수가 있는 행 필터 정의 및 수정을 참조하세요.

  2. 게시에 대한 스키마 스냅샷을 생성합니다. 기본적으로 스키마 스냅샷은 새 게시 마법사를 완료할 때 생성됩니다. SQL Server Management Studio에서 스키마 스냅샷을 생성할 수도 있습니다.

스키마 스냅샷을 생성하려면

  1. Management Studio에서 게시자에 연결한 다음 해당 서버 노드를 확장합니다.

  2. 복제 폴더를 확장한 다음 게시 폴더를 확장합니다.

  3. 스냅샷을 생성할 게시를 마우스 오른쪽 단추로 클릭한 다음 스냅샷 에이전트 상태 보기를 클릭합니다.

  4. 보기 스냅샷 에이전트 상태 - <게시> 대화 상자에서 시작을 클릭합니다.

    스냅샷 에이전트에서 스냅샷 생성을 마치면 "[100%] 17개 아티클의 스냅샷이 생성되었습니다"라는 메시지가 표시됩니다.

구독자가 스냅샷 생성 및 배달을 시작하도록 허용하려면

  1. 게시 속성 - <게시> 대화 상자의 데이터 파티션 페이지에서 파티션 자동 정의를 선택하고 새 구독자가 동기화를 시도할 때 필요한 경우 스냅샷 생성합니다.

  2. 확인을 클릭합니다.

스냅샷을 생성하고 새로 고치려면

  1. 게시 속성 - <게시> 대화 상자의 데이터 파티션 페이지에서 추가를 클릭합니다.

  2. 스냅샷을 만들 파티션과 연결된 HOST_NAME() 및/또는 SUSER_SNAME() 값을 입력합니다.

  3. 선택적으로 스냅샷을 새로 고칠 일정을 지정합니다.

    1. 이 파티션에 대한 스냅샷 에이전트의 실행 시간을 다음 시간으로 예약을 선택합니다.

    2. 기본으로 제공되는 스냅샷 새로 고침 일정을 그대로 적용하거나 변경 을 클릭하여 다른 일정을 지정합니다.

  4. 확인을 클릭하면 게시 속성 - <게시> 대화 상자로 돌아갑니다.

  5. 속성 표에서 파티션을 선택한 다음 선택한 스냅샷 지금 생성을 클릭합니다.

  6. 확인을 클릭합니다.

Transact-SQL 사용

저장 프로시저 및 스냅샷 에이전트를 사용하여 다음을 수행할 수 있습니다.

  • 구독자가 처음 동기화될 때 스냅샷 생성 및 적용을 요청하도록 허용합니다.

  • 각 파티션에 대한 스냅샷을 미리 생성합니다.

  • 각 구독자에 대한 스냅샷을 수동으로 생성합니다.

    중요

    가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다. 자격 증명을 스크립트 파일에 저장해야 하는 경우에는 파일에 무단으로 액세스하지 못하도록 보안을 설정해야 합니다.

구독자가 스냅샷 생성 및 배달을 시작하도록 허용하는 게시를 만들려면

  1. 게시 데이터베이스의 게시자에서 sp_addmergepublication(Transact-SQL)를 실행합니다. 다음 매개 변수를 지정합니다.

    • @publication 게시의 이름입니다.

    • 구독자가 스냅샷 프로세스를 시작할 수 있도록 하는 @allow_subscriber_initiated_snapshot 값 true 입니다.

    • (선택 사항) @max_concurrent_dynamic_snapshots 대해 동시에 실행할 수 있는 동적 스냅샷 프로세스의 수입니다. 최대 수의 프로세스가 실행 중인 상태에서 구독자가 스냅샷 생성을 시도하면 이 프로세스는 큐에 배치됩니다. 기본적으로 동시 프로세스의 수에는 제한이 없습니다.

  2. 게시자에서 sp_addpublication_snapshot(Transact-SQL)을 실행합니다. 게시자에 연결할 때 복제 스냅샷 에이전트 인증이 있는 @publication 1단계에서 사용되는 게시 이름 및 Microsoft Windows 자격 증명을 지정합니다. 또한 @publisher_security_mode0 값을 지정하고 @publisher_login 및 @publisher_password 대한 Microsoft SQL Server 로그인 정보를 지정해야 합니다. 이렇게 하면 게시에 대해 스냅샷 에이전트 작업이 만들어집니다. 초기 스냅샷을 생성하고 스냅샷 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 Create and Apply the Initial Snapshot를 참조하십시오.

    중요

    게시자를 원격 배포자로 구성할 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  3. sp_addmergearticle(Transact-SQL)를 실행하여 게시에 아티클을 추가합니다. 이 저장 프로시저는 게시의 각 아티클에 대해 한 번씩만 실행해야 합니다. 매개 변수가 있는 필터를 사용하는 경우 @subset_filterclause 매개 변수를 사용하여 하나 이상의 아티클에 대해 매개 변수가 있는 행 필터를 지정해야 합니다. 자세한 내용은 병합 아티클에 대한 매개 변수가 있는 행 필터 정의 및 수정을 참조하세요.

  4. 매개 변수가 있는 행 필터를 기반으로 다른 아티클을 필터링하는 경우 sp_addmergefilter(Transact-SQL) 을 실행하여 아티클 간의 조인 또는 논리적 레코드 관계를 정의합니다. 이 저장 프로시저는 정의되는 각 관계에 대해 한 번씩만 실행해야 합니다. 자세한 내용은 병합 아티클 사이에서 조인 필터 정의 및 수정을 참조하세요.

  5. 병합 에이전트가 구독자를 초기화하기 위해 스냅샷을 요청하면 구독의 파티션을 요청하기 위한 스냅샷이 자동으로 생성됩니다.

게시를 만들고 스냅샷을 미리 생성하거나 자동으로 새로 고치려면

  1. sp_addmergepublication(Transact-SQL)를 실행하여 게시를 만듭니다. 자세한 내용은 게시 만들기를 참조하세요.

  2. 게시자에서 sp_addpublication_snapshot(Transact-SQL)을 실행합니다. @publication 1단계에서 사용되는 게시 이름과 @job_login @password 대해 스냅샷 에이전트 실행되는 Windows 자격 증명을 지정합니다. 에이전트가 게시자에 연결할 때 SQL Server 인증을 사용하는 경우 @publisher_security_mode 값 0@publisher_login및 @publisher_password 대한 SQL Server 로그인 정보도 지정해야 합니다. 이렇게 하면 게시에 대해 스냅샷 에이전트 작업이 만들어집니다. 초기 스냅샷을 생성하고 스냅샷 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 Create and Apply the Initial Snapshot를 참조하십시오.

    중요

    게시자를 원격 배포자로 구성할 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  3. sp_addmergearticle(Transact-SQL)를 실행하여 게시에 아티클을 추가합니다. 이 저장 프로시저는 게시의 각 아티클에 대해 한 번씩만 실행해야 합니다. 매개 변수가 있는 필터를 사용하는 경우 @subset_filterclause 매개 변수를 사용하여 한 아티클에 대해 매개 변수가 있는 행 필터를 지정해야 합니다. 자세한 내용은 병합 아티클에 대한 매개 변수가 있는 행 필터 정의 및 수정을 참조하세요.

  4. 매개 변수가 있는 행 필터를 기반으로 다른 아티클을 필터링하는 경우 sp_addmergefilter(Transact-SQL) 을 실행하여 아티클 간의 조인 또는 논리적 레코드 관계를 정의합니다. 이 저장 프로시저는 정의되는 각 관계에 대해 한 번씩만 실행해야 합니다. 자세한 내용은 병합 아티클 사이에서 조인 필터 정의 및 수정을 참조하세요.

  5. 게시 데이터베이스의 게시자에서 1단계의 @publication 값을 지정하여 sp_helpmergepublication(Transact-SQL)를 실행합니다. 결과 집합에서 snapshot_jobid 값을 확인합니다.

  6. 5단계에서 얻은 snapshot_jobid 의 값을 uniqueidentifier로 변환합니다.

  7. msdb 데이터베이스의 게시자에서 sp_start_job(Transact-SQL)를 실행하여 @job_id 대해 6단계에서 가져온 변환된 값을 지정합니다.

  8. 게시 데이터베이스의 게시자에서 sp_addmergepartition(Transact-SQL)를 실행합니다. @publication 1단계의 게시 이름을 지정하고 필터 절에서 SUSER_SNAME(Transact-SQL)를 사용하는 경우 @suser_sname 파티션을 정의하는 데 사용되는 값 또는 필터 절에서 HOST_NAME(Transact-SQL)를 사용하는 경우 @host_name 값을 지정합니다.

  9. 게시 데이터베이스의 게시자에서 sp_adddynamicsnapshot_job(Transact-SQL)를 실행합니다. @publication 1단계의 게시 이름, 8단계의 @suser_sname 또는 @host_name 값 및 작업 일정을 지정합니다. 이렇게 하면 지정된 파티션에 대해 매개 변수가 있는 스냅샷을 생성하는 작업이 만들어집니다. 자세한 내용은 Specify Synchronization Schedules을 참조하세요.

    참고

    이 작업은 2단계에서 정의한 초기 스냅샷 작업과 동일한 Windows 계정을 사용하여 실행됩니다. 매개 변수가 있는 스냅샷 작업 및 관련 데이터 파티션을 제거하려면 sp_dropdynamicsnapshot_job(Transact-SQL)을 실행합니다.

  10. 게시 데이터베이스의 게시자에서 1단계의 @publication 값과 8단계의 @suser_sname 또는 @host_name 값을 지정하여 sp_helpmergepartition(Transact-SQL)을 실행합니다. 결과 집합에서 dynamic_snapshot_jobid 값을 확인합니다.

  11. msdb 데이터베이스의 배포자에서 sp_start_job(Transact-SQL)을 실행하여 @job_id 9단계에서 가져온 값을 지정합니다. 이렇게 하면 파티션에 대한 매개 변수가 있는 스냅샷 작업이 시작됩니다.

  12. 8-11단계를 반복하여 각 구독에 대해 분할된 스냅샷을 생성합니다.

게시를 만들고 각 파티션에 대한 스냅샷을 수동으로 만들려면

  1. sp_addmergepublication(Transact-SQL)를 실행하여 게시를 만듭니다. 자세한 내용은 게시 만들기를 참조하세요.

  2. 게시자에서 sp_addpublication_snapshot(Transact-SQL)을 실행합니다. 1단계에서 @publication 사용되는 게시 이름과 @job_login 및 @password대해 스냅샷 에이전트 실행되는 Windows 자격 증명을 지정합니다. 에이전트가 게시자에 연결할 때 SQL Server 인증을 사용하는 경우 @publisher_security_mode 0 값과 @publisher_login및 @publisher_password 대한 SQL Server 로그인 정보도 지정해야 합니다. 이렇게 하면 게시에 대해 스냅샷 에이전트 작업이 만들어집니다. 초기 스냅샷을 생성하고 스냅샷 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 Create and Apply the Initial Snapshot를 참조하십시오.

    중요

    게시자를 원격 배포자로 구성할 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  3. sp_addmergearticle(Transact-SQL)을 실행하여 아티클을 게시에 추가합니다. 이 저장 프로시저는 게시의 각 아티클에 대해 한 번씩만 실행해야 합니다. 매개 변수가 있는 필터를 사용하는 경우 @subset_filterclause 매개 변수를 사용하여 하나 이상의 아티클에 대해 매개 변수가 있는 행 필터를 지정해야 합니다. 자세한 내용은 병합 아티클에 대한 매개 변수가 있는 행 필터 정의 및 수정을 참조하세요.

  4. 매개 변수가 있는 행 필터를 기반으로 다른 아티클을 필터링하는 경우 sp_addmergefilter(Transact-SQL) 을 실행하여 아티클 간의 조인 또는 논리적 레코드 관계를 정의합니다. 이 저장 프로시저는 정의되는 각 관계에 대해 한 번씩만 실행해야 합니다. 자세한 내용은 병합 아티클 사이에서 조인 필터 정의 및 수정을 참조하세요.

  5. 스냅샷 작업을 시작하거나 명령 프롬프트에서 복제 스냅샷 에이전트를 실행하여 표준 스냅샷 스키마 및 그 밖의 파일을 생성합니다. 자세한 내용은 Create and Apply the Initial Snapshot을 참조하세요.

  6. 명령 프롬프트에서 -DynamicSnapshotLocation 에 분할된 스냅샷의 위치를 지정하고 파티션을 정의하는 다음 속성을 하나 또는 모두 지정하고 복제 스냅샷 에이전트를 다시 실행하여 대량 복사(.bcp) 파일을 생성합니다.

  7. 6단계를 반복하여 각 구독에 대해 분할된 스냅샷을 생성합니다.

  8. 다음 속성을 지정하고 각 구독에 대해 병합 에이전트를 실행하여 구독자에서 초기 분할된 스냅샷을 적용합니다.

    • -Hostname - HOST_NAME의 실제 값이 재정의되는 경우 파티션을 정의하는 데 사용되는 값

    • -DynamicSnapshotLocation - 이 파티션에 대한 동적 스냅샷의 위치

참고

복제 에이전트를 프로그래밍하는 방법에 대한 자세한 내용은 복제 에이전트 실행 파일 개념을 참조하세요.

예제(Transact-SQL)

이 예에서는 매개 변수가 있는 필터를 사용하여 구독자가 스냅샷 생성 프로세스를 시작하는 병합 게시를 만듭니다. @job_login@job_password 대한 값은 스크립팅 변수를 사용하여 전달됩니다.

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication with Subscriber requested snapshot
-- and using the default agent schedule. 
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'true',
  @publication_compatibility_level = N'90RTM';

-- Create a new snapshot job for the publication, using the default schedule.
-- Pass credentials at runtime using sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(login), 
  @job_password = $(password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains salesperson information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO

-- Start the agent job to generate the full snapshot for the publication.
-- The filtered data snapshot is generated automatically the first time 
-- the subscription is synchronized. 
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot 
  @publication = @publication;
GO

이 예에서는 매개 변수가 있는 필터를 사용하여 각 구독자가 sp_addmergepartition 을 실행하여 파티션을 정의하고 sp_adddynamicsnapshot_job 을 실행하여 필터링된 스냅샷 작업을 만들고 분할 정보를 전달하는 게시를 만듭니다. @job_login@job_password 대한 값은 스크립팅 변수를 사용하여 전달됩니다.

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication.  
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the 
-- default schedule. Pass credentials at runtime using 
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(Login), 
  @job_password = $(password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains customer information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO

-- Start the snapshot agent job.
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot 
  @publication = @publication;
GO

PRINT '*** Waiting for the initial snapshot.';
GO

-- Create a temporary table to store the filtered data snapshot 
-- job information.
CREATE TABLE #temp (id int,
    job_name sysname,
    job_id uniqueidentifier,
    dynamic_filter_login sysname NULL,
    dynamic_filter_hostname sysname NULL,
    dynamic_snapshot_location nvarchar(255),
    frequency_type int, 
    frequency_interval int, 
    frequency_subday_type int,
    frequency_subday_interval int, 
    frequency_relative_interval int, 
    frequency_recurrence_factor int, 
    active_start_date int, 
    active_end_date int, 
    active_start_time int, 
    active_end_time int
)

-- Create each snapshot for a partition 
-- The initial snapshot must already be generated.
DECLARE @publication AS sysname;
DECLARE @jobname AS sysname
DECLARE @hostname AS sysname
SET @publication = N'AdvWorksSalesPersonMerge';
SET @hostname = N'adventure-works\Fernando';

WHILE NOT EXISTS(SELECT * FROM sysmergepublications 
    WHERE [name] = @publication 
    AND snapshot_ready = 1)
BEGIN
    WAITFOR DELAY '00:00:05'
END

-- Create a data partition by overriding HOST_NAME().
EXEC sp_addmergepartition 
  @publication = @publication,
  @host_name = @hostname;

-- Create the filtered data snapshot job, and use the returned 
-- information to start the job.
EXEC sp_adddynamicsnapshot_job 
  @publication = @publication,
  @host_name = @hostname;

INSERT INTO #temp (id, job_name, job_id, dynamic_filter_login,
    dynamic_filter_hostname, dynamic_snapshot_location,
    frequency_type,	frequency_interval, frequency_subday_type,
    frequency_subday_interval, frequency_relative_interval, 
    frequency_recurrence_factor, active_start_date,	active_end_date, 
    active_start_time,active_end_time)
EXEC sp_helpdynamicsnapshot_job;

SELECT @jobname = (SELECT DISTINCT job_name FROM #temp WHERE dynamic_filter_hostname = @hostname);

EXEC msdb..sp_start_job @job_name = @jobname;
DROP TABLE #temp;
GO

이 예에서는 매개 변수가 있는 필터를 사용하여 각 구독자가 분할 정보를 제공함으로써 데이터 파티션과 필터링된 스냅샷 작업을 만들어야 하는 게시를 만듭니다. 구독자는 복제 에이전트를 수동으로 실행할 때 구독자가 명령줄 매개 변수를 사용하여 분할 정보를 제공합니다. 이 예에서는 이 게시에 대한 구독도 만들어졌다고 가정합니다.

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication.  
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the 
-- default schedule. Pass credentials at runtime using 
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(Login), 
  @job_password = $(Password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains customer information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO
REM Line breaks are added to improve readability.   
REM In a batch file, commands must be made in a single line.  
REM Run the Snapshot agent from the command line to generate the standard snapshot   
REM schema and other files.   
SET DistPub=%computername%  
SET PubDB=AdventureWorks2012   
SET PubName=AdvWorksSalesPersonMerge  
  
"C:\Program Files\Microsoft SQL Server\120\COM\SNAPSHOT.EXE" -Publication %PubName%    
-Publisher %DistPub% -Distributor  %DistPub%  -PublisherDB %PubDB%  -ReplicationType 2    
-OutputVerboseLevel 1  -DistributorSecurityMode 1  
  
PAUSE  
REM Run the Snapshot agent from the command line, this time to generate   
REM the bulk copy (.bcp) data for each Subscriber partition.    
SET DistPub=%computername%  
SET PubDB=AdventureWorks2012   
SET PubName=AdvWorksSalesPersonMerge  
SET SnapshotDir=\\%DistPub%\repldata\unc\fernando  
  
MD %SnapshotDir%  
  
"C:\Program Files\Microsoft SQL Server\120\COM\SNAPSHOT.EXE" -Publication %PubName%    
-Publisher %DistPub%  -Distributor  %DistPub%  -PublisherDB %PubDB%  -ReplicationType 2    
-OutputVerboseLevel 1  -DistributorSecurityMode 1  -DynamicFilterHostName "adventure-works\Fernando"    
-DynamicSnapshotLocation %SnapshotDir%  
  
PAUSE  
REM Run the Merge Agent for each subscription to apply the partitioned   
REM snapshot for each Subscriber.    
SET Publisher = %computername%  
SET Subscriber = %computername%  
SET PubDB = AdventureWorks2012   
SET SubDB = AdventureWorks2012Replica   
SET PubName = AdvWorksSalesPersonMerge   
SET SnapshotDir=\\%DistPub%\repldata\unc\fernando  
  
"C:\Program Files\Microsoft SQL Server\120\COM\REPLMERG.EXE" -Publisher  %Publisher%    
-Subscriber  %Subscriber%  -Distributor %Publisher%  -PublisherDB %PubDB%    
-SubscriberDB %SubDB% -Publication %PubName%  -PublisherSecurityMode 1  -OutputVerboseLevel 3    
-Output -SubscriberSecurityMode 1  -SubscriptionType 3 -DistributorSecurityMode 1    
-Hostname "adventure-works\Fernando"  -DynamicSnapshotLocation %SnapshotDir%  
  
PAUSE

RMO(복제 관리 개체) 사용

다음과 같이 RMO(복제 관리 개체)를 사용하여 프로그래밍 방식으로 분할된 스냅샷을 만들 수 있습니다.

  • 구독자가 처음 동기화될 때 스냅샷 생성 및 적용을 요청하도록 허용합니다.

  • 각 파티션에 대한 스냅샷을 미리 생성합니다.

  • 스냅샷 에이전트를 실행하여 각 구독자에 대한 스냅샷을 수동으로 생성합니다.

참고

병합 아티클을 만들 때 NonOverlappingSingleSubscriptionPartitionOption 값을 지정하여 아티클을 필터링함으로써 구독별로 고유한 겹치지 않는 파티션을 생성하면 병합 에이전트를 실행할 때마다 메타데이터가 정리됩니다. 따라서 분할된 스냅샷은 더 빨리 만료됩니다. 이 옵션을 사용할 경우 구독자가 스냅샷 생성을 요청하도록 허용하는 것을 고려해야 합니다. 자세한 내용은 Parameterized Row Filters항목의 "적절한 필터링 옵션 사용" 섹션을 참조하세요.

중요

가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다. 자격 증명을 저장해야 하는 경우 Windows .NET Framework에서 제공하는 암호화 서비스 Microsoft 를 사용합니다.

구독자가 스냅샷 생성 및 배달을 시작하도록 허용하는 게시를 만들려면

  1. ServerConnection 클래스를 사용하여 게시자 연결을 만듭니다.

  2. 게시 데이터베이스에 대해 ReplicationDatabase 클래스의 인스턴스를 만들고, 1단계에서 만든 ConnectionContext 인스턴스에 ServerConnection 속성을 설정한 다음 LoadProperties 메서드를 호출합니다. LoadProperties에서 false를 반환하면 데이터베이스가 있는지 확인합니다.

  3. EnabledMergePublishing 속성이 false이면 true로 설정한 후 CommitPropertyChanges를 호출합니다.

  4. MergePublication 클래스의 인스턴스를 만들고 이 개체에 대해 다음 속성을 설정합니다.

  5. Create 메서드를 호출하여 게시를 만듭니다.

    중요

    원격 배포자로 게시자를 구성할 경우 SnapshotGenerationAgentProcessSecurity를 포함하여 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  6. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정합니다. 필요한 경우 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 아티클을 정의을 참조하세요.

  7. SnapshotAgentExists 값이 false이면 CreateSnapshotAgent를 호출하여 이 게시에 대한 초기 스냅샷 에이전트 작업을 만듭니다.

  8. 4단계에서 만든 StartSnapshotGenerationAgentJob 개체의 MergePublication 메서드를 호출합니다. 그러면 초기 스냅샷을 생성하는 에이전트 작업이 시작됩니다. 초기 스냅샷을 생성하고 스냅샷 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 Create and Apply the Initial Snapshot를 참조하십시오.

  9. (옵션) SnapshotAvailable 속성이 true 값인지 확인하여 초기 스냅샷을 사용할 준비가 되었는지 확인합니다.

  10. 구독자가 병합 에이전트에 처음으로 연결하는 경우에는 분할된 스냅샷이 자동으로 생성됩니다.

게시를 만들고 스냅샷을 미리 생성하거나 자동으로 새로 고치려면

  1. MergePublication 클래스의 인스턴스를 사용하여 병합 게시를 정의합니다. 자세한 내용은 게시 만들기를 참조하세요.

  2. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정하고 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 아티클을 정의을 참조하세요.

  3. SnapshotAgentExists의 값이 false이면 CreateSnapshotAgent를 호출하여 이 게시에 대한 스냅샷 에이전트 작업을 만듭니다.

  4. 4단계에서 만든 StartSnapshotGenerationAgentJob 개체의 MergePublication 메서드를 호출합니다. 그러면 초기 스냅샷을 생성하는 에이전트 작업이 시작됩니다. 초기 스냅샷을 생성하고 스냅샷 에이전트에 대한 사용자 지정 일정을 정의하는 방법은 Create and Apply the Initial Snapshot를 참조하십시오.

  5. SnapshotAvailable 속성이 true 값인지 확인하여 초기 스냅샷을 사용할 준비가 되었는지 확인합니다.

  6. MergePartition 클래스의 인스턴스를 만들고 다음 두 속성 중 하나 또는 모두를 사용하여 구독자에 대한 매개 변수가 있는 필터링 조건을 설정합니다.

  7. MergeDynamicSnapshotJob 클래스의 인스턴스를 만들고 6단계와 동일한 속성을 설정합니다.

  8. ReplicationAgentSchedule 클래스를 사용하여 구독자 파티션에 대한 필터링된 스냅샷을 생성할 일정을 정의합니다.

  9. 1단계에서 만든 MergePublication 의 인스턴스를 사용하여 AddMergePartition을 호출합니다. 6단계에서 만든 MergePartition 개체를 전달합니다.

  10. 1단계에서 만든 MergePublication 의 인스턴스를 사용하여 AddMergeDynamicSnapshotJob 메서드를 호출합니다. 7단계에서 만든 MergeDynamicSnapshotJob 개체 및 8단계에서 만든 ReplicationAgentSchedule 개체를 전달합니다.

  11. EnumMergeDynamicSnapshotJobs를 호출하고 반환된 배열의 새로 추가된 분할된 스냅샷 작업에서 MergeDynamicSnapshotJob 개체를 찾습니다.

  12. 작업의 Name 속성을 가져옵니다.

  13. ServerConnection 클래스를 사용하여 배포자 연결을 만듭니다.

  14. 13단계에서 만든 Server 개체를 전달하여 SMO(SQL Server 관리 개체) ServerConnection 클래스의 인스턴스를 만듭니다.

  15. 14단계에서 만든 Job 개체의 JobServer 속성 및 12단계에서 가져온 작업 이름을 전달하여 Server 클래스의 인스턴스를 만듭니다.

  16. Start 메서드를 호출하여 분할된 스냅샷 작업을 시작합니다.

  17. 구독자별로 6단계에서 16단계까지 반복합니다.

게시를 만들고 각 파티션에 대한 스냅샷을 수동으로 만들려면

  1. MergePublication 클래스의 인스턴스를 사용하여 병합 게시를 정의합니다. 자세한 내용은 게시 만들기를 참조하세요.

  2. MergeArticle 속성을 사용하여 게시에 아티클을 추가합니다. 매개 변수가 있는 필터를 정의하는 하나 이상의 아티클에 대해 FilterClause 속성을 지정하고 아티클 간 조인 필터를 정의하는 MergeJoinFilter 개체를 만듭니다. 자세한 내용은 아티클을 정의을 참조하세요.

  3. 초기 스냅샷을 만듭니다. 자세한 내용은 Create and Apply the Initial Snapshot을 참조하세요.

  4. SnapshotGenerationAgent 클래스의 인스턴스를 만들고 다음 필수 속성을 설정합니다.

  5. MergeReplicationType값을 설정합니다.

  6. 다음 속성 중 하나 이상을 설정하여 분할 매개 변수를 정의합니다.

  7. GenerateSnapshot 메서드를 호출합니다.

  8. 구독자별로 4단계에서 7단계까지 반복합니다.

예(RMO)

이 예제에서는 구독자에게 스냅샷 생성 요청을 허용하는 병합 게시를 만듭니다.

// Set the Publisher, publication database, and publication names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2012";

ReplicationDatabase publicationDb;
MergePublication publication;

// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);

try
{
    // Connect to the Publisher.
    conn.Connect();

    // Enable the database for merge publication.				
    publicationDb = new ReplicationDatabase(publicationDbName, conn);
    if (publicationDb.LoadProperties())
    {
        if (!publicationDb.EnabledMergePublishing)
        {
            publicationDb.EnabledMergePublishing = true;
        }
    }
    else
    {
        // Do something here if the database does not exist. 
        throw new ApplicationException(String.Format(
            "The {0} database does not exist on {1}.",
            publicationDb, publisherName));
    }

    // Set the required properties for the merge publication.
    publication = new MergePublication();
    publication.ConnectionContext = conn;
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;

    // Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True;

    // Specify the Windows account under which the Snapshot Agent job runs.
    // This account will be used for the local connection to the 
    // Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

    // Explicitly set the security mode for the Publisher connection
    // Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

    // Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;
    publication.Attributes |= PublicationAttributes.DynamicFilters;

    // Enable pull and push subscriptions.
    publication.Attributes |= PublicationAttributes.AllowPull;
    publication.Attributes |= PublicationAttributes.AllowPush;

    if (!publication.IsExistingObject)
    {
        // Create the merge publication.
        publication.Create();
        
        // Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent();
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The {0} publication already exists.", publicationName));
    }
}

catch (Exception ex)
{
    // Implement custom application error handling here.
    throw new ApplicationException(String.Format(
        "The publication {0} could not be created.", publicationName), ex);
}
finally
{
    conn.Disconnect();
}
' Set the Publisher, publication database, and publication names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2012"

Dim publicationDb As ReplicationDatabase
Dim publication As MergePublication

' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

Try
    ' Connect to the Publisher.
    conn.Connect()

    ' Enable the database for merge publication.				
    publicationDb = New ReplicationDatabase(publicationDbName, conn)
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledMergePublishing Then
            publicationDb.EnabledMergePublishing = True
        End If
    Else
        ' Do something here if the database does not exist. 
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist on {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the merge publication.
    publication = New MergePublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    ' Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowSubscriberInitiatedSnapshot
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.DynamicFilters

    ' Enable pull and push subscriptions
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPull
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPush

    If Not publication.IsExistingObject Then
        ' Create the merge publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try

이 예제에서는 매개 변수가 있는 행 필터를 사용하여 병합 게시에 대한 구독자 파티션 및 필터링된 스냅샷을 수동으로 만듭니다.

// Define the server, database, and publication names
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2012";
string distributorName = publisherInstance;

MergePublication publication;
MergePartition partition;
MergeDynamicSnapshotJob snapshotAgentJob;
ReplicationAgentSchedule schedule;

// Create a connection to the Publisher.
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create a connection to the Distributor to start the Snapshot Agent.
ServerConnection distributorConn = new ServerConnection(distributorName);

try
{
    // Connect to the Publisher.
    publisherConn.Connect();

    // Set the required properties for the publication.
    publication = new MergePublication();
    publication.ConnectionContext = publisherConn;
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;


    // If we can't get the properties for this merge publication, 
    // then throw an application exception.
    if (publication.LoadProperties() || publication.SnapshotAvailable)
    {
        // Set a weekly schedule for the filtered data snapshot.
        schedule = new ReplicationAgentSchedule();
        schedule.FrequencyType = ScheduleFrequencyType.Weekly;
        schedule.FrequencyRecurrenceFactor = 1;
        schedule.FrequencyInterval = Convert.ToInt32(0x001);

        // Set the value of Hostname that defines the data partition. 
        partition = new MergePartition();
        partition.DynamicFilterHostName = hostname;
        snapshotAgentJob = new MergeDynamicSnapshotJob();
        snapshotAgentJob.DynamicFilterHostName = hostname;

        // Create the partition for the publication with the defined schedule.
        publication.AddMergePartition(partition);
        publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule);
    }
    else
    {
        throw new ApplicationException(String.Format(
            "Settings could not be retrieved for the publication, " +
            " or the initial snapshot has not been generated. " +
            "Ensure that the publication {0} exists on {1} and " +
            "that the Snapshot Agent has run successfully.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Do error handling here.
    throw new ApplicationException(string.Format(
        "The partition for '{0}' in the {1} publication could not be created.",
        hostname, publicationName), ex);
}
finally
{
    publisherConn.Disconnect();
    if (distributorConn.IsOpen) distributorConn.Disconnect();
}
' Define the server, database, and publication names
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2012"
Dim distributorName As String = publisherInstance

Dim publication As MergePublication
Dim partition As MergePartition
Dim snapshotAgentJob As MergeDynamicSnapshotJob
Dim schedule As ReplicationAgentSchedule

' Create a connection to the Publisher.
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create a connection to the Distributor to start the Snapshot Agent.
Dim distributorConn As ServerConnection = New ServerConnection(distributorName)

Try
    ' Connect to the Publisher.
    publisherConn.Connect()

    ' Set the required properties for the publication.
    publication = New MergePublication()
    publication.ConnectionContext = publisherConn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName


    ' If we can't get the properties for this merge publication, 
    ' then throw an application exception.
    If (publication.LoadProperties() Or publication.SnapshotAvailable) Then
        ' Set a weekly schedule for the filtered data snapshot.
        schedule = New ReplicationAgentSchedule()
        schedule.FrequencyType = ScheduleFrequencyType.Weekly
        schedule.FrequencyRecurrenceFactor = 1
        schedule.FrequencyInterval = Convert.ToInt32("0x001", 16)

        ' Set the value of Hostname that defines the data partition. 
        partition = New MergePartition()
        partition.DynamicFilterHostName = hostname
        snapshotAgentJob = New MergeDynamicSnapshotJob()
        snapshotAgentJob.DynamicFilterHostName = hostname

        ' Create the partition for the publication with the defined schedule.
        publication.AddMergePartition(partition)
        publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule)
    Else
        Throw New ApplicationException(String.Format( _
         "Settings could not be retrieved for the publication, " + _
         " or the initial snapshot has not been generated. " + _
         "Ensure that the publication {0} exists on {1} and " + _
         "that the Snapshot Agent has run successfully.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Do error handling here.
    Throw New ApplicationException(String.Format( _
     "The partition for '{0}' in the {1} publication could not be created.", _
     hostname, publicationName), ex)
Finally
    publisherConn.Disconnect()
    If distributorConn.IsOpen Then
        distributorConn.Disconnect()
    End If
End Try

이 예제에서는 매개 변수가 있는 행 필터를 사용하여 병합 게시에 구독자에 대한 필터링된 데이터 스냅샷을 만들기 위해 수동으로 스냅샷 에이전트를 시작합니다.

// Set the Publisher, publication database, and publication names.
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2012";
string publisherName = publisherInstance;
string distributorName = publisherInstance;

SnapshotGenerationAgent agent;

try
{
    // Set the required properties for Snapshot Agent.
    agent = new SnapshotGenerationAgent();
    agent.Distributor = distributorName;
    agent.DistributorSecurityMode = SecurityMode.Integrated;
    agent.Publisher = publisherName;
    agent.PublisherSecurityMode = SecurityMode.Integrated;
    agent.Publication = publicationName;
    agent.PublisherDatabase = publicationDbName;
    agent.ReplicationType = ReplicationType.Merge;

    // Specify the partition information to generate a 
    // filtered snapshot based on Hostname.
    agent.DynamicFilterHostName = hostname;

    // Start the agent synchronously.
    agent.GenerateSnapshot();
}
catch (Exception ex)
{
    // Implement custom application error handling here.
    throw new ApplicationException(String.Format(
        "A snapshot could not be generated for the {0} publication."
        , publicationName), ex);
}
' Set the Publisher, publication database, and publication names.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2012"
Dim publisherName As String = publisherInstance
Dim distributorName As String = publisherInstance

Dim agent As SnapshotGenerationAgent

Try
    ' Set the required properties for Snapshot Agent.
    agent = New SnapshotGenerationAgent()
    agent.Distributor = distributorName
    agent.DistributorSecurityMode = SecurityMode.Integrated
    agent.Publisher = publisherName
    agent.PublisherSecurityMode = SecurityMode.Integrated
    agent.Publication = publicationName
    agent.PublisherDatabase = publicationDbName
    agent.ReplicationType = ReplicationType.Merge

    ' Specify the partition information to generate a 
    ' filtered snapshot based on Hostname.
    agent.DynamicFilterHostName = hostname

    ' Start the agent synchronously.
    agent.GenerateSnapshot()
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
     "A snapshot could not be generated for the {0} publication." _
     , publicationName), ex)
End Try

참고 항목

매개 변수가 있는 행 필터
Replication System Stored Procedures Concepts
매개 변수가 있는 필터를 사용하는 병합 게시의 스냅샷
복제 보안을 위한 최선의 구현 방법