Freigeben über


Erstellen eines Pullabonnements

In diesem Thema wird das Erstellen eines Pullabonnements in SQL Server 2014 mithilfe von SQL Server Management Studio, Transact-SQL oder Replication Management Objects (RMO) beschrieben.

Das Einrichten eines Pullabonnements für die P2P-Replikation ist per Skript möglich, ist jedoch nicht über den Assistenten verfügbar.

Verwendung von SQL Server Management Studio

Erstellen Sie ein Pullabonnement beim Publisher oder Abonnenten mit dem Assistenten für neue Abonnements. Folgen Sie den Seiten im Assistenten, um:

  • Geben Sie den Herausgeber und die Publikation an.

  • Wählen Sie aus, wo Replikations-Agents ausgeführt werden sollen. Wählen Sie für ein Pullabonnement die Option "Jeden Agent bei seinem Abonnenten ausführen" (Pullabonnements) auf der Seite Standort des Verteilungsagents oder auf der Seite Standort des Zusammenführungsagents aus, je nach Publikationstyp.

  • Geben Sie Abonnenten- und Abonnementdatenbanken an.

  • Geben Sie die Anmeldeinformationen und Kennwörter an, die für Verbindungen von Replikations-Agents verwendet werden:

    • Geben Sie für Abonnements für Snapshot- und Transaktionspublikationen die Anmeldeinformationen auf der Seite "Sicherheit des Verteilungs-Agents " an.

    • Geben Sie für Abonnements von Zusammenführungspublikationen die Anmeldeinformationen auf der Seite „Merge Agent Security“ an.

    Informationen zu den berechtigungen, die für jeden Agent erforderlich sind, finden Sie unter Replikations-Agent-Sicherheitsmodell.

  • Geben Sie einen Synchronisierungszeitplan an und wann der Abonnent initialisiert werden soll.

  • Angeben zusätzlicher Optionen für die Zusammenführung von Publikationen: Abonnementtyp; Werte für parametrisierte Filterung; und Informationen zur Synchronisierung über HTTPS, wenn die Publikation für die Websynchronisierung aktiviert ist.

  • Geben Sie zusätzliche Optionen für Transaktionspublikationen an, die das Aktualisieren von Abonnements ermöglichen: Ob Abonnenten Änderungen an Publisher sofort übernehmen oder in eine Warteschlange schreiben sollen; Anmeldeinformationen, die zum Herstellen einer Verbindung vom Abonnenten mit dem Herausgeber verwendet werden.

  • Optional skripten Sie das Abonnement.

So erstellen Sie ein Pullabonnement aus dem Publisher

  1. Stellen Sie eine Verbindung mit Publisher in Microsoft SQL Server Management Studio her, und erweitern Sie dann den Serverknoten.

  2. Erweitern Sie den Replikationsordner , und erweitern Sie dann den Ordner " Lokale Publikationen ".

  3. Klicken Sie mit der rechten Maustaste auf die Publikation, für die Sie ein oder mehrere Abonnements erstellen möchten, und klicken Sie dann auf "Neue Abonnements".

  4. Füllen Sie die Seiten im Assistenten für neue Abonnements aus.

So erstellen Sie ein Pullabonnement vom Abonnenten

  1. Stellen Sie eine Verbindung mit dem Abonnenten in SQL Server Management Studio her, und erweitern Sie dann den Serverknoten.

  2. Erweitern Sie den Replikationsordner .

  3. Klicken Sie mit der rechten Maustaste auf den Ordner "Lokale Abonnements ", und klicken Sie dann auf "Neue Abonnements".

  4. Wählen Sie auf der Seite "Publikation" des Assistenten "Neues Abonnement" die Option <"SQL Server Publisher> suchen" oder <"Oracle Publisher> suchen" aus der Dropdownliste "Publisher" aus.

  5. Herstellen einer Verbindung mit dem Herausgeber im Dialogfeld " Mit Server verbinden "

  6. Wählen Sie auf der Seite "Publikation " eine Publikation aus.

  7. Füllen Sie die Seiten im Assistenten für neue Abonnements aus.

Verwenden von Transact-SQL

Pullabonnements können programmgesteuert mit gespeicherten Replikationsprozeduren erstellt werden. Die verwendeten gespeicherten Prozeduren hängen vom Typ der Veröffentlichung ab, zu der das Abonnement gehört.

So erstellen Sie ein Pullabonnement für eine Momentaufnahme oder transaktionsbasierte Publikation

  1. Vergewissern Sie sich bei Publisher, dass die Publikation Pullabonnements unterstützt, indem Sie sp_helppublication (Transact-SQL) ausführen.

    • Wenn der Wert von allow_pull im Resultset 1 ist, unterstützt die Publikation Pullabonnements.

    • Wenn der Wert von allow_pull0 ist, führen Sie sp_changepublication (Transact-SQL) aus, und geben Sie allow_pull für @property und true für @value an.

  2. Führen Sie beim Abonnenten sp_addpullsubscription (Transact-SQL) aus. Geben Sie @publisher und @publication an. Informationen zum Aktualisieren von Abonnements finden Sie unter Create an Updatable Subscription to a Transactional Publication.

  3. Führen Sie beim Abonnenten sp_addpullsubscription_agent (Transact-SQL) aus. Geben Sie Folgendes an:

    • Die Parameter @publisher, @publisher_db und @publication .

    • Die Microsoft Windows-Anmeldeinformationen, auf deren Grundlage der Verteilungs-Agent beim Abonnenten für @job_login und @job_password ausgeführt wird.

      Hinweis

      Verbindungen, die mit der integrierten Windows-Authentifizierung hergestellt werden, verwenden immer die von @job_login und @job_password angegebenen Windows-Anmeldeinformationen. Der Verteilungs-Agent stellt immer die lokale Verbindung mit dem Abonnenten mithilfe der integrierten Windows-Authentifizierung bereit. Standardmäßig stellt der Agent mithilfe der integrierten Windows-Authentifizierung eine Verbindung mit dem Distributor her.

    • (Optional) Der Wert 0 für @distributor_security_mode und die Microsoft SQL Server-Anmeldeinformationen für @distributor_login und @distributor_password, wenn Sie sql Server-Authentifizierung beim Herstellen einer Verbindung mit dem Distributor verwenden müssen.

    • Ein Zeitplan für den Verteiler-Agent-Auftrag für dieses Abonnement. Weitere Informationen finden Sie unter Angeben von Synchronisierungszeitplänen.

  4. Führen Sie im Publisher sp_addsubscription (Transact-SQL) aus, um das Pullabonnement zu registrieren. Geben Sie @publication, @subscriber und @destination_db an. Geben Sie einen Pullwert für @subscription_type an.

So erstellen Sie ein Pullabonnement für eine Zusammenführungsveröffentlichung

  1. Überprüfen Sie bei Publisher, ob die Publikation Pullabonnements unterstützt, indem Sie sp_helpmergepublication (Transact-SQL) ausführen.

    • Wenn der Wert von allow_pull im Resultset 1 ist, unterstützt die Publikation Pullabonnements.

    • Wenn der Wert von allow_pull0 ist, führen Sie sp_changemergepublication (Transact-SQL) aus, und geben Sie allow_pull für @property und true für @value an.

  2. Führen Sie beim Abonnenten sp_addmergepullsubscription (Transact-SQL) aus. Geben Sie @publisher, @publisher_db, @publication und die folgenden Parameter an:

    • @subscriber_type – Geben Sie lokal für ein Clientabonnement und global für ein Serverabonnement an.

    • @subscription_priority – Geben Sie eine Priorität für das Abonnement an (0.00 bis 99.99). Dies ist nur für ein Serverabonnement erforderlich.

      Weitere Informationen finden Sie unter Advanced Merge Replication Conflict Detection and Resolution.

  3. Führen Sie beim Abonnenten sp_addmergepullsubscription_agent (Transact-SQL) aus. Geben Sie die folgenden Parameter an:

    • @publisher, @publisher_db und @publication.

    • Die Windows-Anmeldeinformationen, unter denen der Seriendruck-Agent beim Abonnenten für @job_login und @job_password ausgeführt wird.

      Hinweis

      Verbindungen, die mit der integrierten Windows-Authentifizierung hergestellt werden, verwenden immer die von @job_login und @job_password angegebenen Windows-Anmeldeinformationen. Der Zusammenführungs-Agent führt immer die lokale Verbindung mit dem Abonnenten mithilfe der integrierten Windows-Authentifizierung durch. Standardmäßig stellt der Agent mithilfe der integrierten Windows-Authentifizierung eine Verbindung mit dem Distributor und Publisher her.

    • (Optional) Der Wert 0 für @distributor_security_mode und die SQL Server-Anmeldeinformationen für @distributor_login und @distributor_password, wenn Sie sql Server-Authentifizierung beim Herstellen einer Verbindung mit dem Verteiler verwenden müssen.

    • (Optional) Der Wert 0 für @publisher_security_mode und die SQL Server-Anmeldeinformationen für @publisher_login und @publisher_password, wenn Sie sql Server-Authentifizierung beim Herstellen einer Verbindung mit Publisher verwenden müssen.

    • Ein Zeitplan für die Aufgabe "Zusammenführungs-Agent" für dieses Abonnement. Weitere Informationen finden Sie unter Erstellen eines aktualisierbaren Abonnements für eine transaktionsbasierte Publikation.

  4. Führen Sie im Publisher sp_addmergesubscription (Transact-SQL) aus. Geben Sie @publication, @subscriber, @subscriber_db und einen Pullwert für@subscription_type an. Dadurch wird das Pullabonnement registriert.

Beispiele (Transact-SQL)

Im folgenden Beispiel wird ein Pullabonnement für eine transaktionsbasierte Publikation erstellt. Der erste Batch wird beim Abonnenten ausgeführt, und der zweite Batch wird beim Publisher ausgeführt. Anmelde- und Kennwortwerte werden zur Laufzeit mithilfe von sqlcmd-Skriptingvariablen bereitgestellt.

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

-- Execute this batch at the Subscriber.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';

-- At the subscription database, create a pull subscription 
-- to a transactional publication.
USE [AdventureWorks2012Replica]
EXEC sp_addpullsubscription 
  @publisher = @publisher, 
  @publication = @publication, 
  @publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.
EXEC sp_addpullsubscription_agent 
  @publisher = @publisher, 
  @publisher_db = @publicationDB, 
  @publication = @publication, 
  @distributor = @publisher, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables  
-- on the command line and in SQL Server Management Studio, see the 
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Publisher.
DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

-- At the Publisher, register the subscription, using the defaults.
EXEC sp_addsubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @destination_db = @subscriptionDB, 
  @subscription_type = N'pull',
  @status = N'subscribed';
GO

Im folgenden Beispiel wird ein Pull-Abonnement für eine Zusammenführungsveröffentlichung erstellt. Der erste Batch wird beim Abonnenten ausgeführt, und der zweite Batch wird beim Publisher ausgeführt. Anmelde- und Kennwortwerte werden zur Laufzeit mithilfe von sqlcmd-Skriptingvariablen bereitgestellt.


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

-- Execute this batch at the Subscriber.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';
SET @hostname = N'adventure-works\david8';

-- At the subscription database, create a pull subscription 
-- to a merge publication.
USE [AdventureWorks2012Replica]
EXEC sp_addmergepullsubscription 
  @publisher = @publisher, 
  @publication = @publication, 
  @publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription. 
EXEC sp_addmergepullsubscription_agent 
  @publisher = @publisher, 
  @publisher_db = @publicationDB, 
  @publication = @publication, 
  @distributor = @publisher, 
  @job_login = $(Login), 
  @job_password = $(Password),
  @hostname = @hostname;
GO
-- Execute this batch at the Publisher.
DECLARE @myMergePub  AS sysname;
DECLARE @mySub       AS sysname;
DECLARE @mySubDB     AS sysname;

SET @myMergePub = N'AdvWorksSalesOrdersMerge';
SET @mySub = N'MYSUBSERVER';
SET @mySubDB = N'AdventureWorks2012Replica';

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

Verwenden von Replikationsverwaltungsobjekten (RMO)

Die RMO-Klassen, die zum Erstellen eines Pullabonnements verwendet werden, hängen vom Typ der Publikation ab, zu der das Abonnement gehört.

So erstellen Sie ein Pullabonnement für eine Momentaufnahme oder eine transaktionsbasierte Publikation

  1. Erstellen Sie Verbindungen mit dem Abonnenten und Publisher mithilfe der ServerConnection Klasse.

  2. Erstellen Sie eine Instanz der TransPublication Klasse mithilfe der Publisher-Verbindung aus Schritt 1. Name, DatabaseName und ConnectionContext angeben.

  3. Rufen Sie die LoadProperties-Methode auf. Wenn diese Methode zurückgegeben wird false, sind entweder die in Schritt 2 angegebenen Eigenschaften falsch, oder die Publikation ist auf dem Server nicht vorhanden.

  4. Führen Sie eine bitweise logische UND-Verknüpfung (& in Visual C# und And in Visual Basic) zwischen der Attributes-Eigenschaft und AllowPull durch. Wenn das Ergebnis None ist, setzen Sie Attributes auf das Ergebnis eines bitweisen logischen ODER-Vergleichs (| in Visual C# und Or in Visual Basic) zwischen Attributes und AllowPull. Rufen Sie dann CommitPropertyChanges auf, um Pullabonnements zu aktivieren.

  5. Wenn die Abonnementdatenbank nicht vorhanden ist, erstellen Sie sie mithilfe der Database Klasse. Weitere Informationen finden Sie unter Erstellen, Ändern und Entfernen von Datenbanken.

  6. Erstellen Sie eine Instanz der TransPullSubscription Klasse.

  7. Legen Sie die folgenden Abonnementeigenschaften fest:

  8. Rufen Sie die Create-Methode auf.

  9. Rufen Sie mithilfe der Instanz der TransPublication Klasse aus Schritt 2 die MakePullSubscriptionWellKnown Methode auf, um das Pullabonnement bei Publisher zu registrieren. Wenn diese Registrierung bereits vorhanden ist, tritt eine Ausnahme auf.

So erstellen Sie ein Pullabonnement für eine Zusammenführungsveröffentlichung

  1. Erstellen Sie Verbindungen mit dem Abonnenten und Publisher mithilfe der ServerConnection Klasse.

  2. Erstellen Sie eine Instanz der MergePublication Klasse mithilfe der Publisher-Verbindung aus Schritt 1. Angeben Name, DatabaseName, und ConnectionContext.

  3. Rufen Sie die LoadProperties-Methode auf. Wenn diese Methode zurückgegeben wird false, sind entweder die in Schritt 2 angegebenen Eigenschaften falsch, oder die Publikation ist auf dem Server nicht vorhanden.

  4. Führen Sie eine bitweise logische UND-Verknüpfung (& in Visual C# und And in Visual Basic) zwischen der Attributes-Eigenschaft und AllowPull durch. Wenn das Ergebnis None ist, setzen Sie Attributes auf das Ergebnis eines bitweisen logischen ODER-Vergleichs (| in Visual C# und Or in Visual Basic) zwischen Attributes und AllowPull. Rufen Sie dann CommitPropertyChanges an, um Pullabonnements zu aktivieren.

  5. Wenn die Abonnementdatenbank nicht vorhanden ist, erstellen Sie sie mithilfe der Database Klasse. Weitere Informationen finden Sie unter Erstellen, Ändern und Entfernen von Datenbanken.

  6. Erstellen Sie eine Instanz der MergePullSubscription Klasse.

  7. Legen Sie die folgenden Abonnementeigenschaften fest:

  8. Rufen Sie die Create-Methode auf.

  9. Rufen Sie mithilfe der Instanz der MergePublication Klasse aus Schritt 2 die MakePullSubscriptionWellKnown Methode auf, um das Pullabonnement bei Publisher zu registrieren. Wenn diese Registrierung bereits vorhanden ist, tritt eine Ausnahme auf.

Beispiel (RMO)

In diesem Beispiel wird ein Pullabonnement für eine transaktionsbasierte Publikation erstellt. Die Anmeldeinformationen des Microsoft Windows-Kontos, die zum Erstellen des Verteiler-Agent-Auftrags verwendet werden, werden zur Laufzeit übergeben.

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

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

try
{
    // Connect to the Publisher and Subscriber.
    subscriberConn.Connect();
    publisherConn.Connect();

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

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

        // Define the pull subscription.
        subscription = new TransPullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;

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

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // By default, subscriptions to transactional publications are synchronized 
        // continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (TransSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                TransSubscriberType.ReadOnly);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksProductTran"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

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

Try
    ' Connect to the Publisher and Subscriber.
    subscriberConn.Connect()
    publisherConn.Connect()

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

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

        ' Define the pull subscription.
        subscription = New TransPullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.Description = "Pull subscription to " + publicationDbName _
        + " on " + subscriberName + "."

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

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' By default, subscriptions to transactional publications are synchronized 
        ' continuously, but in this case we only want to synchronize on demand.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.OnDemand

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As TransSubscription In publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName And _
                existing.SubscriptionDBName = subscriptionDbName Then
                registered = True
            End If
        Next existing
        If Not registered Then
            ' Register the subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             TransSubscriberType.ReadOnly)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

In diesem Beispiel wird ein Pull-Abonnement für eine Zusammenführungs-Publikation erstellt. Die Windows-Kontoanmeldeinformationen, die für die Erstellung des Zusammenführungs-Agentenauftrags verwendet werden, werden zur Laufzeit übergeben.

// 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 connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

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

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

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

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;
        subscription.HostName = hostname;

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

        // Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
Dim hostname As String = "adventure-works\garrett1"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

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

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

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

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname

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

        ' Make sure that the agent job for the subscription is created.
        subscription.CreateSyncAgentByDefault = True

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
        "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

In diesem Beispiel wird ein Pullabonnement für eine zusammengeführte Veröffentlichung erstellt, ohne einen zugeordneten Agentauftrag und Abonnementmetadaten in MSsubscription_properties zu erstellen. Die zum Erstellen des Merge-Agent-Auftrags verwendeten Windows-Kontoanmeldeinformationen werden während der Ausführung übergeben.

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

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

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

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

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

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;

        // Specify that an agent job not be created for this subscription. The
        // subscription can only be synchronized by running the Merge Agent directly.
        // Subscripition metadata stored in MSsubscription_properties will not
        // be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = false;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

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

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

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

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName

        ' Specify that an agent job not be created for this subscription. The
        ' subscription can only be synchronized by running the Merge Agent directly.
        ' Subscripition metadata stored in MSsubscription_properties will not
        ' be available and must be specified at run time.
        subscription.CreateSyncAgentByDefault = False

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

In diesem Beispiel wird ein Pullabonnement für eine Zusammenführungsveröffentlichung erstellt, die mithilfe der Websynchronisierung über das Internet synchronisiert werden kann. Die Windows-Kontoanmeldeinformationen, die zum Erstellen des Zusammenführungs-Agent-Auftrags verwendet werden, werden zur Laufzeit übergeben. Weitere Informationen finden Sie unter Konfigurieren der Websynchronisierung.

// 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";
string webSyncUrl = "https://" + publisherInstance + "/WebSync/replisapi.dll";

//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);

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

try
{
    // Connect to the Subscriber.
    subscriberConn.Connect();

    // Ensure that the publication exists and that 
    // it supports pull subscriptions and Web synchronization.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = publisherConn;

    if (publication.LoadProperties())
    {
        if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPull;
        }
        if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
        }

        // Define the pull subscription.
        subscription = new MergePullSubscription();
        subscription.ConnectionContext = subscriberConn;
        subscription.PublisherName = publisherName;
        subscription.PublicationName = publicationName;
        subscription.PublicationDBName = publicationDbName;
        subscription.DatabaseName = subscriptionDbName;
        subscription.HostName = hostname;

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

        // Enable Web synchronization.
        subscription.UseWebSynchronization = true;
        subscription.InternetUrl = webSyncUrl;

        // Specify the same Windows credentials to use when connecting to the
        // Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
        subscription.InternetLogin = winLogin;
        subscription.InternetPassword = winPassword;

        // Ensure that we create a job for this subscription.
        subscription.CreateSyncAgentByDefault = true;

        // Create the pull subscription at the Subscriber.
        subscription.Create();

        Boolean registered = false;

        // Verify that the subscription is not already registered.
        foreach (MergeSubscription existing
            in publication.EnumSubscriptions())
        {
            if (existing.SubscriberName == subscriberName
                && existing.SubscriptionDBName == subscriptionDbName
                && existing.SubscriptionType == SubscriptionOption.Pull)
            {
                registered = true;
            }
        }
        if (!registered)
        {
            // Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown(
                subscriberName, subscriptionDbName,
                SubscriptionSyncType.Automatic,
                MergeSubscriberType.Local, 0);
        }
    }
    else
    {
        // Do something here if the publication does not exist.
        throw new ApplicationException(String.Format(
            "The publication '{0}' does not exist on {1}.",
            publicationName, publisherName));
    }
}
catch (Exception ex)
{
    // Implement the appropriate error handling here.
    throw new ApplicationException(String.Format(
        "The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
    subscriberConn.Disconnect();
    publisherConn.Disconnect();
}
' Define the Publisher, publication, and databases.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publisherName As String = publisherInstance
Dim subscriberName As String = subscriberInstance
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
Dim hostname As String = "adventure-works\garrett1"
Dim webSyncUrl As String = "https://" + publisherInstance + "/WebSync/replisapi.dll"

'Create connections to the Publisher and Subscriber.
Dim subscriberConn As ServerConnection = New ServerConnection(subscriberName)
Dim publisherConn As ServerConnection = New ServerConnection(publisherName)

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

Try
    ' Connect to the Subscriber.
    subscriberConn.Connect()

    ' Ensure that the publication exists and that 
    ' it supports pull subscriptions and Web synchronization.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = publisherConn

    If publication.LoadProperties() Then
        If (publication.Attributes And PublicationAttributes.AllowPull) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPull
        End If
        If (publication.Attributes And PublicationAttributes.AllowWebSynchronization) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowWebSynchronization
        End If

        ' Define the pull subscription.
        subscription = New MergePullSubscription()
        subscription.ConnectionContext = subscriberConn
        subscription.PublisherName = publisherName
        subscription.PublicationName = publicationName
        subscription.PublicationDBName = publicationDbName
        subscription.DatabaseName = subscriptionDbName
        subscription.HostName = hostname
        subscription.CreateSyncAgentByDefault = True

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

        ' Enable Web synchronization.
        subscription.UseWebSynchronization = True
        subscription.InternetUrl = webSyncUrl

        ' Specify the same Windows credentials to use when connecting to the
        ' Web server using HTTPS Basic Authentication.
        subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication
        subscription.InternetLogin = winLogin
        subscription.InternetPassword = winPassword

        ' Create the pull subscription at the Subscriber.
        subscription.Create()

        Dim registered As Boolean = False

        ' Verify that the subscription is not already registered.
        For Each existing As MergeSubscription In _
        publication.EnumSubscriptions()
            If existing.SubscriberName = subscriberName Then
                registered = True
            End If
        Next
        If Not registered Then
            ' Register the local subscription with the Publisher.
            publication.MakePullSubscriptionWellKnown( _
             subscriberName, subscriptionDbName, _
             SubscriptionSyncType.Automatic, _
             MergeSubscriberType.Local, 0)
        End If
    Else
        ' Do something here if the publication does not exist.
        Throw New ApplicationException(String.Format( _
         "The publication '{0}' does not exist on {1}.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Implement the appropriate error handling here.
    Throw New ApplicationException(String.Format( _
     "The subscription to {0} could not be created.", publicationName), ex)
Finally
    subscriberConn.Disconnect()
    publisherConn.Disconnect()
End Try

Siehe auch

Konzepte für Replikationsverwaltungsobjekte
Anzeigen und Ändern der Eigenschaften von Pull-Abonnements
Konfigurieren der Websynchronisierung
Abonnieren von Veröffentlichungen
Bewährte Methoden für Replikationssicherheit