밀어넣기 구독 만들기Create a Push Subscription

이 항목에서는 SQL Server 2017SQL Server 2017 , SQL Server Management StudioSQL Server Management Studio또는 RMO(복제 관리 개체)를 사용하여 Transact-SQLTransact-SQL에서 밀어넣기 구독을 만드는 방법에 대해 설명합니다.This topic describes how to create a push subscription in SQL Server 2017SQL Server 2017 by using SQL Server Management StudioSQL Server Management Studio, Transact-SQLTransact-SQL, or Replication Management Objects (RMO). SQL ServerSQL Server 이외 구독자에 대해 밀어넣기 구독을 만드는 방법에 대한 자세한 내용은 SQL Server 이외 구독자에 대한 구독 만들기를 참조하세요.For information about creating a push subscription for a non- SQL ServerSQL Server Subscriber, see Create a Subscription for a Non-SQL Server Subscriber.

SQL Server Management Studio 사용 Using SQL Server Management Studio

새 구독 마법사를 사용하여 게시자 또는 구독자에서 밀어넣기 구독을 만듭니다.Create a push 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 push subscription, select Run all agents at the Distributor (push 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.

  • 게시 유형 및 매개 변수가 있는 필터링 값 등의 병합 게시에 대한 추가 옵션을 지정합니다.Specify additional options for merge publications: subscription type; and values for parameterized filtering.

  • 구독자가 게시자의 변경 내용을 즉시 커밋할지 아니면 큐에 쓸지 여부, 구독자에서 게시자로 연결하는 데 사용할 자격 증명 등, 트랜잭션 게시에 대해 구독 업데이트를 허용하는 추가 옵션을 지정합니다.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 push 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 push 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

밀어넣기 구독은 복제 저장 프로시저를 사용하여 프로그래밍 방식으로 만들 수 있습니다.Push 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.

중요!IMPORTANT! 가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다.When possible, prompt users to enter security credentials at run time. 자격 증명을 스크립트 파일에 저장해야 하는 경우에는 파일에 무단으로 액세스하지 못하도록 보안을 설정해야 합니다.If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

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

  1. 게시 데이터베이스의 게시자에서 sp_helppublication을 실행하여 게시에서 밀어넣기 구독을 지원하는지 확인합니다.At the Publisher on the publication database, verify that the publication supports push subscriptions by executing sp_helppublication.

    • allow_push 의 값이 1이면 게시에서 밀어넣기 구독을 지원합니다.If the value of allow_push is 1, push subscriptions are supported.

    • allow_push의 값이 0이면 sp_changepublication을 실행하고 @propertyallow_push, @valuetrue를 지정합니다.If the value of allow_push is 0, execute sp_changepublication, specifying allow_push for @property and true for @value.

  2. 게시 데이터베이스의 게시자에서 sp_addsubscription을 실행합니다.At the Publisher on the publication database, execute sp_addsubscription. @publication, @subscriber@destination_db을 지정합니다.Specify @publication, @subscriber and @destination_db. @subscription_typepush 값을 지정합니다.Specify a value of push for @subscription_type. 구독 업데이트 방법은 Create an Updatable Subscription to a Transactional Publication를 참조하세요.For information about how to update subscriptions, see Create an Updatable Subscription to a Transactional Publication.

  3. 게시 데이터베이스의 게시자에서 sp_addpushsubscription_agent를 실행합니다.At the Publisher on the publication database, execute sp_addpushsubscription_agent. 다음을 지정합니다.Specify the following:

    • 배포자의 배포 에이전트가 @subscriber또는 RMO(복제 관리 개체)를 사용하여 @subscriber_db@publication 매개 변수The @subscriber, @subscriber_db, and @publication parameters.

    • 배포자의 배포 에이전트가 MicrosoftMicrosoft @job_login @job_login 를 지정하고 @job_password를 참조하세요.The MicrosoftMicrosoft Windows credentials under which the Distribution Agent at the Distributor runs for @job_login and @job_password.

      참고: Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login@job_password로 지정된 Windows 자격 증명을 사용합니다.NOTE: 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 Distributor using Windows Integrated Authentication. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 구독자에 연결합니다.By default, the agent will connect to the Subscriber using Windows Integrated Authentication.

    • (옵션) 0@subscriber_security_mode 값 및 MicrosoftMicrosoft SQL ServerSQL Server@subscriber_login 를 지정하고 @subscriber_password를 참조하세요.(Optional) A value of 0 for @subscriber_security_mode and the MicrosoftMicrosoft SQL ServerSQL Server login information for @subscriber_login and @subscriber_password. 구독자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 이러한 매개 변수를 지정합니다.Specify these parameters if you need to use SQL Server Authentication when connecting to the Subscriber.

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

    중요!!IMPORTANT!! 게시자에서 원격 배포자를 사용하여 밀어넣기 구독을 만드는 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 보내집니다.When creating a push subscription at a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and job_password, are sent to the Distributor as plain text. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다.You should encrypt the connection between the Publisher and its remote Distributor before executing this stored procedure. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.For more information, see Enable Encrypted Connections to the Database Engine (SQL Server Configuration Manager).

병합 게시에 밀어넣기 구독을 만들려면To create a push subscription to a merge publication

  1. _게시 데이터베이스의 게시자에서 sp_helpmergepublication을 실행하여 게시에서 밀어넣기 구독을 지원하는지 확인합니다.At the Publisher on the publication database, verify that the publication supports push subscriptions by executing sp_helpmergepublication.

    • allow_push 값이 1이면 게시에서 밀어넣기 구독을 지원합니다.If the value of allow_push is 1, the publication supports push subscriptions.

    • allow_push의 값이 1이 아니면 sp_changemergepublication을 실행하고 @propertyallow_push, @valuetrue를 지정합니다.If the value of allow_push is not 1, execute sp_changemergepublication, specifying allow_push for @property and true for @value.

  2. 게시 데이터베이스의 게시자에서 sp_addmergesubscription을 실행하고 다음 매개 변수를 지정합니다.At the Publisher on the publication database, execute sp_addmergesubscription, specifying the following parameters:

    • @publication를 참조하세요.@publication. 게시의 이름입니다.This is the name of the publication.

    • @subscriber_type를 참조하세요.@subscriber_type. 클라이언트 구독에 local 을 지정하고 서버 구독에 global을 지정합니다.For a client subscription, specify local and for a server subscription, specify global.

    • @subscription_priority를 참조하세요.@subscription_priority. 서버 구독에 대해 구독의 우선 순위를 지정합니다(0.00 ~ 99.99).For a server subscription, specify a priority for the subscription (0.00 to 99.99).

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

  3. 게시 데이터베이스의 게시자에서 sp_addmergepushsubscription_agent를 실행합니다.At the Publisher on the publication database, execute sp_addmergepushsubscription_agent. 다음을 지정합니다.Specify the following:

    • 배포자의 배포 에이전트가 @subscriber또는 RMO(복제 관리 개체)를 사용하여 @subscriber_db@publication 매개 변수The @subscriber, @subscriber_db, and @publication parameters.

    • @job_login@job_password에 대해 배포자의 병합 에이전트를 실행하는 데 사용되는 Windows 자격 증명The Windows credentials under which the Merge Agent at the Distributor runs for @job_login and @job_password.

      참고: Windows 통합 인증을 사용하여 만든 연결은 항상 @job_login@job_password로 지정된 Windows 자격 증명을 사용합니다.NOTE: 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 Distributor using Windows Integrated Authentication. 기본적으로 에이전트는 Windows 통합 인증을 사용하여 구독자에 연결합니다.By default, the agent will connect to the Subscriber using Windows Integrated Authentication.

    • (옵션) 0@subscriber_security_mode 값 및 SQL ServerSQL Server@subscriber_login 를 지정하고 @subscriber_password를 참조하세요.(Optional) A value of 0 for @subscriber_security_mode and the SQL ServerSQL Server login information for @subscriber_login and @subscriber_password. 구독자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 이러한 매개 변수를 지정합니다.Specify these parameters if you need to use SQL Server Authentication when connecting to the Subscriber.

    • (옵션) 0@publisher_security_mode 값 및 SQL ServerSQL Server@publisher_login 를 지정하고 @publisher_password를 참조하세요.(Optional) A value of 0 for @publisher_security_mode and the SQL ServerSQL Server login information for @publisher_login and @publisher_password. 구독자에 연결할 때 SQL Server 인증을 사용해야 하는 경우 이러한 값을 지정합니다.Specify these values if you need to use SQL Server Authentication when connecting to the Publisher.

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

    중요!!IMPORTANT!! 게시자에서 원격 배포자를 사용하여 밀어넣기 구독을 만드는 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 보내집니다.When creating a push subscription at a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and job_password, are sent to the Distributor as plain text. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다.You should encrypt the connection between the Publisher and its remote Distributor before executing this stored procedure. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.For more information, see Enable Encrypted Connections to the Database Engine (SQL Server Configuration Manager).

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

다음은 트랜잭션 게시에 밀어넣기 구독을 만드는 예입니다.The following example creates a push subscription to a transactional publication. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임 시 제공됩니다.Login and password values are supplied at run time by 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".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

--Add a push subscription to a transactional publication.
USE [AdventureWorks2012]
EXEC sp_addsubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @destination_db = @subscriptionDB, 
  @subscription_type = N'push';

--Add an agent job to synchronize the push subscription.
EXEC sp_addpushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @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".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

--Add a push subscription to a transactional publication.
USE [AdventureWorks2012]
EXEC sp_addsubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @destination_db = @subscriptionDB, 
  @subscription_type = N'push';

--Add an agent job to synchronize the push subscription.
EXEC sp_addpushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO

다음은 병합 게시에 밀어넣기 구독을 만드는 예입니다.The following example creates a push subscription to a merge publication. 로그인 및 암호 값은 sqlcmd 스크립팅 변수를 사용하여 런타임 시 제공됩니다.Login and password values are supplied at run time by 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".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorksReplica'; 
SET @hostname = N'adventure-works\david8'

-- Add a push subscription to a merge publication.
USE [AdventureWorks2012];
EXEC sp_addmergesubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @subscription_type = N'push',
  @hostname = @hostname;

--Add an agent job to synchronize the push subscription.
EXEC sp_addmergepushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @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".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorksReplica'; 
SET @hostname = N'adventure-works\david8'

-- Add a push subscription to a merge publication.
USE [AdventureWorks2012];
EXEC sp_addmergesubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @subscription_type = N'push',
  @hostname = @hostname;

--Add an agent job to synchronize the push subscription.
EXEC sp_addmergepushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO

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

RMO(복제 관리 개체)를 사용하여 프로그래밍 방식으로 밀어넣기 구독을 만들 수 있습니다.You can create push subscriptions programmatically by using Replication Management Objects (RMO). _밀어넣기 구독을 만들 때 사용하는 RMO 클래스는 구독을 만드는 게시 유형에 따라 달라집니다.The RMO classes you use to create a push subscription depend on the type of publication to which the subscription is created.

중요!IMPORTANT! 가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다.When possible, prompt users to enter security credentials at runtime. 자격 증명을 저장해야 하는 경우 Windows .NET Framework에서 제공하는 암호화 서비스 MicrosoftMicrosoft 를 사용합니다.If you must store credentials, use the cryptographic services provided by the MicrosoftMicrosoft Windows .NET Framework.

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

  1. ServerConnection 클래스를 사용하여 게시자 연결을 만듭니다.Create a connection to the 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 exists on the server.

  4. Attributes 속성과 AllowPush 사이에서 비트 논리 AND(Visual C#의 & 및 Visual Basic의 And)를 수행합니다.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. 결과가 None이면 Attributes| 속성과 Or 및 Visual Basic의 Attributes 를 지정하고 AllowPush를 참조하세요.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 AllowPush. 그런 다음 CommitPropertyChanges 를 호출하여 밀어넣기 구독을 설정합니다.Then, call CommitPropertyChanges to enable push 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. TransSubscription 클래스의 인스턴스를 만듭니다.Create an instance of the TransSubscription class.

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

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

    중요!!원격 배포자가 있는 게시자에서 밀어넣기 구독을 만드는 경우 SynchronizationAgentProcessSecurity를 비롯한 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다.IMPORTANT!!When creating a push subscription at a Publisher with a remote Distributor, the values supplied for all properties, including SynchronizationAgentProcessSecurity, are sent to the Distributor as plain text. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다.You should encrypt the connection between the Publisher and its remote Distributor before calling the Create method. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.For more information, see Enable Encrypted Connections to the Database Engine (SQL Server Configuration Manager).

병합 게시에 밀어넣기 구독을 만들려면To create a push subscription to a merge publication

  1. ServerConnection 클래스를 사용하여 게시자 연결을 만듭니다.Create a connection to the 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 exists on the server.

  4. Attributes 속성과 AllowPush 사이에서 비트 논리 AND(Visual C#의 & 및 Visual Basic의 And)를 수행합니다.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. 결과가 None이면 Attributes| 속성과 Or 및 Visual Basic의 Attributes 를 지정하고 AllowPush를 참조하세요.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 AllowPush. 그런 다음 CommitPropertyChanges 를 호출하여 밀어넣기 구독을 설정합니다.Then, call CommitPropertyChanges to enable push 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. MergeSubscription 클래스의 인스턴스를 만듭니다.Create an instance of the MergeSubscription class.

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

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

    중요!IMPORTANT! 원격 배포자가 있는 게시자에서 밀어넣기 구독을 만드는 경우 SynchronizationAgentProcessSecurity를 비롯한 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다.When creating a push subscription at a Publisher with a remote Distributor, the values supplied for all properties, including SynchronizationAgentProcessSecurity, are sent to the Distributor as plain text. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다.You should encrypt the connection between the Publisher and its remote Distributor before calling the Create method. 자세한 내용은 데이터베이스 엔진에 암호화 연결 사용(SQL Server 구성 관리자)을 참조하세요.For more information, see Enable Encrypted Connections to the Database Engine (SQL Server Configuration Manager).

예(RMO) Examples (RMO)

다음은 트랜잭션 게시에 _새 밀어넣기 구독을 만드는 예입니다.This example creates a new push subscription to a transactional publication. 배포 에이전트 작업을 실행하는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.The Windows account credentials you use to run 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 = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";

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

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

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

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

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

		// Define the push subscription.
		subscription = new TransSubscription();
		subscription.ConnectionContext = conn;
		subscription.SubscriberName = subscriberName;
		subscription.PublicationName = publicationName;
		subscription.DatabaseName = publicationDbName;
		subscription.SubscriptionDBName = subscriptionDbName;

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

                 // 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 push subscription.
		subscription.Create();
	}
	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
{
	conn.Disconnect();
}
// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksProductTran";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";

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

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

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

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

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

		// Define the push subscription.
		subscription = new TransSubscription();
		subscription.ConnectionContext = conn;
		subscription.SubscriberName = subscriberName;
		subscription.PublicationName = publicationName;
		subscription.DatabaseName = publicationDbName;
		subscription.SubscriptionDBName = subscriptionDbName;

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

                 // 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 push subscription.
		subscription.Create();
	}
	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
{
	conn.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 a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

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

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

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

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

        ' Define the push subscription.
        subscription = New TransSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName

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

        ' 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 push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try
' 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 a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

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

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

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

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

        ' Define the push subscription.
        subscription = New TransSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName

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

        ' 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 push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try

다음은 병합 게시에 새 밀어넣기 구독을 만드는 예입니다.This example creates a new push subscription to a merge publication. 병합 에이전트 작업을 실행하는 데 사용되는 Windows 계정 자격 증명은 런타임에 전달됩니다.The Windows account credentials you use to run 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 = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
string hostname = @"adventure-works\garrett1";

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

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

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

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

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

		// Define the push subscription.
		subscription = new MergeSubscription();
		subscription.ConnectionContext = conn;
		subscription.SubscriberName = subscriberName;
		subscription.PublicationName = publicationName;
		subscription.DatabaseName = publicationDbName;
		subscription.SubscriptionDBName = subscriptionDbName;
		subscription.HostName = hostname;

		// Set a schedule to synchronize the subscription every 2 hours
		// during weekdays from 6am to 10pm.
		subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly;
		subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32(0x003E);
		subscription.AgentSchedule.FrequencyRecurrenceFactor = 1;
		subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour;
		subscription.AgentSchedule.FrequencySubDayInterval = 2;
		subscription.AgentSchedule.ActiveStartDate = 20051108;
		subscription.AgentSchedule.ActiveEndDate = 20071231;
		subscription.AgentSchedule.ActiveStartTime = 060000;
		subscription.AgentSchedule.ActiveEndTime = 100000;

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

		// Create the push subscription.
		subscription.Create();
	}
	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
{
	conn.Disconnect();
}
// 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 a connection to the Publisher.
ServerConnection conn = new ServerConnection(subscriberName);

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

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

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

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

		// Define the push subscription.
		subscription = new MergeSubscription();
		subscription.ConnectionContext = conn;
		subscription.SubscriberName = subscriberName;
		subscription.PublicationName = publicationName;
		subscription.DatabaseName = publicationDbName;
		subscription.SubscriptionDBName = subscriptionDbName;
		subscription.HostName = hostname;

		// Set a schedule to synchronize the subscription every 2 hours
		// during weekdays from 6am to 10pm.
		subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly;
		subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32(0x003E);
		subscription.AgentSchedule.FrequencyRecurrenceFactor = 1;
		subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour;
		subscription.AgentSchedule.FrequencySubDayInterval = 2;
		subscription.AgentSchedule.ActiveStartDate = 20051108;
		subscription.AgentSchedule.ActiveEndDate = 20071231;
		subscription.AgentSchedule.ActiveStartTime = 060000;
		subscription.AgentSchedule.ActiveEndTime = 100000;

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

		// Create the push subscription.
		subscription.Create();
	}
	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
{
	conn.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 a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

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

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

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

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

        ' Define the push subscription.
        subscription = New MergeSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName
        subscription.HostName = hostname

        ' Set a schedule to synchronize the subscription every 2 hours
        ' during weekdays from 6am to 10pm.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly
        subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32("0x003E", 16)
        subscription.AgentSchedule.FrequencyRecurrenceFactor = 1
        subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour
        subscription.AgentSchedule.FrequencySubDayInterval = 2
        subscription.AgentSchedule.ActiveStartDate = 20051108
        subscription.AgentSchedule.ActiveEndDate = 20071231
        subscription.AgentSchedule.ActiveStartTime = 60000
        subscription.AgentSchedule.ActiveEndTime = 100000

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

        ' Create the push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try
' 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 a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

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

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

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

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

        ' Define the push subscription.
        subscription = New MergeSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName
        subscription.HostName = hostname

        ' Set a schedule to synchronize the subscription every 2 hours
        ' during weekdays from 6am to 10pm.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly
        subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32("0x003E", 16)
        subscription.AgentSchedule.FrequencyRecurrenceFactor = 1
        subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour
        subscription.AgentSchedule.FrequencySubDayInterval = 2
        subscription.AgentSchedule.ActiveStartDate = 20051108
        subscription.AgentSchedule.ActiveEndDate = 20071231
        subscription.AgentSchedule.ActiveStartTime = 60000
        subscription.AgentSchedule.ActiveEndTime = 100000

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

        ' Create the push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try

참고 항목See Also

밀어넣기 구독 속성 보기 및 수정 View and Modify Push Subscription Properties
복제 보안을 위한 최선의 구현 방법 Replication Security Best Practices
게시 만들기 Create a Publication
Replication Management Objects Concepts Replication Management Objects Concepts
밀어넣기 구독 동기화 Synchronize a Push Subscription
게시 구독 Subscribe to Publications
스크립팅 변수와 함께 sqlcmd 사용Use sqlcmd with Scripting Variables