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

적용 대상:SQL Server

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

매개 변수가 있는 행 필터가 병합 게시에 사용되는 경우 복제본(replica)tion은 두 부분으로 구성된 스냅샷 사용하여 각 구독을 초기화합니다. 첫째, 복제본(replica)tion에 필요한 모든 개체와 게시된 개체의 스키마를 포함하는 스키마 스냅샷 만들어지지만 데이터는 포함하지 않습니다. 그런 다음 스키마 스냅샷의 개체 및 스키마와 구독의 파티션에 속한 데이터를 포함하는 스냅샷으로 각 구독을 초기화합니다. 둘 이상의 구독이 주어진 파티션(동일한 스키마와 데이터)을 받는다면 해당 파티션에 대한 스냅샷은 단 한 번만 생성됩니다. 동일한 스냅샷에서 여러 개의 구독이 초기화됩니다. 매개 변수가 있는 행 필터에 대한 자세한 내용은 매개 변수가 있는 행 필터를 참조 하세요.

다음 세 가지 방법 중 하나로 매개 변수가 있는 필터를 사용하여 게시에 대한 스냅샷 만들 수 있습니다.

  • 각 파티션에 대한 스냅샷을 미리 생성합니다. 이 옵션을 사용하면 스냅샷 생성되는 시기를 제어할 수 있습니다.
    일정에 따라 스냅샷을 새로 고칠 수 있도록 선택할 수도 있습니다. 스냅샷 만들어진 파티션을 구독하는 새 구독자는 최신 스냅샷 받습니다.

  • 구독자가 스냅샷 생성을 요청할 수 있도록 허용 및 애플리케이션을 처음 동기화할 때 적용됩니다. 이 옵션을 사용하면 새 구독자가 관리자의 개입 없이 동기화할 수 있습니다(SQL Server 에이전트 게시자에서 실행되어 스냅샷 생성될 수 있도록 해야 합니다).

    참고 항목

    게시에서 하나 이상의 아티클을 필터링하면 각 구독에 대해 고유한 겹치지 않는 파티션이 생성되면 병합 에이전트 실행될 때마다 메타데이터가 클린. 즉, 분할된 스냅샷 더 빨리 만료됩니다. 이 옵션을 사용하는 경우 구독자가 스냅샷 생성 및 배달을 시작하도록 허용하는 것이 좋습니다. 필터링 옵션에 대한 자세한 내용은 매개 변수가 있는 행 필터를 참조 하세요.

  • 스냅샷 에이전트 사용하여 각 구독자에 대한 스냅샷 수동으로 생성합니다. 구독자는 올바른 스냅샷 검색하고 적용할 수 있도록 병합 에이전트 스냅샷 위치를 제공해야 합니다.

    참고 항목

    이 옵션은 이전 버전과의 호환성을 위해 지원되며 FTP 스냅샷 공유를 허용하지 않습니다.

가장 유연한 방법은 미리 생성된 옵션과 구독자가 요청한 스냅샷 옵션의 조합을 사용하는 것입니다. 스냅샷 예약된 기준으로 미리 생성되고 새로 고쳐지지만(일반적으로 사용량이 많은 시간 동안) 새 파티션이 필요한 구독이 만들어지면 구독자가 자체 스냅샷 생성할 수 있습니다.

개별 매장에 인벤토리를 제공하는 모바일 인력이 있는 Adventure Works를 고려해 보세요. 각 영업 사원은 로그인할 때만 구독을 접수하며 자신이 담당하는 상점에 대한 데이터를 검색합니다. 관리자는 스냅샷 미리 생성하고 매주 일요일에 새로 고치도록 선택합니다. 경우에 따라 새 사용자가 시스템에 추가되고 사용 가능한 스냅샷 없는 파티션에 대한 데이터가 필요합니다. 또한 관리자는 구독자가 시작한 스냅샷 스냅샷 아직 사용할 수 없으므로 구독자가 게시를 구독할 수 없는 상황을 방지하도록 허용하도록 선택합니다. 새 구독자가 처음으로 연결되면 지정된 파티션에 대해 스냅샷 생성되고 구독자에 적용됩니다(SQL Server 에이전트 스냅샷 생성할 수 있도록 게시자에서 실행 중이어야 합니다).

매개 변수가 있는 필터를 사용하여 게시에 대한 스냅샷 만들려면 매개 변수가 있는 필터를 사용하여 병합 게시에 대한 스냅샷 만들기를 참조하세요.

스냅샷 에이전트 대한 보안 설정

스냅샷 에이전트 각 파티션에 대한 스냅샷 만듭니다. 미리 생성된 스냅샷과 구독자가 요청한 스냅샷에 대해 게시에 대한 스냅샷 에이전트 작업을 새 게시 마법사 또는 sp_addpublication_snapshot을 통해 만들 때 지정한 자격 증명으로 스냅샷 에이전트를 실행 및 연결합니다. 자격 증명을 변경하려면 sp_changedynamicsnapshot_job을 사용합니다. 자세한 내용은 sp_changedynamic스냅샷_job(Transact-SQL)를 참조하세요.

권장 사항

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

  • 게시에서 하나 이상의 아티클을 필터링하면 각 구독에 대해 고유한 겹치지 않는 파티션이 생성되면 병합 에이전트 실행될 때마다 메타데이터가 클린. 즉, 분할된 스냅샷 더 빨리 만료됩니다. 이 옵션을 사용하는 경우 구독자가 스냅샷 생성 및 배달을 시작하도록 허용하는 것이 좋습니다.

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 사용

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

  • 구독자가 스냅샷 생성을 요청할 수 있도록 허용 및 애플리케이션을 처음 동기화할 때 적용됩니다.

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

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

    Important

    가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다. 스크립트 파일에 자격 증명을 저장해야 하는 경우 무단 액세스를 방지하기 위해 파일을 보호해야 합니다.

구독자가 스냅샷 생성 및 배달을 시작할 수 있는 게시를 만들려면

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

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

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

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때 job_login 및 job_password 비롯한 모든 매개 변수에 제공된 값은 일반 텍스트로 배포자로 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간의 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진(SQL Server 구성 관리자)에 대한 암호화된 커넥트온을 사용하도록 설정하세요.

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

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

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

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

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때 job_login 및 job_password 비롯한 모든 매개 변수에 제공된 값은 일반 텍스트로 배포자로 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간의 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진(SQL Server 구성 관리자)에 대한 암호화된 커넥트온을 사용하도록 설정하세요.

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

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

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

  6. 5단계에서 가져온 스냅샷_jobid 값을 uniqueidentifier로 변환합니다.

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

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

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

    참고 항목

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

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

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

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

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

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때 job_login 및 job_password 비롯한 모든 매개 변수에 제공된 값은 일반 텍스트로 배포자로 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간의 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진(SQL Server 구성 관리자)에 대한 암호화된 커넥트온을 사용하도록 설정하세요.

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

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

  5. 스냅샷 작업을 시작하거나 명령 프롬프트에서 복제 스냅샷 에이전트 실행하여 표준 스냅샷 스키마 및 기타 파일을 생성합니다. 자세한 내용은 초기 스냅샷 만들기 및 적용을 참조하세요.

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

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

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

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

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

참고 항목

복제본(replica) 에이전트 프로그래밍에 대한 자세한 내용은 복제 에이전트 실행 파일 개념을 참조하세요.

예제(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'AdventureWorks2022';
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 [AdventureWorks2022];

-- Enable AdventureWorks2022 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 AdventureWorks2022.', 
  @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_adddynamic스냅샷_job 실행하여 만든 필터링된 스냅샷 작업 및 sp_addmergepartition 실행하여 정의된 파티션이 있는 매개 변수가 있는 필터를 사용하여 게시를 만듭니다. @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'AdventureWorks2022';
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 [AdventureWorks2022];

-- Enable AdventureWorks2022 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 AdventureWorks2022.', 
  @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

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

-- 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'AdventureWorks2022';
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 [AdventureWorks2022];

-- Enable AdventureWorks2022 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 AdventureWorks2022.', 
  @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=AdventureWorks2022   
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=AdventureWorks2022   
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 = AdventureWorks2022   
SET SubDB = AdventureWorks2022Replica   
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(복제 관리 개체)를 사용하여 다음과 같은 방법으로 프로그래밍 방식으로 분할된 스냅샷 생성할 수 있습니다.

  • 구독자가 스냅샷 생성을 요청할 수 있도록 허용 및 애플리케이션을 처음 동기화할 때 적용됩니다.

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

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

참고 항목

병합 아티클을 만들 때 F:Microsoft.SqlServer.Replication.PartitionOptions.NonOverlappingSingleSubscription에 P:Microsoft.SqlServer.Replication.MergeArticle.PartitionOption 값을 지정하여 아티클을 필터링함으로써 구독별로 고유한 겹치지 않는 파티션을 생성하면 병합 에이전트를 실행할 때마다 메타데이터가 정리됩니다. 즉, 분할된 스냅샷 더 빨리 만료됩니다. 이 옵션을 사용하는 경우 구독자가 스냅샷 생성을 요청하도록 허용하는 것이 좋습니다. 자세한 내용은 매개 변수가 있는 행 필터 항목 에서 적절한 필터링 옵션을 사용하는 섹션을 참조하세요.

Important

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

구독자가 스냅샷 생성 및 배달을 시작할 수 있는 게시를 만들려면

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

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

  3. 속성이 falseEnabledMergePublishing true설정하고 호출CommitPropertyChanges합니다.

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

    • ServerConnection 에서 1단계에서 만든 ConnectionContext.

    • 게시된 데이터베이스의 이름입니다 DatabaseName.

    • 게시의 이름입니다 Name.

    • 실행할 동적 스냅샷 작업의 최대 수입니다MaxConcurrentDynamicSnapshots. 구독자가 시작한 스냅샷 요청은 언제든지 발생할 수 있으므로 이 속성은 여러 구독자가 분할된 스냅샷 동시에 요청할 때 동시에 실행할 수 있는 스냅샷 에이전트 작업의 수를 제한합니다. 최대 작업 수가 실행 중인 경우 실행 중인 작업 중 하나가 완료될 때까지 분할된 추가 스냅샷 요청이 큐에 대기됩니다.

    • 비트 논리 OR(| Visual C# 및 Visual Basic의 경우) 연산자를 사용하여 값을 AllowSubscriberInitiatedSnapshotAttributes추가합니다.

    • Login 스냅샷 에이전트 작업이 실행되는 Microsoft Windows 계정에 대한 자격 증명을 제공할 필드 및 Password 필드 SnapshotGenerationAgentProcessSecurity 입니다.

      참고 항목

      sysadmin 고정 서버 역할의 멤버가 게시를 만들 때 설정을 SnapshotGenerationAgentProcessSecurity 사용하는 것이 좋습니다. 자세한 내용은 Replication Agent Security Model을 참조하세요.

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

    Important

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

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

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

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

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

  10. 구독자에 대한 병합 에이전트 처음으로 연결되면 분할된 스냅샷 자동으로 생성됩니다.

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

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

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

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

  4. StartSnapshotGenerationAgentJob 1단계에서 만든 개체의 MergePublication 메서드를 호출합니다. 이 메서드는 초기 스냅샷 생성하는 에이전트 작업을 시작합니다. 초기 스냅샷 생성하고 스냅샷 에이전트 대한 사용자 지정 일정을 정의하는 방법에 대한 자세한 내용은 초기 스냅샷 만들기 및 적용을 참조하세요.

  5. 속성이 초기 스냅샷 사용할 준비가 된 시기를 확인하려면 trueSnapshotAvailable 값을 확인합니다.

  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 개체 속성과 12단계의 Server 작업 이름을 전달 JobServer 하여 클래스의 인스턴스를 만듭니다.

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

  17. 각 구독자에 대해 6-16단계를 반복합니다.

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

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

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

  3. 초기 스냅샷을 만듭니다. 자세한 내용은 초기 스냅샷 만들기 및 적용을 참조하세요.

  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 = "AdventureWorks2022";

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 = "AdventureWorks2022"

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 = "AdventureWorks2022";
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 = "AdventureWorks2022"
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 = "AdventureWorks2022";
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 = "AdventureWorks2022"
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
복제 보안을 위한 최선의 구현 방법