建立發送訂閱Create a push subscription

適用範圍:Applies to: 是SQL ServerSQL Server (所有支援的版本) yesSQL ServerSQL Server (all supported versions) 是Azure SQL DatabaseAzure SQL DatabaseYesAzure SQL DatabaseAzure SQL Database適用範圍:Applies to: 是SQL ServerSQL Server (所有支援的版本) yesSQL ServerSQL Server (all supported versions) 是Azure SQL DatabaseAzure SQL DatabaseYesAzure SQL DatabaseAzure SQL Database

本主題描述如何使用 SQL ServerSQL ServerSQL Server Management StudioSQL Server Management Studio或 Replication Management Objects (RMO) 來建立 Transact-SQLTransact-SQL中的發送訂閱。This topic describes how to create a push subscription in SQL ServerSQL Server 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.

注意

Azure SQL 受控執行個體可以是快照式與異動複寫的發行者、散發者與訂閱者。Azure SQL Managed Instance can be a publisher, distributor, and subscriber for snapshot and transactional replication. Azure SQL Database 中的資料庫只能是快照式與異動複寫的發送訂閱者。Databases in Azure SQL Database can only be push subscribers for snapshot and transactional replication. 如需詳細資訊,請參閱使用 Azure SQL DatabaseAzure SQL 受控執行個體的異動複寫。For more information, see Transactional replication with Azure SQL Database and Azure SQL Managed Instance.

使用 SQL Server Management StudioUsing SQL Server Management Studio

使用 [新增訂閱精靈] 在「發行者」或「訂閱者」端建立發送訂閱。Create a push subscription at the Publisher or the Subscriber by 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.

      如需各代理程式所需權限的資訊,請參閱複寫代理程式安全性模型For information about the permissions that each agent requires, 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. 其中一個選項是決定訂閱者是否應立即在發行者端認可變更,或將其寫入佇列。One option is to decide whether Subscribers should commit changes at the Publisher immediately or write them to a queue. 另一個選項是設定用來從訂閱者連線至發行者的認證。Another option is setting up 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 select 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 select New Subscriptions.

  4. 在 [新增訂閱] 精靈的 [發行集] 頁面上,從 [發行者] 下拉式清單中選取 [<Find SQL Server Publisher>] 或 [<Find Oracle Publisher>]。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-SQLUsing Transact-SQL

您可以使用複寫預存程序,以程式設計的方式建立發送訂閱。You can create push subscriptions programmatically by using replication stored procedures. 使用哪些預存程序要依訂閱所屬的發行集類型而定。The stored procedures used will depend on the type of publication to which the subscription belongs.

重要

可能的話,會在執行階段提示使用者輸入安全性認證。When possible, prompt users to enter security credentials at runtime. 如果您必須將認證儲存在指令碼檔案中,則必須維護這個檔案的安全性,使他人無法在未獲授權的情況下擅自存取。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 running sp_helppublication.

    • 如果 allow_push 的值為 1,則發送訂閱受到支援。If the value of allow_push is 1, push subscriptions are supported.

    • 如果 allow_push 的值為 0,請執行 sp_changepublicationIf the value of allow_push is 0, run sp_changepublication. 針對 @property 指定 allow_push,並針對 @value 指定 trueSpecify allow_push for @property and true for @value.

  2. 在發行集資料庫的發行者上,執行 sp_addsubscriptionAt the Publisher on the publication database, run sp_addsubscription. 指定 @publication@subscriber@destination_dbSpecify @publication, @subscriber, and @destination_db. @subscription_type 的值指定為 pushSpecify a value of push for @subscription_type. 如需如何更新訂閱的資訊,請參閱建立交易式發行集的可更新訂閱For information about how to update subscriptions, see Create an updatable subscription to a transactional publication.

  3. 在發行集資料庫的發行者上,執行 sp_addpushsubscription_agentAt the Publisher on the publication database, run sp_addpushsubscription_agent. 指定下列項目:Specify the following:

    • @subscriber@subscriber_db@publication 參數。The @subscriber, @subscriber_db, and @publication parameters.

    • MicrosoftMicrosoft Windows 認證,執行「散發者」上的「散發代理程式」時會針對 @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 認證。Connections made through 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 by using Windows Integrated Authentication. 根據預設,代理程式會使用 Windows 整合式驗證連線至訂閱者。By default, the agent will connect to the Subscriber by using Windows Integrated Authentication.

    • (選擇性) @subscriber_security_mode 的值 0,以及 @subscriber_login@subscriber_passwordMicrosoftMicrosoft SQL ServerSQL Server 登入資訊。(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. 如需詳細資訊,請參閱指定同步處理排程For more information, see Specify synchronization schedules.

重要

當您使用遠端散發者來建立發行者上的發送訂閱時,提供給所有參數的值 (包括 job_loginjob_password) 都會以純文字格式傳送給散發者。When you're 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 running 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 running sp_helpmergepublication.

    • 如果 allow_push 的值為 1,則發行集支援發送訂閱。If the value of allow_push is 1, the publication supports push subscriptions.

    • 如果 allow_push 的值不為 1,請執行 sp_changemergepublicationIf the value of allow_push is not 1, run sp_changemergepublication. 針對 @property 指定 allow_push,並針對 @value 指定 trueSpecify allow_push for @property and true for @value.

  2. 在發行集資料庫的發行者上,執行 sp_addmergesubscriptionAt the Publisher on the publication database, run sp_addmergesubscription. 指定下列參數:Specify the following parameters:

    • @Publication@publication. 這是發行集的名稱。This is the name of the publication.

    • @subscriber_type@subscriber_type. 針對客訂閱,請指定 localFor a client subscription, specify local. 針對主訂閱,請指定 globalFor a server subscription, specify global.

    • @subscription_priority@subscription_priority. 指定主訂閱的訂閱優先權 (從 0.0099.99)。For a server subscription, specify a priority for the subscription (0.00 to 99.99).

    如需詳細資訊,請參閱進階合併式複寫衝突偵測與解決For more information, see Advanced merge replication conflict detection and resolution.

  3. 在發行集資料庫的發行者上,執行 sp_addmergepushsubscription_agentAt the Publisher on the publication database, run sp_addmergepushsubscription_agent. 指定下列項目:Specify the following:

    • @subscriber@subscriber_db@publication 參數。The @subscriber, @subscriber_db, and @publication parameters.

    • Windows 認證,執行「散發者」上的「合併代理程式」時會針對 @job_login@job_password 使用該認證。The Windows credentials under which the Merge Agent at the Distributor runs for @job_login and @job_password.

      注意

      透過 Windows 整合式驗證進行的連線,一律使用由 @job_login@job_password 指定的 Windows 認證。Connections made through 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 by using Windows Integrated Authentication. 根據預設,代理程式會使用 Windows 整合式驗證連線至訂閱者。By default, the agent will connect to the Subscriber by using Windows Integrated Authentication.

    • (選擇性) @subscriber_security_mode 的值 0,以及 @subscriber_login@subscriber_passwordSQL ServerSQL Server 登入資訊。(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.

    • (選擇性) @publisher_security_mode 的值 0,以及 @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. 如果您在連接到「發行者」時需要使用「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. 如需詳細資訊,請參閱指定同步處理排程For more information, see Specify synchronization schedules.

重要

當您使用遠端散發者來建立發行者上的發送訂閱時,提供給所有參數的值 (包括 job_loginjob_password) 都會以純文字格式傳送給散發者。When you're 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 running 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 runtime through 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

下列範例會建立合併式發行集的發送訂閱。The following example creates a push subscription to a merge publication. 登入和密碼值是在執行階段透過 sqlcmd 指令碼變數所提供。Login and password values are supplied at runtime through 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

使用 Replication Management ObjectsUsing Replication Management Objects

您可以使用 Replication Management Objects (RMO) 以程式設計的方式建立發送訂閱。You can create push subscriptions programmatically by using Replication Management Objects (RMO). 用於建立發送訂閱的 RMO 類別,依該訂閱所屬的發行集類型而定。The RMO classes that you use to create a push subscription depend on the type of publication to which the subscription is created.

重要

可能的話,會在執行階段提示使用者輸入安全性認證。When possible, prompt users to enter security credentials at runtime. 如果您必須儲存認證,請使用 MicrosoftMicrosoft Windows .NET Framework 提供的密碼編譯服務If you must store credentials, use the cryptographic services that the MicrosoftMicrosoft Windows .NET Framework provides.

若要建立快照式或交易式發行集的發送訂閱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. 指定 NameDatabaseNameConnectionContextSpecify 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. & 屬性和 And 之間執行位元運算邏輯 AND (Visual C# 中的 Attributes 和 Visual Basic 中的 AllowPush>。Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. 如果結果為 None,則將 Attributes 設為 | 屬性和 Or 之間位元運算邏輯 OR (Visual C# 中的 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) 都會以純文字方式傳送給散發者。When you're 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. 指定 NameDatabaseNameConnectionContextSpecify 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. & 屬性和 And 之間執行位元運算邏輯 AND (Visual C# 中的 Attributes 和 Visual Basic 中的 AllowPush>。Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. 如果結果為 None,則將 Attributes 設為 | 屬性和 Or 之間位元運算邏輯 OR (Visual C# 中的 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.

重要

當您使用遠端散發者來建立發行者的發送訂閱時,提供給所有屬性的值 (包括 SynchronizationAgentProcessSecurity) 都會以純文字方式傳送給散發者。When you're 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 that 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(publisherName);

           // 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(publisherName)

' 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 that 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(publisherName);

// 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(publisherName)

' 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
同步處理發送訂閱 Synchronize a push subscription
訂閱發行集 Subscribe to publications
以指令碼變數使用 sqlcmdUse sqlcmd with scripting variables