끌어오기 구독 만들기Create a Pull Subscription

이 항목에서는 SQL Server 2017SQL Server 2017 , SQL Server Management StudioSQL Server Management Studio또는 RMO(복제 관리 개체)를 사용하여 Transact-SQLTransact-SQL에서 끌어오기 구독을 만드는 방법에 대해 설명합니다.This topic describes how create a pull subscription in SQL Server 2017SQL Server 2017 by using SQL Server Management StudioSQL Server Management Studio, Transact-SQLTransact-SQL, or Replication Management Objects (RMO).

P2P 복제에 대한 끌어오기 구독 설정은 스크립트를 통해서는 가능하지만 마법사를 통해서는 사용할 수 없습니다.Setting up a pull subscription for P2P replication is possible by script, but is not available through the wizard.

SQL Server Management Studio 사용 Using SQL Server Management Studio

새 구독 마법사를 사용하여 게시자나 구독자에서 끌어오기 구독을 만듭니다.Create a pull subscription at the Publisher or the Subscriber using the New Subscription Wizard. 마법사의 페이지에 따라 다음을 수행하세요.Follow the pages in the wizard to:

  • 게시자와 게시를 지정합니다.Specify the Publisher and publication.

  • 복제 에이전트가 실행될 위치를 선택합니다.Select where replication agents will run. 끌어오기 구독의 경우 게시 유형에 따라 배포 에이전트 위치 페이지나 병합 에이전트 위치 페이지에서 각 에이전트를 해당 구독자(끌어오기 구독)에서 실행 을 선택합니다.For a pull subscription, select Run each agent at its Subscriber (pull subscriptions) on the Distribution Agent Location page or Merge Agent Location page, depending on the type of publication.

  • 구독자와 구독 데이터베이스를 지정합니다.Specify Subscribers and subscription databases.

  • 복제 에이전트에서 설정한 연결에 사용할 로그인과 암호를 지정합니다.Specify the logins and passwords used for connections made by replication agents:

    • 스냅숏 및 트랜잭션 게시에 대한 구독의 경우 배포 에이전트 보안 페이지에서 자격 증명을 지정합니다.For subscriptions to snapshot and transactional publications, specify credentials on the Distribution Agent Security page.

    • 병합 게시에 대한 구독의 경우 병합 에이전트 보안 페이지에서 자격 증명을 지정합니다.For subscriptions to merge publications, specify credentials on the Merge Agent Security page.

      각 에이전트에 필요한 사용 권한에 대한 자세한 내용은 Replication Agent Security Model를 참조하세요.For information about the permissions required by each agent, see Replication Agent Security Model.

  • 동기화 일정과 구독자의 초기화 시기를 지정합니다.Specify a synchronization schedule and when the Subscriber should be initialized.

  • 구독 유형, 매개 변수가 있는 필터링에 대한 값, 게시에 웹 동기화를 사용할 수 있는 경우 HTTPS를 통한 동기화 정보 등 병합 게시에 대한 추가 옵션을 지정합니다.Specify additional options for merge publications: subscription type; values for parameterized filtering; and information for synchronization through HTTPS if the publication is enabled for Web synchronization.

  • 구독자가 게시자의 변경 내용을 즉시 커밋할지 아니면 큐에 쓸지 여부, 구독자에서 게시자로 연결하는 데 사용할 자격 증명 등, 트랜잭션 게시에 대해 구독 업데이트를 허용하는 추가 옵션을 지정합니다.Specify additional options for transactional publications that allow updating subscriptions: whether Subscribers should commit changes at the Publisher immediately or write them to a queue; credentials used to connect from the Subscriber to the Publisher.

  • 경우에 따라 구독을 스크립팅합니다.Optionally script the subscription.

게시자에서 끌어오기 구독을 만들려면To create a pull subscription from the Publisher

  1. MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio에서 게시자에 연결한 다음 해당 서버 노드를 확장합니다.Connect to the Publisher in MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio, and then expand the server node.

  2. 복제 폴더를 확장한 다음 로컬 게시 폴더를 확장합니다.Expand the Replication folder, and then expand the Local Publications folder.

  3. 하나 이상의 구독을 만들 게시를 마우스 오른쪽 단추로 클릭한 다음 새 구독을 클릭합니다.Right-click the publication for which you want to create one or more subscriptions, and then click New Subscriptions.

  4. 새 구독 마법사의 페이지를 완료합니다.Complete the pages in the New Subscription Wizard.

구독자에서 끌어오기 구독을 만들려면To create a pull subscription from the Subscriber

  1. SQL Server Management StudioSQL Server Management Studio에서 구독자에 연결한 다음 해당 서버 노드를 확장합니다.Connect to the Subscriber in SQL Server Management StudioSQL Server Management Studio, and then expand the server node.

  2. 복제 폴더를 확장합니다.Expand the Replication folder.

  3. 로컬 구독 폴더를 마우스 오른쪽 단추로 클릭한 다음 새 구독을 클릭합니다.Right-click the Local Subscriptions folder, and then click New Subscriptions.

  4. 새 구독 마법사의 게시 페이지에 있는 게시자 드롭다운 목록에서 <SQL Server 게시자 찾기> 또는 <Oracle 게시자 찾기>를 선택합니다.On the Publication page of the New Subscription Wizard, select <Find SQL Server Publisher> or <Find Oracle Publisher> from the Publisher drop-down list.

  5. 서버에 연결 대화 상자에서 게시자에 연결합니다.Connect to the Publisher in the Connect to Server dialog box.

  6. 게시 페이지에서 게시를 선택합니다.Select a publication on the Publication page.

  7. 새 구독 마법사의 페이지를 완료합니다.Complete the pages in the New Subscription Wizard.

Transact-SQL 사용 Using Transact-SQL

끌어오기 구독은 복제 저장 프로시저를 사용하여 프로그래밍 방식으로 만들 수 있습니다.Pull subscriptions can be created programmatically using replication stored procedures. 사용되는 저장 프로시저는 구독이 속한 게시 유형에 따라 달라집니다.The stored procedures used will depend on the type of publication to which the subscription belongs.

스냅숏 또는 트랜잭션 게시에 끌어오기 구독을 만들려면To create a pull subscription to a snapshot or transactional publication

  1. 게시자에서 sp_helppublication(Transact-SQL)을 실행하여 게시에서 끌어오기 구독을 지원하는지 확인합니다.At the Publisher, verify that the publication supports pull subscriptions by executing sp_helppublication (Transact-SQL).

    • 결과 집합의 allow_pull 값이 1이면 게시에서 끌어오기 구독을 지원합니다.If the value of allow_pull in the result set is 1, then the publication supports pull subscriptions.

    • allow_pull의 값이 0이면 @propertyallow_pull을, @valuetrue를 지정하여 sp_changepublication(Transact-SQL)을 실행합니다.If the value of allow_pull is 0, execute sp_changepublication (Transact-SQL), specifying allow_pull for @property and true for @value.

  2. 구독자에서 sp_addpullsubscription(Transact-SQL)을 실행합니다.At the Subscriber, execute sp_addpullsubscription (Transact-SQL). @publisher@publication을 지정합니다.Specify @publisher and @publication. 구독 업데이트에 대한 자세한 내용은 Create an Updatable Subscription to a Transactional Publication을 참조하세요.For information about updating subscriptions, see Create an Updatable Subscription to a Transactional Publication.

  3. 구독자에서 sp_addpullsubscription_agent (Transact-SQL)를 실행합니다.At the Subscriber, execute sp_addpullsubscription_agent (Transact-SQL). 다음을 지정합니다.Specify the following:

    • 구독자에서 배포 에이전트가 실행되는 @publisher또는 RMO(복제 관리 개체)를 사용하여 @publisher_db@publication 매개 변수The @publisher, @publisher_db, and @publication parameters.

    • 구독자에서 배포 에이전트가 실행되는 MicrosoftMicrosoft @job_login @job_login 을 지정하고 @job_password를 참조하세요.The MicrosoftMicrosoft Windows credentials under which the Distribution Agent at the Subscriber runs for @job_login and @job_password.

      참고

      Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login 을 지정하고 @job_password를 참조하세요.Connections made using Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. 배포 에이전트는 항상 Windows 통합 인증을 사용하여 구독자에 대한 로컬 연결을 만듭니다.The Distribution Agent always makes the local connection to the Subscriber using Windows Integrated Authentication. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 배포자에 연결합니다.By default, the agent will connect to the Distributor using Windows Integrated Authentication.

    • (선택 사항) @distributor_security_mode에 대한 0 값과, @distributor_login@distributor_password에 대한 SQL Server 로그인 정보(배포자에 연결할 때 SQL Server 인증을 사용해야 하는 경우).(Optional) A value of 0 for @distributor_security_mode and the SQL Server login information for @distributor_login and @distributor_password, if you need to use SQL Server Authentication when connecting to the Distributor.

    • 이 구독에 대한 배포 에이전트 작업 일정.A schedule for the Distribution Agent job for this subscription. 자세한 내용은 Specify Synchronization Schedules을 참조하세요.For more information, see Specify Synchronization Schedules.

  4. 게시자에서 sp_addsubscription(Transact-SQL)을 실행하여 끌어오기 구독을 등록합니다.At the Publisher, execute sp_addsubscription (Transact-SQL) to register the pull subscription. @publication, @subscriber@destination_db를 지정합니다.Specify @publication, @subscriber, and @destination_db. @subscription_typepull 값을 지정합니다.Specify a value of pull for @subscription_type.

병합 게시에 끌어오기 구독을 만들려면To create a pull subscription to a merge publication

  1. 게시자에서 sp_helpmergepublication(Transact-SQL)을 실행하여 게시에서 끌어오기 구독을 지원하는지 확인합니다.At the Publisher, verify that the publication supports pull subscriptions by executing sp_helpmergepublication (Transact-SQL).

    • 결과 집합의 allow_pull 값이 1이면 게시에서 끌어오기 구독을 지원합니다.If the value of allow_pull in the result set is 1, then the publication supports pull subscriptions.

    • allow_pull의 값이 0이면 @propertyallow_pull을, @valuetrue를 지정하여 sp_changemergepublication(Transact-SQL)을 실행합니다.If the value of allow_pull is 0, execute sp_changemergepublication (Transact-SQL), specifying allow_pull for @property and true for @value.

  2. 구독자에서 sp_addmergepullsubscription(Transact-SQL)을 실행합니다.At the Subscriber, execute sp_addmergepullsubscription (Transact-SQL). @publisher, @publisher_db, @publication과 다음 매개 변수를 지정합니다.Specify @publisher, @publisher_db, @publication, and the following parameters:

    • @subscriber_type - 클라이언트 구독에 local 을 지정하고 서버 구독에 global 을 지정합니다.@subscriber_type – specify local for a client subscription and global for a server subscription.

    • @subscription_priority - 구독의 우선 순위를 지정합니다(0.00 ~ 99.99).@subscription_priority – Specify a priority for the subscription (0.00 to 99.99). 이 지정은 서버 구독에만 필요합니다.This is only required for a server subscription.

      자세한 내용은 Advanced Merge Replication Conflict Detection and Resolution을 참조하세요.For more information, see Advanced Merge Replication Conflict Detection and Resolution.

  3. 구독자에서 sp_addmergepullsubscription_agent(Transact-SQL)를 실행합니다.At the Subscriber, execute sp_addmergepullsubscription_agent (Transact-SQL). 다음 매개 변수를 지정합니다.Specify the following parameters:

    • @publisher또는 RMO(복제 관리 개체)를 사용하여 @publisher_db@publication를 참조하세요.@publisher, @publisher_db, and @publication.

    • @job_login@job_password에 대해 구독자에서 배포 에이전트가 실행되는 Windows 자격 증명을 지정합니다.The Windows credentials under which the Merge Agent at the Subscriber runs for @job_login and @job_password.

      참고

      Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login@job_password에서 SQL Server 이외 구독자에 대한 구독을 만드는 방법에 대해 설명합니다.Connections made using Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. 병합 에이전트는 항상 Windows 통합 인증을 사용하여 구독자에 대한 로컬 연결을 만듭니다.The Merge Agent always makes the local connection to the Subscriber using Windows Integrated Authentication. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 배포자 및 게시자에 연결합니다.By default, the agent will connect to the Distributor and Publisher using Windows Integrated Authentication.

    • (옵션) 배포자에 연결할 때 0@distributor_security_mode 0 SQL ServerSQL Server @distributor_login @distributor_login 을 지정하고 @distributor_passwordSQL ServerSQL Server 로그인 정보 지정(Optional) A value of 0 for @distributor_security_mode and the SQL ServerSQL Server login information for @distributor_login and @distributor_password, if you need to use SQL ServerSQL Server Authentication when connecting to the Distributor.

    • (옵션) 배포자에 연결할 때 0@publisher_security_mode 0 SQL ServerSQL Server @distributor_login @publisher_login 을 지정하고 @publisher_passwordSQL ServerSQL Server 로그인 정보 지정(Optional) A value of 0 for @publisher_security_mode and the SQL ServerSQL Server login information for @publisher_login and @publisher_password, if you need to use SQL ServerSQL Server Authentication when connecting to the Publisher.

    • 이 구독에 대한 병합 에이전트 작업 일정.A schedule for the Merge Agent job for this subscription. 자세한 내용은 Create an Updatable Subscription to a Transactional Publication을 참조하세요.For more information, see Create an Updatable Subscription to a Transactional Publication.

  4. 게시자에서 sp_addmergesubscription(Transact-SQL)을 실행합니다.At the Publisher, execute sp_addmergesubscription (Transact-SQL). 이때 @publication, @subscriber, @subscriber_db, @subscription_type에 값 pull을 지정합니다.Specify @publication, @subscriber, @subscriber_db, and a value of pull for @subscription_type. 끌어오기 구독이 등록됩니다.This registers the pull subscription.

예(Transact-SQL) Examples (Transact-SQL)

다음은 트랜잭션 게시에 끌어오기 구독을 만드는 예입니다.The following example creates a pull subscription to a transactional publication. 구독자에서 첫 번째 일괄 처리가 실행되고 두 번째 일괄 처리는 게시자에서 실행됩니다.The first batch is executed at the Subscriber, and the second batch is executed at the Publisher. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임에 제공됩니다.Login and password values are supplied at runtime using sqlcmd scripting variables.

-- 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'AdventureWorks';  

-- At the subscription database, create a pull subscription   
-- to a transactional publication.  
USE [AdventureWorksReplica]  
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'AdventureWorksReplica';  

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

다음은 병합 게시에 끌어오기 구독을 만드는 예입니다.The following example creates a pull subscription to a merge publication. 구독자에서 첫 번째 일괄 처리가 실행되고 두 번째 일괄 처리는 게시자에서 실행됩니다.The first batch is executed at the Subscriber, and the second batch is executed at the Publisher. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임에 제공됩니다.Login and password values are supplied at runtime using sqlcmd scripting variables.

-- 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'AdventureWorks';  
SET @hostname = N'adventure-works\david8';  

-- At the subscription database, create a pull subscription   
-- to a merge publication.  
USE [AdventureWorksReplica]  
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'AdventureWorksReplica';  

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

RMO(복제 관리 개체) 사용 Using Replication Management Objects (RMO)

끌어오기 구독을 만드는 데 사용되는 RMO 클래스는 구독이 속한 게시 유형에 따라 달라집니다.The RMO classes used to create a pull subscription depend on the type of publication to which the subscription belongs.

스냅숏 또는 트랜잭션 게시에 끌어오기 구독을 만들려면To create a pull subscription to a snapshot or transactional publication

  1. ServerConnection 클래스를 사용하여 구독자 및 게시자 둘 다의 연결을 만듭니다.Create connections to both the Subscriber and Publisher by using the ServerConnection Class.

  2. 1단계에서 만든 게시자 연결을 사용하여 TransPublication 클래스의 인스턴스를 만듭니다.Create an instance of the TransPublication class by using the Publisher connection from step 1. Name, DatabaseNameConnectionContext를 지정합니다.Specify Name, DatabaseName and ConnectionContext.

  3. LoadProperties 메서드를 호출합니다.Call the LoadProperties method. 이 메서드가 false를 반환하는 경우 2단계에서 지정한 속성이 올바르지 않거나 서버에 게시가 없는 것입니다.If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Attributes 속성과 AllowPull 간에 비트 논리 AND(Visual C#에서는&, Visual Basic에서는 And)를 수행합니다.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. 결과가 None이면 AttributesAttributesAllowPull 간의 비트 논리 OR(Visual C#에서는 |, Visual Basic에서는 Or) 결과로 설정합니다.If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. 그런 다음 CommitPropertyChanges를 호출하여 끌어오기 구독을 설정합니다.Then, call CommitPropertyChanges to enable pull subscriptions.

  5. 구독 데이터베이스가 없는 경우 Database 클래스를 사용하여 만듭니다.If the subscription database does not exist, create it by using the Database class. 자세한 내용은 데이터베이스 생성, 변경 및 제거를 참조하세요.For more information, see Creating, Altering, and Removing Databases.

  6. TransPullSubscription 클래스의 인스턴스를 만듭니다.Create an instance of the TransPullSubscription class.

  7. 다음 구독 속성을 설정합니다.Set the following subscription properties:

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

  9. 2단계의 TransPublication 클래스 인스턴스를 사용해서 MakePullSubscriptionWellKnown 메서드를 호출하여 끌어오기 구독을 게시자에 등록합니다.Using the instance of the TransPublication class from step 2, call the MakePullSubscriptionWellKnown method to register the pull subscription with the Publisher. 이 등록이 이미 존재하는 경우 예외가 발생합니다.If this registration already exists, an exception occurs.

병합 게시에 끌어오기 구독을 만들려면To create a pull subscription to a merge publication

  1. ServerConnection 클래스를 사용하여 구독자 및 게시자 둘 다의 연결을 만듭니다.Create connections to both the Subscriber and Publisher by using the ServerConnection class.

  2. 1단계에서 만든 게시자 연결을 사용하여 MergePublication 클래스의 인스턴스를 만듭니다.Create an instance of the MergePublication class by using the Publisher connection from step 1. Name, DatabaseNameConnectionContext를 지정합니다.Specify Name, DatabaseName, and ConnectionContext.

  3. LoadProperties 메서드를 호출합니다.Call the LoadProperties method. 이 메서드가 false를 반환하는 경우 2단계에서 지정한 속성이 올바르지 않거나 서버에 게시가 없는 것입니다.If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Attributes 속성과 AllowPull 간에 비트 논리 AND(Visual C#에서는&, Visual Basic에서는 And)를 수행합니다.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. 결과가 None이면 AttributesAttributesAllowPull 간의 비트 논리 OR(Visual C#에서는 |, Visual Basic에서는 Or) 결과로 설정합니다.If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. 그런 다음 CommitPropertyChanges를 호출하여 끌어오기 구독을 설정합니다.Then, call CommitPropertyChanges to enable pull subscriptions.

  5. 구독 데이터베이스가 없는 경우 Database 클래스를 사용하여 만듭니다.If the subscription database does not exist, create it by using the Database class. 자세한 내용은 데이터베이스 생성, 변경 및 제거를 참조하세요.For more information, see Creating, Altering, and Removing Databases.

  6. MergePullSubscription 클래스의 인스턴스를 만듭니다.Create an instance of the MergePullSubscription class.

  7. 다음 구독 속성을 설정합니다.Set the following subscription properties:

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

  9. 2단계의 MergePublication 클래스 인스턴스를 사용해서 MakePullSubscriptionWellKnown 메서드를 호출하여 끌어오기 구독을 게시자에 등록합니다.Using the instance of the MergePublication class from step 2, call the MakePullSubscriptionWellKnown method to register the pull subscription with the Publisher. 이 등록이 이미 존재하는 경우 예외가 발생합니다.If this registration already exists, an exception occurs.

예(RMO) Example (RMO)

다음은 트랜잭션 게시에 끌어오기 구독을 만드는 예입니다.This example creates a pull subscription to a transactional publication. 배포 에이전트 작업을 만드는 데 사용되는 MicrosoftMicrosoft Windows 계정 자격 증명은 런타임에 전달됩니다.The MicrosoftMicrosoft Windows account credentials used to create the Distribution Agent job are passed at runtime.

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

//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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  

'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  

다음은 병합 게시에 끌어오기 구독을 만드는 예입니다.This example creates a pull subscription to a merge publication. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.The Windows account credentials used to create the Merge Agent job are passed at runtime.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksSalesOrdersMerge";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
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에서 관련된 에이전트 작업 및 구독 메타데이터를 만들지 않고 병합 게시에 끌어오기 구독을 만드는 예입니다.This example creates a pull subscription to a merge publication without creating an associated agent job and subscription metadata in MSsubscription_properties. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.The Windows account credentials used to create the Merge Agent job are passed at runtime.

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

//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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  

'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  

다음은 웹 동기화를 사용하여 인터넷을 통해 동기화할 수 있는 병합 게시에 끌어오기 구독을 만드는 예입니다.This example creates a pull subscription to a merge publication that can be synchronized over the Internet using Web synchronization. 병합 에이전트 작업을 만드는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.The Windows account credentials used to create the Merge Agent job are passed at runtime. 자세한 내용은 Configure Web Synchronization을 참조하세요.For more information, see Configure Web Synchronization.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksSalesOrdersMerge";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
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  

관련 항목:See Also

복제 관리 개체 개념 Replication Management Objects Concepts
끌어오기 구독 속성 보기 및 수정 View and Modify Pull Subscription Properties
Configure Web Synchronization Configure Web Synchronization
게시 구독 Subscribe to Publications
Replication Security Best Practices Replication Security Best Practices