Synchroniser un abonnement par extractionSynchronize a Pull Subscription

Cette rubrique explique comment synchroniser un abonnement par extraction de données (pull) dans SQL Server 2016SQL Server 2016 à l'aide de SQL Server Management StudioSQL Server Management Studio, d'agents de réplication ou d'objets RMO (Replication Management Objects).This topic describes how to synchronize a pull subscription in SQL Server 2016SQL Server 2016 by using SQL Server Management StudioSQL Server Management Studio, replication agents, or Replication Management Objects (RMO).

Dans cette rubriqueIn This Topic

Utilisation de SQL Server Management Studio Using SQL Server Management Studio

Les abonnements sont synchronisés par l'Agent de distribution (pour la réplication transactionnelle et d'instantané) ou l'Agent de fusion (pour la réplication de fusion).Subscriptions are synchronized by the Distribution Agent (for snapshot and transactional replication) or the Merge Agent (for merge replication). Les agents peuvent s'exécuter en continu, à la demande ou selon une planification.Agents can run continuously, run on demand, or run on a schedule. Pour plus d’informations sur la spécification de planifications de synchronisation, consultez Spécifier des planifications de synchronisation.For more information about specifying synchronization schedules, see Specify Synchronization Schedules.

Synchronisez un abonnement à la demande à partir du dossier Publications locales dans SQL Server Management StudioSQL Server Management Studio.Synchronize a subscription on demand from the Local Subscriptions folder in SQL Server Management StudioSQL Server Management Studio.

Pour synchroniser à la demande un abonnement par extraction de données dans Management StudioTo synchronize a pull subscription on demand in Management Studio

  1. Connectez-vous à l'Abonné dans Management StudioManagement Studio, puis développez le nœud du serveur.Connect to the Subscriber in Management StudioManagement Studio, and then expand the server node.

  2. Développez le dossier Réplication , puis développez le dossier Abonnements locaux .Expand the Replication folder, and then expand the Local Subscriptions folder.

  3. Cliquez avec le bouton droit sur l'abonnement à synchroniser, puis cliquez sur Afficher l'état de synchronisation.Right-click the subscription you want to synchronize, and then click View Synchronization Status.

  4. Dans la boîte de dialogue Afficher l’état de synchronisation - <Abonné> : <Base_de_données_Abonnement>, cliquez sur Démarrer.In the View Synchronization Status - <Subscriber>:<SubscriptionDatabase> dialog box, click Start. Lorsque la synchronisation est terminée, le message Synchronisation terminée s'affiche.When synchronization is complete, the message Synchronization completed is displayed.

  5. Cliquez sur Fermer.Click Close.

Replication Agents Replication Agents

Les abonnements par extraction de données (pull) peuvent être synchronisés par le biais de la programmation et à la demande en appelant le fichier exécutable de l'Agent de réplication approprié à partir de l'invite de commandes.Pull subscriptions can be synchronized programmatically and on-demand by invoking the appropriate replication agent executable file from the command prompt. Le fichier exécutable de l'Agent de réplication qui est appelé dépend du type de publication à laquelle l'abonnement par extraction de données (pull) appartient.The replication agent executable file that is invoked will depend on the type of publication to which the pull subscription belongs. Pour plus d'informations, voir Replication Agents.For more information, see Replication Agents.

Note

Les Agents de réplication se connectent au serveur local au moyen des informations d'identification d'authentification Windows de l'utilisateur qui a démarré l'agent à partir de l'invite de commandes.Replication agents connect to the local server using the Windows Authentication credentials of the user who started the agent from the command prompt. Ces informations d'identification Windows sont également utilisées lors de la connexion à des serveurs distants au moyen de l'authentification intégrée Windows.These Windows credentials are also used when connecting to remote servers using Windows Integrated Authentication.

Pour démarrer l'Agent de distribution à partir de l'invite de commandes ou à partir d'un fichier de commandesTo start the distribution agent from the command prompt or from a batch file

  1. À partir de l'invite de commandes ou dans un fichier de commandes, démarrez l' Agent de distribution de réplication en exécutant distrib.exeet en spécifiant les arguments suivant sur la ligne de commande :From the command prompt or in a batch file, start the Replication Distribution Agent by running distrib.exe, specifying the following command-line arguments:

    • -Publisher-Publisher

    • -PublisherDB-PublisherDB

    • -Distributor-Distributor

    • -DistributorSecurityMode = 1-DistributorSecurityMode = 1

    • -Subscriber-Subscriber

    • -SubscriberDB-SubscriberDB

    • -SubscriberSecurityMode = 1-SubscriberSecurityMode = 1

    • -SubscriptionType = 1-SubscriptionType = 1

      Si vous utilisez l'authentification SQL ServerSQL Server , vous devez également spécifier les arguments suivants :If you are using SQL ServerSQL Server Authentication, you must also specify the following arguments:

    • -DistributorLogin-DistributorLogin

    • -DistributorPassword-DistributorPassword

    • -DistributorSecurityMode = 0-DistributorSecurityMode = 0

    • -PublisherLogin-PublisherLogin

    • -PublisherPassword-PublisherPassword

    • -PublisherSecurityMode = 0-PublisherSecurityMode = 0

    • -SubscriberLogin-SubscriberLogin

    • -SubscriberPassword-SubscriberPassword

    • -SubscriberSecurityMode = 0-SubscriberSecurityMode = 0

Pour démarrer l'Agent de fusion à partir de l'invite de commandes ou à partir d'un fichier de commandesTo start the merge agent from the command prompt or from a batch file

  1. À partir de l'invite de commandes ou dans un fichier de commandes, démarrez l' Agent de fusion de réplication en exécutant replmerg.exeet en spécifiant les arguments suivant sur la ligne de commande :From the command prompt or in a batch file, start the Replication Merge Agent by running replmerg.exe, specifying the following command-line arguments:

    • -Publisher-Publisher

    • -PublisherDB-PublisherDB

    • -PublisherSecurityMode = 1-PublisherSecurityMode = 1

    • -Publication-Publication

    • -Distributor-Distributor

    • -DistributorSecurityMode = 1-DistributorSecurityMode = 1

    • -Subscriber-Subscriber

    • -SubscriberSecurityMode = 1-SubscriberSecurityMode = 1

    • -SubscriberDB-SubscriberDB

    • -SubscriptionType = 1-SubscriptionType = 1

      Si vous utilisez l'authentification SQL ServerSQL Server , vous devez également spécifier les arguments suivants :If you are using SQL ServerSQL Server Authentication, you must also specify the following arguments:

    • -DistributorLogin-DistributorLogin

    • -DistributorPassword-DistributorPassword

    • -DistributorSecurityMode = 0-DistributorSecurityMode = 0

    • -PublisherLogin-PublisherLogin

    • -PublisherPassword-PublisherPassword

    • -PublisherSecurityMode = 0-PublisherSecurityMode = 0

    • -SubscriberLogin-SubscriberLogin

    • -SubscriberPassword-SubscriberPassword

    • -SubscriberSecurityMode = 0-SubscriberSecurityMode = 0

Exemples (Agents de réplication) Examples (Replication Agents)

L'exemple suivant démarre l'Agent de distribution pour synchroniser un abonnement par extraction de données (pull).The following example starts the Distribution Agent to synchronize a pull subscription. Toutes les connexions sont effectuées au moyen de l'authentification Windows.All connections are made using Windows Authentication.

 -- Declare the variables.  
SET Publisher=%instancename%  
SET Subscriber=%instancename%  
SET PublicationDB=AdventureWorks  
SET SubscriptionDB=AdventureWorksReplica   
SET Publication=AdvWorksProductsTran  

-- Start the Distribution Agent.  
-- The following command must be supplied without line breaks.  
"C:\Program Files\Microsoft SQL Server\100\COM\DISTRIB.EXE" -Subscriber %Subscriber%   
-SubscriberDB %SubscriptionDB% -SubscriberSecurityMode 1 -Publication %Publication%   
-Publisher %Publisher% -PublisherDB %PublicationDB% -Distributor %Publisher%   
-DistributorSecurityMode 1 -Continuous -SubscriptionType 1;  

L'exemple suivant démarre l'Agent de fusion pour synchroniser un abonnement par extraction de données (pull).The following example starts the Merge Agent to synchronize a pull subscription. Toutes les connexions sont effectuées au moyen de l'authentification Windows.All connections are made using Windows Authentication.

-- Declare the variables.  
SET Publisher=%instancename%  
SET Subscriber=%instancename%  
SET PublicationDB=AdventureWorks  
SET SubscriptionDB=AdventureWorksReplica   
SET Publication=AdvWorksSalesOrdersMerge  

--Start the Merge Agent with concurrent upload and download processes.  
-- The following command must be supplied without line breaks.  
"C:\Program Files\Microsoft SQL Server\100\COM\REPLMERG.EXE" -Publication %Publication%    
-Publisher %Publisher%  -Subscriber  %Subscriber%  -Distributor %Publisher%    
-PublisherDB %PublicationDB%  -SubscriberDB %SubscriptionDB% -PublisherSecurityMode 1    
-OutputVerboseLevel 2  -SubscriberSecurityMode 1  -SubscriptionType 1 -DistributorSecurityMode 1    
-Validate 3  -ParallelUploadDownload 1 ;  

Utilisation d'objets RMO (Replication Management Objects) Using Replication Management Objects (RMO)

Vous pouvez synchroniser des abonnements par extraction de données (pull) au moyen d'objets RMO (Replication Management Objects) et d'un accès par code managé aux fonctionnalités de l'Agent de réplication.You can synchronize pull subscriptions programmatically by using Replication Management Objects (RMO) and managed code access to replication agent functionalities. Les classes que vous utilisez pour synchroniser un abonnement par extraction de données (pull) sont fonction du type de publication à laquelle l'abonnement appartient.The classes you use to synchronize a pull subscription depend on the type of publication to which the subscription belongs.

Note

Si vous voulez démarrer une synchronisation qui s'exécute de façon autonome sans affecter votre application, démarrez l'agent en mode asynchrone.If you want to start a synchronization that runs autonomously without affecting your application, start the agent asynchronously. Toutefois, si vous voulez analyser le résultat de la synchronisation et recevoir des rappels à partir de l'agent au cours du processus de synchronisation (par exemple, pour afficher une barre de progression), démarrez l'agent en mode synchrone.However, if you want to monitor the outcome of the synchronization and receive callbacks from the agent during the synchronization process (for example, to display a progress bar), you should start the agent synchronously. For MicrosoftMicrosoft SQL Server 2005 Express EditionSQL Server 2005 Express Edition Subscribers, you must start the agent synchronously.For MicrosoftMicrosoft SQL Server 2005 Express EditionSQL Server 2005 Express Edition Subscribers, you must start the agent synchronously.

Pour synchroniser un abonnement par extraction vers une publication d'instantané ou transactionnelleTo synchronize a pull subscription to a snapshot or transactional publication

  1. Créez une connexion à l’abonné en utilisant la classe ServerConnection.Create a connection to the Subscriber by using the ServerConnection class.

  2. Créez une instance de la classe TransPullSubscription, puis définissez les propriétés suivantes :Create an instance of the TransPullSubscription class, and set the following properties:

  3. Appelez la méthode LoadProperties pour obtenir les propriétés d’abonnement restantes.Call the LoadProperties method to get the remaining subscription properties. Si cette méthode retourne false, vérifiez que l'abonnement existe.If this method returns false, verify that the subscription exists.

  4. Démarrez l'Agent de distribution sur l'Abonné de l'une des façons suivantes :Start the Distribution Agent at the Subscriber in one of the following ways:

Pour synchroniser un abonnement par extraction de données (pull) vers une publication de fusionTo synchronize a pull subscription to a merge publication

  1. Créez une connexion à l’abonné en utilisant la classe ServerConnection.Create a connection to the Subscriber by using the ServerConnection class.

  2. Créez une instance de la classe MergePullSubscription, puis définissez les propriétés suivantes :Create an instance of the MergePullSubscription class, and set the following properties:

  3. Appelez la méthode LoadProperties pour obtenir les propriétés d’abonnement restantes.Call the LoadProperties method to get the remaining subscription properties. Si cette méthode retourne false, vérifiez que l'abonnement existe.If this method returns false, verify that the subscription exists.

  4. Démarrez l'Agent de fusion sur l'Abonné de l'une des façons suivantes :Start the Merge Agent at the Subscriber in one of the following ways:

Exemples (RMO) Examples (RMO)

Cet exemple synchronise un abonnement par envoi de données (pull) vers une publication transactionnelle, où l'agent est démarré en mode asynchrone au moyen du travail d'agent.This example synchronizes a pull subscription to a transactional publication, where the agent is started asynchronously using the agent job.

// Define server, publication, and database names.  
String subscriberName = subscriberInstance;  
String publisherName = publisherInstance;  
String publicationName = "AdvWorksProductTran";  
String publicationDbName = "AdventureWorks";  
String subscriptionDbName = "AdventureWorksReplica";  

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

TransPullSubscription subscription;  

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

    // Define subscription properties.  
    subscription = new TransPullSubscription();  
    subscription.ConnectionContext = conn;  
    subscription.DatabaseName = subscriptionDbName;  
    subscription.PublisherName = publisherName;  
    subscription.PublicationDBName = publicationDbName;  
    subscription.PublicationName = publicationName;  

    // If the pull subscription and the job exists, start the agent job.  
    if (subscription.LoadProperties() && subscription.AgentJobId != null)  
    {  
        subscription.SynchronizeWithJob();  
    }  
    else  
    {  
        // Do something here if the subscription does not exist.  
        throw new ApplicationException(String.Format(  
            "A subscription to '{0}' does not exists on {1}",  
            publicationName, subscriberName));  
    }  
}  
catch (Exception ex)  
{  
    // Do appropriate error handling here.  
    throw new ApplicationException("The subscription could not be synchronized.", ex);  
}  
finally  
{  
    conn.Disconnect();  
}  
' Define server, publication, and database names.  
Dim subscriberName As String = subscriberInstance  
Dim publisherName As String = publisherInstance  
Dim publicationName As String = "AdvWorksProductTran"  
Dim publicationDbName As String = "AdventureWorks"  
Dim subscriptionDbName As String = "AdventureWorksReplica"  

' Create a connection to the Subscriber.  
Dim conn As ServerConnection = New ServerConnection(subscriberName)  

Dim subscription As TransPullSubscription  

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

    ' Define subscription properties.  
    subscription = New TransPullSubscription()  
    subscription.ConnectionContext = conn  
    subscription.DatabaseName = subscriptionDbName  
    subscription.PublisherName = publisherName  
    subscription.PublicationDBName = publicationDbName  
    subscription.PublicationName = publicationName  

    ' If the pull subscription and the job exists, start the agent job.  
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then  
        subscription.SynchronizeWithJob()  
    Else  
        ' Do something here if the subscription does not exist.  
        Throw New ApplicationException(String.Format( _  
         "A subscription to '{0}' does not exists on {1}", _  
         publicationName, subscriberName))  
    End If  
Catch ex As Exception  
    ' Do appropriate error handling here.  
    Throw New ApplicationException("The subscription could not be synchronized.", ex)  
Finally  
    conn.Disconnect()  
End Try  

Cet exemple synchronise un abonnement par envoi de données (pull) vers une publication transactionnelle, où l'agent est démarré en mode synchrone.This example synchronizes a pull subscription to a transactional publication, where the agent is started synchronously.

// Define the server, publication, and database names.  
string subscriberName = subscriberInstance;  
string publisherName = publisherInstance;  
string publicationName = "AdvWorksProductTran";  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  

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

TransPullSubscription subscription;  

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

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

    // If the pull subscription exists, then start the synchronization.  
    if (subscription.LoadProperties())  
    {  
        // Check that we have enough metadata to start the agent.  
        if (subscription.PublisherSecurity != null)  
        {  
            // Synchronously start the Distribution Agent for the subscription.  
            subscription.SynchronizationAgent.Synchronize();  
        }  
        else  
        {  
            throw new ApplicationException("There is insufficent metadata to " +  
                "synchronize the subscription. Recreate the subscription with " +  
                "the agent job or supply the required agent properties at run time.");  
        }  
    }  
    else  
    {  
        // Do something here if the pull subscription does not exist.  
        throw new ApplicationException(String.Format(  
            "A subscription to '{0}' does not exist on {1}",  
            publicationName, subscriberName));  
    }  
}  
catch (Exception ex)  
{  
    // Implement appropriate error handling here.  
    throw new ApplicationException("The subscription could not be " +  
        "synchronized. Verify that the subscription has " +  
        "been defined correctly.", ex);  
}  
finally  
{  
    conn.Disconnect();  
}  
' Define the server, publication, and database names.  
Dim subscriberName As String = subscriberInstance  
Dim publisherName As String = publisherInstance  
Dim publicationName As String = "AdvWorksProductTran"  
Dim subscriptionDbName As String = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  

' Create a connection to the Subscriber.  
Dim conn As ServerConnection = New ServerConnection(subscriberName)  

Dim subscription As TransPullSubscription  

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

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

    ' If the pull subscription exists, then start the synchronization.  
    If subscription.LoadProperties() Then  
        ' Check that we have enough metadata to start the agent.  
        If Not subscription.PublisherSecurity Is Nothing Then  

            ' Write agent output to a log file.  
            subscription.SynchronizationAgent.Output = "distagent.log"  
            subscription.SynchronizationAgent.OutputVerboseLevel = 2  

            ' Synchronously start the Distribution Agent for the subscription.  
            subscription.SynchronizationAgent.Synchronize()  
        Else  
            Throw New ApplicationException("There is insufficent metadata to " + _  
             "synchronize the subscription. Recreate the subscription with " + _  
             "the agent job or supply the required agent properties at run time.")  
        End If  
    Else  
        ' Do something here if the pull subscription does not exist.  
        Throw New ApplicationException(String.Format( _  
         "A subscription to '{0}' does not exist on {1}", _  
         publicationName, subscriberName))  
    End If  
Catch ex As Exception  
    ' Implement appropriate error handling here.  
    Throw New ApplicationException("The subscription could not be " + _  
     "synchronized. Verify that the subscription has " + _  
     "been defined correctly.", ex)  
Finally  
    conn.Disconnect()  
End Try  

Cet exemple synchronise un abonnement par envoi de données (pull) vers une publication de fusion, où l'agent est démarré en mode asynchrone au moyen du travail d'agent.This example synchronizes a pull subscription to a merge publication, where the agent is started asynchronously using the agent job.

// Define server, publication, and database names.  
String subscriberName = subscriberInstance;  
String publisherName = publisherInstance;  
String publicationName = "AdvWorksSalesOrdersMerge";  
String publicationDbName = "AdventureWorks";  
String subscriptionDbName = "AdventureWorksReplica";  

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

MergePullSubscription subscription;  

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

    // Define subscription properties.  
    subscription = new MergePullSubscription();  
    subscription.ConnectionContext = conn;  
    subscription.DatabaseName = subscriptionDbName;  
    subscription.PublisherName = publisherName;  
    subscription.PublicationDBName = publicationDbName;  
    subscription.PublicationName = publicationName;  

    // If the pull subscription and the job exists, start the agent job.  
    if (subscription.LoadProperties() && subscription.AgentJobId != null)  
    {  
        subscription.SynchronizeWithJob();  
    }  
    else  
    {  
        // Do something here if the subscription does not exist.  
        throw new ApplicationException(String.Format(  
            "A subscription to '{0}' does not exists on {1}",  
            publicationName, subscriberName));  
    }  
}  
catch (Exception ex)  
{  
    // Do appropriate error handling here.  
    throw new ApplicationException("The subscription could not be synchronized.", ex);  
}  
finally  
{  
    conn.Disconnect();  
}  
' Define server, publication, and database names.  
Dim subscriberName As String = subscriberInstance  
Dim publisherName As String = publisherInstance  
Dim publicationName As String = "AdvWorksSalesOrdersMerge"  
Dim publicationDbName As String = "AdventureWorks"  
Dim subscriptionDbName As String = "AdventureWorksReplica"  

' Create a connection to the Subscriber.  
Dim conn As ServerConnection = New ServerConnection(subscriberName)  

Dim subscription As MergePullSubscription  

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

    ' Define subscription properties.  
    subscription = New MergePullSubscription()  
    subscription.ConnectionContext = conn  
    subscription.DatabaseName = subscriptionDbName  
    subscription.PublisherName = publisherName  
    subscription.PublicationDBName = publicationDbName  
    subscription.PublicationName = publicationName  

    ' If the pull subscription and the job exists, start the agent job.  
    If subscription.LoadProperties() And Not subscription.AgentJobId Is Nothing Then  
        subscription.SynchronizeWithJob()  
    Else  
        ' Do something here if the subscription does not exist.  
        Throw New ApplicationException(String.Format( _  
         "A subscription to '{0}' does not exists on {1}", _  
         publicationName, subscriberName))  
    End If  
Catch ex As Exception  
    ' Do appropriate error handling here.  
    Throw New ApplicationException("The subscription could not be synchronized.", ex)  
Finally  
    conn.Disconnect()  
End Try  

Cet exemple synchronise un abonnement par envoi de données (pull) vers une publication de fusion, où l'agent est démarré en mode synchrone.This example synchronizes a pull subscription to a merge publication, where the agent is started synchronously.

// Define the server, publication, and database names.  
string subscriberName = subscriberInstance;  
string publisherName = publisherInstance;  
string publicationName = "AdvWorksSalesOrdersMerge";  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  

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

MergePullSubscription subscription;  

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

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

    // If the pull subscription exists, then start the synchronization.  
    if (subscription.LoadProperties())  
    {  
        // Check that we have enough metadata to start the agent.  
        if (subscription.PublisherSecurity != null || subscription.DistributorSecurity != null)  
        {  
            // Synchronously start the Merge Agent for the subscription.  
            subscription.SynchronizationAgent.Synchronize();  
        }  
        else  
        {  
            throw new ApplicationException("There is insufficent metadata to " +  
                "synchronize the subscription. Recreate the subscription with " +  
                "the agent job or supply the required agent properties at run time.");  
        }  
    }  
    else  
    {  
        // Do something here if the pull subscription does not exist.  
        throw new ApplicationException(String.Format(  
            "A subscription to '{0}' does not exist on {1}",  
            publicationName, subscriberName));  
    }  
}  
catch (Exception ex)  
{  
    // Implement appropriate error handling here.  
    throw new ApplicationException("The subscription could not be " +  
        "synchronized. Verify that the subscription has " +  
        "been defined correctly.", ex);  
}  
finally  
{  
    conn.Disconnect();  
}  
' Define the server, publication, and database names.  
Dim subscriberName As String = subscriberInstance  
Dim publisherName As String = publisherInstance  
Dim publicationName As String = "AdvWorksSalesOrdersMerge"  
Dim subscriptionDbName As String = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  

' Create a connection to the Subscriber.  
Dim conn As ServerConnection = New ServerConnection(subscriberName)  

Dim subscription As MergePullSubscription  

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

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

    ' If the pull subscription exists, then start the synchronization.  
    If subscription.LoadProperties() Then  
        ' Check that we have enough metadata to start the agent.  
        If Not subscription.PublisherSecurity Is Nothing Or subscription.DistributorSecurity Is Nothing Then  

            ' Output agent messages to the console.   
            subscription.SynchronizationAgent.OutputVerboseLevel = 1  
            subscription.SynchronizationAgent.Output = ""  

            ' Synchronously start the Merge Agent for the subscription.  
            subscription.SynchronizationAgent.Synchronize()  
        Else  
            Throw New ApplicationException("There is insufficent metadata to " + _  
             "synchronize the subscription. Recreate the subscription with " + _  
             "the agent job or supply the required agent properties at run time.")  
        End If  
    Else  
        ' Do something here if the pull subscription does not exist.  
        Throw New ApplicationException(String.Format( _  
         "A subscription to '{0}' does not exist on {1}", _  
         publicationName, subscriberName))  
    End If  
Catch ex As Exception  
    ' Implement appropriate error handling here.  
    Throw New ApplicationException("The subscription could not be " + _  
     "synchronized. Verify that the subscription has " + _  
     "been defined correctly.", ex)  
Finally  
    conn.Disconnect()  
End Try  

Cet exemple synchronise un abonnement par extraction de données (pull) vers une publication de fusion au moyen de la synchronisation web.This example synchronizes a pull subscription to a merge publication using Web synchronization. Dans la mesure où l'abonnement a été créé sans le travail d'agent et les métadonnées d'abonnement associées, l'agent doit être démarré en mode synchrone et des informations d'abonnement supplémentaires sont fournies.The subscription was created without the agent job and related subscription metadata, so the agent must be started synchronously and additional subscription information is supplied.

// Define the server, publication, and database names.  
string subscriberName = subscriberInstance;  
string publisherName = publisherInstance;  
string distributorName = distributorInstance;  
string publicationName = "AdvWorksSalesOrdersMerge";  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
string hostname = @"adventure-works\garrett1";  
string webSyncUrl = "https://" + publisherInstance + "/SalesOrders/replisapi.dll";  

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

MergePullSubscription subscription;  
MergeSynchronizationAgent agent;  

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

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

    // If the pull subscription exists, then start the synchronization.  
    if (subscription.LoadProperties())  
    {  
        // Get the agent for the subscription.  
        agent = subscription.SynchronizationAgent;  

        // Check that we have enough metadata to start the agent.  
        if (agent.PublisherSecurityMode == null)  
        {  
            // Set the required properties that could not be returned  
            // from the MSsubscription_properties table.   
            agent.PublisherSecurityMode = SecurityMode.Integrated;  
            agent.DistributorSecurityMode = SecurityMode.Integrated;  
            agent.Distributor = publisherName;  
            agent.HostName = hostname;  

            // Set optional Web synchronization properties.  
            agent.UseWebSynchronization = true;  
            agent.InternetUrl = webSyncUrl;  
            agent.InternetSecurityMode = SecurityMode.Standard;  
            agent.InternetLogin = winLogin;  
            agent.InternetPassword = winPassword;  
        }  
        // Enable agent output to the console.  
        agent.OutputVerboseLevel = 1;  
        agent.Output = "";  

        // Synchronously start the Merge Agent for the subscription.  
        agent.Synchronize();  
    }  
    else  
    {  
        // Do something here if the pull subscription does not exist.  
        throw new ApplicationException(String.Format(  
            "A subscription to '{0}' does not exist on {1}",  
            publicationName, subscriberName));  
    }  
}  
catch (Exception ex)  
{  
    // Implement appropriate error handling here.  
    throw new ApplicationException("The subscription could not be " +  
        "synchronized. Verify that the subscription has " +  
        "been defined correctly.", ex);  
}  
finally  
{  
    conn.Disconnect();  
}  
' Define the server, publication, and database names.  
Dim subscriberName As String = subscriberInstance  
Dim publisherName As String = publisherInstance  
Dim publicationName As String = "AdvWorksSalesOrdersMerge"  
Dim subscriptionDbName As String = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
Dim hostname As String = "adventure-works\garrett1"  
Dim webSyncUrl As String = "https://" + publisherInstance + "/SalesOrders/replisapi.dll"  

' Create a connection to the Subscriber.  
Dim conn As ServerConnection = New ServerConnection(subscriberName)  

Dim subscription As MergePullSubscription  
Dim agent As MergeSynchronizationAgent  

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

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

    ' If the pull subscription exists, then start the synchronization.  
    If subscription.LoadProperties() Then  
        ' Get the agent for the subscription.  
        agent = subscription.SynchronizationAgent  

        ' Check that we have enough metadata to start the agent.  
        If agent.PublisherSecurityMode = Nothing Then  
            ' Set the required properties that could not be returned  
            ' from the MSsubscription_properties table.   
            agent.PublisherSecurityMode = SecurityMode.Integrated  
            agent.Distributor = publisherInstance  
            agent.DistributorSecurityMode = SecurityMode.Integrated  
            agent.HostName = hostname  

            ' Set optional Web synchronization properties.  
            agent.UseWebSynchronization = True  
            agent.InternetUrl = webSyncUrl  
            agent.InternetSecurityMode = SecurityMode.Standard  
            agent.InternetLogin = winLogin  
            agent.InternetPassword = winPassword  
        End If  

        ' Enable agent logging to the console.  
        agent.OutputVerboseLevel = 1  
        agent.Output = ""  

        ' Synchronously start the Merge Agent for the subscription.  
        agent.Synchronize()  
    Else  
        ' Do something here if the pull subscription does not exist.  
        Throw New ApplicationException(String.Format( _  
         "A subscription to '{0}' does not exist on {1}", _  
         publicationName, subscriberName))  
    End If  
Catch ex As Exception  
    ' Implement appropriate error handling here.  
    Throw New ApplicationException("The subscription could not be " + _  
     "synchronized. Verify that the subscription has " + _  
     "been defined correctly.", ex)  
Finally  
    conn.Disconnect()  
End Try  

Voir aussiSee Also

Synchroniser les données Synchronize Data
Créer un abonnement par extraction Create a Pull Subscription
Replication Security Best Practices Replication Security Best Practices