创建推送订阅

本主题介绍如何使用 SQL Server Management Studio、Transact-SQL 或复制管理对象 (RMO) 在 SQL Server 2014 中创建推送订阅。 有关为非SQL Server订阅服务器创建推送订阅的信息,请参阅为非SQL Server订阅服务器创建订阅

使用 SQL Server Management Studio

使用新建订阅向导,在发布服务器或订阅服务器上创建推送订阅。 按照向导中的页的指示执行下列操作:

  • 指定发布服务器和发布。

  • 选择运行复制代理的位置。 对于推送订阅,根据发布类型的不同,在 “分发代理位置” 页或 “合并代理位置” 页上选择 “在分发服务器上运行所有代理(推送订阅)”

  • 指定订阅服务器和订阅数据库。

  • 指定复制代理建立连接所用的登录名和密码:

    • 对于快照发布和事务发布的订阅,在 “分发代理安全性” 页上指定凭据。

    • 对于合并发布的订阅,在 “合并代理安全性” 页上指定凭据。

    有关每个代理所需权限的信息,请参阅 R复制代理安全模式

  • 指定同步计划和初始化订阅服务器的时间。

  • 指定合并发布的其他选项:订阅类型以及用于参数化筛选的值。

  • 指定允许更新订阅的事务发布的其他选项:订阅服务器是立即在发布服务器上提交更改还是将它们写入队列、用于从订阅服务器连接到发布服务器的凭据。

  • 还可以编写订阅的脚本(可选)。

从发布服务器创建推送订阅

  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,为@property 指定allow_pushtrue@value 指定 。

  2. 在发布服务器的发布数据库中,执行 sp_addsubscription。 指定 @publication@subscriber@destination_db。 为@subscription_type指定推送值。 有关如何更新订阅的信息,请参阅 创建事务发布的可更新订阅

  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@subscriber_login和@subscriber_password的 Microsoft SQL Server登录信息。 如果您需要在连接到订阅服务器时使用 SQL Server 身份验证,则指定这些参数。

    • 该订阅的分发代理作业计划。 有关详细信息,请参阅 Specify Synchronization Schedules

    重要

    用远程分发服务器在发布服务器上创建推送订阅时,为所有参数(包括 job_loginjob_password)提供的值将以纯文本格式发送到分发服务器。 在执行此存储过程之前,应该对发布服务器及其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅启用数据库引擎的加密连接(SQL Server 配置管理器)

创建合并发布的推送订阅

  1. 在发布服务器的发布数据库中,通过执行 sp_helpmergepublication核实发布是否支持推送订阅。

    • 如果 allow_push 的值为 1,则发布支持推送订阅。

    • 如果 allow_push 的值不是 1,请执行 sp_changemergepublication,为@property 指定allow_pushtrue@value 指定。

  2. 在发布服务器的发布数据库中,执行 sp_addmergesubscription,并指定以下参数:

    • @publication。 这是发布的名称。

    • @subscriber_type。 对于客户端订阅,请指定 local ,对于服务器订阅,请指定 global

    • @subscription_priority。 对于服务器订阅,请指定订阅的优先级(从0.0099.99)。

      有关详细信息,请参阅 高级合并复制冲突的检测和解决

  3. 在发布服务器的发布数据库中,执行 sp_addmergepushsubscription_agent。 指定下列各项:

    • @subscriber@subscriber_db@publication参数。

    • 分发服务器上运行合并代理用于@job_login@job_password的 Windows 凭据。

      注意

      使用 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 身份验证,则指定这些值。

    • 该订阅的合并代理作业计划。 有关详细信息,请参阅 Specify Synchronization Schedules

    重要

    用远程分发服务器在发布服务器上创建推送订阅时,为所有参数(包括 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

使用复制管理对象 (RMO)

可以使用复制管理对象 (RMO) 以编程方式创建推送订阅。 用于创建推送订阅的 RMO 类取决于对其创建订阅的发布的类型。

重要

如果可能,请在运行时提示用户输入安全凭据。 如果必须存储凭据,请使用 Windows .NET Framework 提供的 Cryptographic Services Microsoft (加密服务)。

创建快照或事务发布的推送订阅

  1. 使用 ServerConnection 类创建与发布服务器的连接。

  2. 使用步骤 1 中的发布服务器连接,创建 TransPublication 类的实例。 指定 NameDatabaseNameConnectionContext

  3. 调用 LoadProperties 方法。 如果此方法返回 false,则步骤 2 中指定的属性不正确,或者服务器上不存在发布。

  4. Attributes 属性和 AllowPush 之间执行逻辑位与(在 Visual C# 中为 &,在 Visual Basic 中为 And)运算。 如果结果为 None,则将 Attributes 设置为 AttributesAllowPush 之间的逻辑位或(在 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. Attributes 属性和 AllowPush 之间执行逻辑位与(在 Visual C# 中为 &,在 Visual Basic 中为 And)运算。 如果结果为 None,则将 Attributes 设置为 AttributesAllowPush 之间的逻辑位或(在 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 与脚本变量结合使用