共用方式為


建立推送訂閱

本主題描述如何使用 SQL Server Management Studio、Transact-SQL 或 Replication Management Objects (RMO) 在 SQL Server 2014 中建立發送訂閱。 如需為非 SQL Server 訂閱者建立發送訂閱的相關信息,請參閱 建立非 SQL Server 訂閱者的訂閱

使用 SQL Server Management Studio

使用 [新增訂閱精靈] 於發行者或訂閱者端建立推送訂閱。 按嚮導中的頁面指引:

  • 指定發行者和出版物。

  • 選取複寫代理程式將執行的位置。 針對發送訂閱,請根據發行集的類型,選取 [散發者位置] 頁面或 [合併代理程式位置] 頁面上的 [在散發者端執行所有代理程式(發送訂閱]

  • 指定訂閱者和訂閱資料庫。

  • 指定複寫代理程式所建立連接所使用的登入和密碼:

    • 針對快照式發行集和交易式發行集的訂閱,請在 [ 散發代理程序安全性 ] 頁面上指定認證。

    • 針對合併發行的訂閱,請在 [合併代理程式安全性] 頁面上指定認證資訊。

    如需有關各代理程式需要的權限資訊,請參閱< 複寫代理程式安全性模型>。

  • 指定同步排程,並決定應在何時初始化訂閱者。

  • 指定合併式發行集的其他選項:訂閱類型;參數化篩選的 和 值。

  • 為允許訂閱更新的交易式發行集指定其他選項:訂閱者是否應立即提交在發行者端的變更,或將它們寫入佇列,以及用來從訂閱者連接到發行者的認證。

  • 選擇性地撰寫訂閱服務的腳本。

從發行者建立推送訂閱

  1. 在 Microsoft SQL Server Management Studio 中連接到發行者,然後展開伺服器節點。

  2. 展開 複寫 資料夾,然後展開 本機發行集 資料夾。

  3. 右鍵點擊您想要建立一或多個訂閱的發行集,然後點擊新增訂閱

  4. 完成 [新增訂閱精靈] 中的頁面。

從訂閱者建立推送訂閱

  1. 連線到 SQL Server Management Studio 中的訂閱者,然後展開伺服器節點。

  2. 展開 [ 複寫 ] 資料夾。

  3. 以滑鼠右鍵按兩下 [ 本機訂閱] 資料夾,然後按兩下 [ 新增訂閱]。

  4. 在 [新增訂閱精靈] 的 [發行集] 頁面上,從 [發行者] 下拉式清單中選取 <[尋找 SQL Server 發行>者] 或 <[尋找 Oracle 發行者>]。

  5. 在 [ 連接到伺服器 ] 對話框中連接到發行者。

  6. 在 [出版物] 頁面上選擇 出版物

  7. 在 [新增訂閱精靈] 中填寫所有頁面。

使用 Transact-SQL

可以使用複寫預存程式以程式設計方式建立推送訂閱。 使用的預存程式將取決於訂閱所屬的發行集類型。

這很重要

可能的話,提示使用者在運行時間輸入安全性認證。 如果您必須將認證儲存在指令碼檔案中,則必須維護這個檔案的安全性,使他人無法在未獲授權的情況下擅自存取。

建立快照型或交易型出版的推送訂閱

  1. 在發行集資料庫的發行者端,執行 sp_helppublication,確認發行集支援發送訂閱。

    • 如果 allow_push 值為 1,則支援發送訂閱。

    • 如果allow_push值為0,請執行sp_changepublication,並設置allow_push@property以及對true@value進行指定。

  2. 在發行者的發行集資料庫上,執行 sp_addsubscription。 指定 @publication@subscriber@destination_db。 指定@subscription_type的值為push。 如需如何更新訂閱的資訊,請參閱 建立交易式發行集的可更新訂閱

  3. 在發佈資料庫的發行者系統上,執行 sp_addpushsubscription_agent。 指定下列項目:

    • @subscriber@subscriber_db@publication參數。

    • 在散發者端,散發代理程式執行@job_login@job_password時所使用的 Microsoft Windows 認證。

      備註

      使用 Windows 整合式驗證建立的連接一律使用 @job_login@job_password指定的 Windows 認證。 配送代理程式總是使用 Windows 整合式驗證與本地的分發站進行連線。 根據預設,代理程式會使用 Windows 整合式驗證連接到訂閱者。

    • (選擇性)@subscriber_security_mode 的值為 0,以及 Microsoft SQL Server 的登入資訊,包括 @subscriber_login@subscriber_password。 如果您需要在連接到訂閱者時使用 SQL Server 驗證,請指定這些參數。

    • 此訂閱的散發代理工作排程。 如需詳細資訊,請參閱 指定同步處理排程

    這很重要

    當在具有遠端散發者的發行者端建立推送訂閱時,所有參數的值,包括job_loginjob_password,都會以純文本形式傳送給散發者。 您應該先加密「發行者」及其遠端「散發者」之間的連接,再執行這個預存程序。 如需詳細資訊,請參閱啟用資料庫引擎的加密連線 (SQL Server 組態管理員)

建立合併發行的推送訂閱

  1. 在發行者的發行集資料庫中,執行 sp_helpmergepublication 以確認發行集是否支援推送訂閱。

    • 如果 allow_push 值為 1,出版物支持推送訂閱。

    • 如果allow_push的值不是 1,請執行 sp_changemergepublication,並針對@propertytrue@value 指定allow_push

  2. 在發行集資料庫的發行者上,執行 sp_addmergesubscription,並指定下列參數:

    • @publication。 這是刊物的名稱。

    • @subscriber_type。 針對客戶端訂閱,指定 本機;針對伺服器訂閱,指定 全域

    • @subscription_priority。 針對伺服器訂用帳戶,指定訂用帳戶的優先順序 (0.0099.99)。

      如需詳細資訊,請參閱 進階合併式複寫衝突偵測與解決

  3. 在發行集資料庫的發行者上,執行 sp_addmergepushsubscription_agent。 指定下列項目:

    • @subscriber@subscriber_db@publication參數。

    • 在散發者端,合併代理程式使用 Windows 認證執行 @job_login@job_password

      備註

      使用 Windows 整合式驗證建立的連接一律使用 @job_login@job_password指定的 Windows 認證。 合併代理程式一律會使用 Windows 整合式驗證對發行者進行本地端連線。 根據預設,代理程式會使用 Windows 整合式驗證連接到訂閱者。

    • (選擇性)@subscriber_security_mode 的值為 0,以及 @subscriber_login@subscriber_password 的 SQL Server 登入資訊。 如果您需要在連接到訂閱者時使用 SQL Server 驗證,請指定這些參數。

    • (選擇性)@publisher_security_mode 的值為 0,以及 @publisher_login 和 @publisher_password 的 SQL Server 登入資訊。 如果您需要在連接到發行者時使用 SQL Server 驗證,請指定這些值。

    • 此訂用帳戶的合併代理程序作業排程。 如需詳細資訊,請參閱 指定同步處理排程

    這很重要

    當在具有遠端散發者的發行者端建立推送訂閱時,所有參數的值,包括job_loginjob_password,都會以純文本形式傳送給散發者。 您應該先加密「發行者」及其遠端「散發者」之間的連接,再執行這個預存程序。 如需詳細資訊,請參閱啟用資料庫引擎的加密連線 (SQL Server 組態管理員)

範例 (Transact-SQL)

下列範例會建立交易式出版物的推送訂閱。 登入和密碼值是在運行時間使用 sqlcmd 腳本變數來提供。

-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables  
-- on the command line and in SQL Server Management Studio, see the 
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

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

下列範例會建立推送式訂閱以進行合併發行。 登入和密碼值是在運行時間使用 sqlcmd 腳本變數來提供。

-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables  
-- on the command line and in SQL Server Management Studio, see the 
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

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 Objects (RMO)

您可以透過程式設計的方式使用複寫管理物件 (RMO) 來建立推送訂閱。 您用來建立發送訂閱的 RMO 類別取決於建立訂閱的發行集類型。

這很重要

可能的話,會在執行階段提示使用者輸入安全性認證。 如果您必須儲存認證,請使用 Microsoft Windows .NET Framework 提供的密碼編譯服務

建立快照型或交易型出版的推送訂閱

  1. 使用 ServerConnection 類別建立與發行者的連接。

  2. 使用步驟 1 中的發行者連線,建立 類別的 TransPublication 實例。 指定 NameDatabaseNameConnectionContext

  3. 呼叫 LoadProperties 方法。 如果這個方法傳 false回 ,則步驟 2 中指定的屬性不正確,或發行集不存在於伺服器上。

  4. Attributes 屬性與 AllowPush 之間執行位元邏輯 AND(在 Visual C# 中為 & 和在 Visual Basic 中為 And)。 如果結果為 None,請將 Attributes 設定為 AttributesAllowPush 之間的位邏輯 OR 結果(在 Visual C# 中是 |,在 Visual Basic 中是 Or)。 然後,呼叫 CommitPropertyChanges 以啟用發送訂閱。

  5. 如果訂閱資料庫不存在,請使用 Database 類別加以建立。 如需詳細資訊,請參閱 建立、改變和移除資料庫

  6. 建立 TransSubscription 類別的執行個體。

  7. 設定下列訂用帳戶屬性:

  8. 呼叫 Create 方法。

    這很重要

    在具有遠端配發者的發行者上建立推送訂閱時,所有屬性提供的值,包括 SynchronizationAgentProcessSecurity,都會以純文本形式傳送給配發者。 您應該先加密發行者與其遠端散發者之間的連線,再呼叫 Create 方法。 如需詳細資訊,請參閱啟用資料庫引擎的加密連線 (SQL Server 組態管理員)

建立合併發行的推送訂閱

  1. 使用 ServerConnection 類別建立與發行者的連接。

  2. 使用步驟 1 中的發行者連線,建立 類別的 MergePublication 實例。 指定 NameDatabaseNameConnectionContext

  3. 呼叫 LoadProperties 方法。 如果這個方法傳 false回 ,則步驟 2 中指定的屬性不正確,或發行集不存在於伺服器上。

  4. 在屬性AttributesAllowPush之間執行位元邏輯 AND(在 Visual C# 中為& 和在 Visual Basic 中為And)。 如果結果為 None,請將 Attributes 設定為 AttributesAllowPush 之間進行位元邏輯 OR 的結果(在 Visual C# 中為 |,在 Visual Basic 中為 Or)。 然後,呼叫 CommitPropertyChanges 以啟用發送訂閱。

  5. 如果訂閱資料庫不存在,請使用 Database 類別加以建立。 如需詳細資訊,請參閱 建立、改變和移除資料庫

  6. 建立 MergeSubscription 類別的執行個體。

  7. 設定下列訂用帳戶屬性:

  8. 呼叫 Create 方法。

    這很重要

    在具有遠端配發者的發行者上建立推送訂閱時,所有屬性提供的值,包括 SynchronizationAgentProcessSecurity,都會以純文本形式傳送給配發者。 您應該先加密發行者與其遠端散發者之間的連線,再呼叫 Create 方法。 如需詳細資訊,請參閱啟用資料庫引擎的加密連線 (SQL Server 組態管理員)

範例 (RMO)

此範例會為事務型發行建立新的推送訂閱。 您用來執行散發代理程式作業的 Windows 帳戶認證會在執行時間傳遞。

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

此範例會建立一個新的合併發布的推送訂閱。 您用來執行合併代理程式作業的 Windows 帳戶認證會在執行時間傳遞。

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

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

另請參閱

檢視及修改發送訂閱屬性
複寫安全性最佳作法
創建出版物
複寫管理物件概念
同步推送訂閱
訂閱發行集
搭配腳本變數使用 sqlcmd