다음을 통해 공유


끌어오기 구독 설정

이 항목에서는 SQL Server Management Studio, Transact-SQL 또는 RMO(복제 관리 개체)를 사용하여 SQL Server 2014에서 끌어오기 구독을 만드는 방법을 설명합니다.

P2P 복제에 대한 끌어오기 구독 설정은 스크립트에서 가능하지만 마법사를 통해 사용할 수 없습니다.

SQL Server Management Studio 사용

새 구독 마법사를 사용하여 게시자 또는 구독자에서 끌어오기 구독을 만듭니다. 마법사의 페이지에 따라 다음을 수행합니다.

  • 게시자 및 게시를 지정합니다.

  • 복제 에이전트가 실행될 위치를 선택합니다. 끌어오기 구독의 경우 게시 유형에 따라 배포 에이전트 위치 페이지 또는 병합 에이전트 위치 페이지의 구독자(끌어오기 구독)에서 각 에이전트 실행을 선택합니다.

  • 구독자 및 구독 데이터베이스를 지정합니다.

  • 복제 에이전트에서 만든 연결에 사용되는 로그인 및 암호를 지정합니다.

    • 스냅샷 및 트랜잭션 게시에 대한 구독의 경우 배포 에이전트 보안 페이지에서 자격 증명을 지정합니다.

    • 병합 발행물에 대한 구독의 경우, 병합 에이전트 보안 페이지에서 자격 증명을 지정합니다.

    각 에이전트에 필요한 권한에 대한 자세한 내용은 복제 에이전트 보안 모델을 참조하세요.

  • 동기화 일정과 구독자를 초기화해야 하는 시기를 지정합니다.

  • 병합 게시에 대한 추가 옵션 지정: 구독 유형; 매개 변수가 있는 필터링에 대한 값입니다. 게시가 웹 동기화에 사용하도록 설정된 경우 HTTPS를 통한 동기화 정보입니다.

  • 트랜잭션 게시에서 구독을 업데이트할 수 있는 추가 옵션을 지정합니다. 구독자가 게시자에서 변경 내용을 즉시 커밋할지 아니면 큐에 기록할지 여부와, 구독자에서 게시자로 연결하는 데 사용되는 자격 증명을 설정합니다.

  • 필요에 따라 구독을 스크립션합니다.

게시자에서 끌어오기 구독을 만들려면

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

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

  3. 하나 이상의 구독을 만들려는 게시를 마우스 오른쪽 단추로 클릭한 다음 새 구독을 클릭합니다.

  4. 새 구독 마법사에서 페이지를 완료합니다.

구독자에서 Pull Subscription을 생성하려면

  1. SQL Server Management Studio에서 구독자에 연결한 다음 서버 노드를 확장합니다.

  2. 복제 폴더를 확장합니다.

  3. 로컬 구독 폴더를 마우스 오른쪽 단추로 클릭한 다음 새 구독을 클릭합니다.

  4. 새 구독 마법사의 게시 페이지에서 < 드롭다운 목록에서 < 또는 >Oracle 게시자 찾기를 선택합니다.

  5. 서버에 연결 대화 상자에서 게시자에 연결합니다.

  6. 발행물 페이지에서 발행물을 선택합니다.

  7. 새 구독 마법사에서 페이지를 완료합니다.

Transact-SQL 사용

끌어오기 구독은 복제 저장 프로시저를 사용하여 프로그래밍 방식으로 만들 수 있습니다. 사용되는 저장 프로시저는 구독이 속한 게시 유형에 따라 달라집니다.

스냅샷 또는 트랜잭션 게시에 대한 끌어오기 구독을 만들려면

  1. 게시자에서 sp_helppublication(Transact-SQL)을 실행하여 게시물이 끌어오기 구독을 지원하는지 확인합니다.

    • 결과 집합에서 allow_pull의 값이 1인 경우, 해당 게시물은 끌어오기 구독을 지원합니다.

    • allow_pull 값이 0이면 sp_changepublication(Transact-SQL)를 실행하고 @propertytrue@value allow_pull 지정합니다.

  2. 구독자에서 sp_addpullsubscription(Transact-SQL)를 실행합니다. @publisher 지정하고 @publication. 구독 업데이트에 대한 자세한 내용은 트랜잭션 게시에 업데이트할 수 있는 구독 만들기를 참조하세요.

  3. 구독자에서 sp_addpullsubscription_agent(Transact-SQL)를 실행합니다. 다음을 지정합니다.

    • @publisher, @publisher_db@publication 매개 변수입니다.

    • 구독자에서 배포 에이전트가 @job_login@job_password 하에서 실행되는 Microsoft Windows 자격 증명.

      비고

      Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login 지정한 Windows 자격 증명을 사용하고 @job_password. 배포 에이전트는 항상 Windows 통합 인증을 사용하여 구독자에 대한 로컬 연결을 만듭니다. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 배포자에 연결합니다.

    • (선택 사항) 배포자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 @distributor_login@distributor_password 대한 @distributor_security_mode 및 Microsoft SQL Server 로그인 정보 값 0입니다.

    • 이 구독에 대한 배포 에이전트 작업의 일정입니다. 자세한 내용은 동기화 일정 지정을 참조하세요.

  4. 게시자에서 sp_addsubscription(Transact-SQL) 를 실행하여 끌어오기 구독을 등록합니다. @publication, @subscriber@destination_db 지정합니다. @subscription_type끌어오기 값을 지정합니다.

병합 게시에 대한 끌어오기 구독을 만들려면

  1. 게시자에서, sp_helpmergepublication(Transact-SQL)을 실행하여 게시물이 끌어오기 구독을 지원하는지 확인합니다.

    • 결과 집합의 allow_pull 값이 1이면 게시에서 풀 구독을 지원합니다.

    • allow_pull 값이 0이면 @property 및 @value allow_pull 지정하여 sp_changemergepublication(Transact-SQLtrue)를 실행합니다.

  2. 구독자에서 sp_addmergepullsubscription(Transact-SQL)를 실행합니다. @publisher, @publisher_db, @publication 및 다음 매개 변수를 지정합니다.

    • @subscriber_type - 클라이언트 구독에 대해 로컬을 지정하고 서버 구독에 전역을 지정합니다.

    • @subscription_priority - 구독에 대한 우선 순위를 지정합니다(0.00 ~ 99.99). 서버 구독에만 필요합니다.

      자세한 내용은 고급 병합 복제 충돌 검색 및 해결을 참조하세요.

  3. 구독자 시스템에서 sp_addmergepullsubscription_agent(Transact-SQL)를 실행합니다. 다음 매개 변수를 지정합니다.

    • @publisher, @publisher_db@publication.

    • 구독자에서 병합 에이전트가 실행되는 @job_login@job_password에 대한 Windows 자격 증명입니다.

      비고

      Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login 지정한 Windows 자격 증명을 사용하고 @job_password. 병합 에이전트는 항상 Windows 통합 인증을 사용하여 구독자에 대한 로컬 연결을 만듭니다. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 배포자 및 게시자에 연결합니다.

    • (선택 사항) 배포자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 @distributor_security_mode0이고 @distributor_login@distributor_password 대한 SQL Server 로그인 정보입니다.

    • (선택 사항) 게시자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 @publisher_security_mode@publisher_login@publisher_password 대한 SQL Server 로그인 정보 값이 0입니다.

    • 이 구독에 대한 병합 에이전트 작업의 일정입니다. 자세한 내용은 트랜잭션 게시에 업데이트할 수 있는 구독 만들기를 참조하세요.

  4. 게시자에서 sp_addmergesubscription(Transact-SQL)를 실행합니다. @publication, @subscriber, @subscriber_db@subscription_type에 대해 끌어오기 값을 지정합니다. 끌어오기 구독을 등록합니다.

예시(Transact-SQL)

다음 예에서는 트랜잭션 게시에 수동 구독을 만듭니다. 첫 번째 일괄 처리는 구독자에서 실행되고 두 번째 일괄 처리는 게시자에서 실행됩니다. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임에 제공됩니다.

-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). 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".

-- Execute this batch at the Subscriber.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';

-- At the subscription database, create a pull subscription 
-- to a transactional publication.
USE [AdventureWorks2012Replica]
EXEC sp_addpullsubscription 
  @publisher = @publisher, 
  @publication = @publication, 
  @publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.
EXEC sp_addpullsubscription_agent 
  @publisher = @publisher, 
  @publisher_db = @publicationDB, 
  @publication = @publication, 
  @distributor = @publisher, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). 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".

-- Execute this batch at the Publisher.
DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

-- At the Publisher, register the subscription, using the defaults.
EXEC sp_addsubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @destination_db = @subscriptionDB, 
  @subscription_type = N'pull',
  @status = N'subscribed';
GO

다음 예제에서는 병합 게시에 대한 풀 구독을 생성합니다. 첫 번째 일괄 처리는 구독자에서 실행되고 두 번째 일괄 처리는 게시자에서 실행됩니다. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임에 제공됩니다.


-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). 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".

-- Execute this batch at the Subscriber.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';
SET @hostname = N'adventure-works\david8';

-- At the subscription database, create a pull subscription 
-- to a merge publication.
USE [AdventureWorks2012Replica]
EXEC sp_addmergepullsubscription 
  @publisher = @publisher, 
  @publication = @publication, 
  @publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription. 
EXEC sp_addmergepullsubscription_agent 
  @publisher = @publisher, 
  @publisher_db = @publicationDB, 
  @publication = @publication, 
  @distributor = @publisher, 
  @job_login = $(Login), 
  @job_password = $(Password),
  @hostname = @hostname;
GO
-- Execute this batch at the Publisher.
DECLARE @myMergePub  AS sysname;
DECLARE @mySub       AS sysname;
DECLARE @mySubDB     AS sysname;

SET @myMergePub = N'AdvWorksSalesOrdersMerge';
SET @mySub = N'MYSUBSERVER';
SET @mySubDB = N'AdventureWorks2012Replica';

-- At the Publisher, register the subscription, using the defaults.
USE [AdventureWorks2012]
EXEC sp_addmergesubscription @publication = @myMergePub, 
@subscriber = @mySub, @subscriber_db = @mySubDB, 
@subscription_type = N'pull';
GO

RMO(복제 관리 개체) 사용

끌어오기 구독을 만드는 데 사용되는 RMO 클래스는 구독이 속한 게시 유형에 따라 달라집니다.

스냅샷 또는 트랜잭션 게시에 대한 끌어오기 구독을 만들려면

  1. 클래스를 사용하여 ServerConnection 구독자와 게시자에 대한 연결을 만듭니다.

  2. 1단계의 게시자 연결을 사용하여 클래스의 TransPublication 인스턴스를 만듭니다. 및 를 Name 지정합니다DatabaseNameConnectionContext.

  3. LoadProperties 메서드를 호출합니다. 이 메서드가 반환 false되면 2단계에서 지정한 속성이 올바르지 않거나 게시가 서버에 존재하지 않습니다.

  4. &And에서 Attributes 속성과 AllowPull 간에 비트 단위 논리 AND를 수행합니다. 결과가 None인 경우, Attributes|Or의 비트 논리 OR 연산(Attributes은 Visual C#에서, AllowPull는 Visual Basic에서)의 결과로 설정합니다. 그런 다음 CommitPropertyChanges을 호출하여 끌어오기 구독을 사용하도록 설정합니다.

  5. 구독 데이터베이스가 없는 경우 클래스를 Database 사용하여 만듭니다. 자세한 내용은 데이터베이스 만들기, 변경 및 제거를 참조하세요.

  6. TransPullSubscription 클래스의 인스턴스를 만듭니다.

  7. 다음 구독 속성을 설정합니다.

  8. Create 메서드를 호출합니다.

  9. 2단계에서 얻은 TransPublication 클래스 인스턴스를 사용하여, MakePullSubscriptionWellKnown 메서드를 호출해 게시자에 끌어오기 구독을 등록하십시오. 이 등록이 이미 있는 경우 예외가 발생합니다.

병합 게시에 대한 끌어오기 구독을 만들려면

  1. 클래스를 사용하여 구독자와 게시자에 대한 연결을 만듭니다 ServerConnection .

  2. 1단계의 게시자 연결을 사용하여 클래스의 MergePublication 인스턴스를 만듭니다. Name, DatabaseName, 그리고 ConnectionContext를 지정합니다.

  3. LoadProperties 메서드를 호출합니다. 이 메서드가 반환 false되면 2단계에서 지정한 속성이 올바르지 않거나 게시가 서버에 존재하지 않습니다.

  4. &And에서 Attributes 속성과 AllowPull 간에 비트 단위 논리 AND를 수행합니다. 결과가 None인 경우, Attributes|Or의 비트 논리 OR 연산(Attributes은 Visual C#에서, AllowPull는 Visual Basic에서)의 결과로 설정합니다. 그런 다음 CommitPropertyChanges을 호출하여 끌어오기 구독을 사용하도록 설정합니다.

  5. 구독 데이터베이스가 없는 경우 클래스를 Database 사용하여 만듭니다. 자세한 내용은 데이터베이스 만들기, 변경 및 제거를 참조하세요.

  6. MergePullSubscription 클래스의 인스턴스를 만듭니다.

  7. 다음 구독 속성을 설정합니다.

  8. Create 메서드를 호출합니다.

  9. 2단계에서 MergePublication 클래스의 인스턴스를 사용하여 MakePullSubscriptionWellKnown 메서드를 호출함으로써 게시자에 풀 구독을 등록합니다. 이 등록이 이미 있는 경우 예외가 발생합니다.

예제(RMO)

이 예제는 트랜잭션 게시에 대한 끌어오기 구독을 생성합니다. 배포 에이전트 작업을 만드는 데 사용되는 Microsoft Windows 계정 자격 증명은 런타임에 전달됩니다.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksProductTran";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
TransPublication publication;
TransPullSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new TransPublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.IsExistingObject)
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

        // Define the pull subscription.
        subscription = new TransPullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;

        // Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // By default, subscriptions to transactional publications are synchronized 
        // continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (TransSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                TransSubscriberType.ReadOnly);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksProductTran"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As TransPublication
Dim subscription As TransPullSubscription

Try
    ' Connect to the Publisher and Subscriber.
    subscriberConn.Connect()
    publisherConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New TransPublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.IsExistingObject Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New TransPullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.Description = "Pull subscription to " + publicationDbName _
        + " on " + subscriberName + "."

        ' Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' By default, subscriptions to transactional publications are synchronized 
        ' continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As TransSubscription In publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName And _
                existing.SubscriptionDBName = subscriptionDbName Then
                registered = True
            End If
        Next existing
        If Not registered Then
            ' Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             TransSubscriberType.ReadOnly)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

다음은 병합 게시에 대한 풀 구독을 만드는 예제입니다. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
string hostname = @"adventure-works\garrett1";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;
        subscription.HostName = hostname;

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
Dim hostname As String = "adventure-works\garrett1"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

다음은 병합 게시에 대한 풀 구독을 만드는 예제이며, MSsubscription_properties에 연결된 에이전트 작업 및 구독 메타데이터를 생성하지 않습니다. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;

        // Specify that an agent job not be created for this subscription. The
        // subscription can only be synchronized by running the Merge Agent directly.
        // Subscripition metadata stored in MSsubscription_properties will not
        // be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = false;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName

        ' Specify that an agent job not be created for this subscription. The
        ' subscription can only be synchronized by running the Merge Agent directly.
        ' Subscripition metadata stored in MSsubscription_properties will not
        ' be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = False

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

다음은 웹 동기화를 사용하여 인터넷을 통해 동기화할 수 있는 병합 게시에 대한 끌어오기 구독을 만드는 예제입니다. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다. 자세한 내용은 웹 동기화 구성을 참조하세요.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
string hostname = @"adventure-works\garrett1";
string webSyncUrl = "https://" + publisherInstance + "/WebSync/replisapi.dll";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergePullSubscription subscription;

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions and Web synchronization.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }
        if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;
        subscription.HostName = hostname;

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Enable Web synchronization.
        subscription.UseWebSynchronization = true;
        subscription.InternetUrl = webSyncUrl;

        // Specify the same Windows credentials to use when connecting to the
        // Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
        subscription.InternetLogin = winLogin;
        subscription.InternetPassword = winPassword;

        // Ensure that we create a job for this subscription.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/WebSync/replisapi.dll"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergePullSubscription

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions and Web synchronization.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If
        If (publication.Attributes And PublicationAttributes.AllowWebSynchronization) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowWebSynchronization
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname
        subscription.CreateSyncAgentByDefault = True

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Enable Web synchronization.
        subscription.UseWebSynchronization = True
        subscription.InternetUrl = webSyncUrl

        ' Specify the same Windows credentials to use when connecting to the
        ' Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication
        subscription.InternetLogin = winLogin
        subscription.InternetPassword = winPassword

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

또한 참조하십시오

복제 관리 개체 개념
끌어오기 구독 속성 보기 및 수정
웹 동기화 구성
게시 구독
복제 보안 모범 사례