Créer un abonnement par extraction de données (pull)Create a Pull Subscription

S’APPLIQUE À : ouiSQL Server ouiAzure SQL Database (Managed Instance uniquement) nonAzure SQL Data Warehouse nonParallel Data Warehouse APPLIES TO: yesSQL Server yesAzure SQL Database (Managed Instance only) noAzure SQL Data Warehouse noParallel Data Warehouse

Cette rubrique explique comment créer un abonnement par extraction de données (pull) dans SQL Server 2017SQL Server 2017 à l'aide de SQL Server Management StudioSQL Server Management Studio, de Transact-SQLTransact-SQLou d'objets RMO (Replication Management Objects).This topic describes how create a pull subscription in SQL Server 2017SQL Server 2017 by using SQL Server Management StudioSQL Server Management Studio, Transact-SQLTransact-SQL, or Replication Management Objects (RMO).

La définition d'un abonnement par extraction de données (pull) pour la réplication P2P est possible au moyen d'un script, mais n'est pas disponible via l'assistant.Setting up a pull subscription for P2P replication is possible by script, but is not available through the wizard.

Utilisation de SQL Server Management StudioUsing SQL Server Management Studio

Créer un abonnement par extraction de données sur le serveur de publication ou sur l'Abonné à l'aide de l'Assistant Nouvel abonnement.Create a pull subscription at the Publisher or the Subscriber using the New Subscription Wizard. Exécutez les étapes de l'Assistant pour :Follow the pages in the wizard to:

  • Spécifier le serveur de publication et la publication.Specify the Publisher and publication.

  • Sélectionner l'emplacement d'exécution des Agents de réplication.Select where replication agents will run. Pour un abonnement par extraction de données, sélectionnez Exécuter chaque Agent sur son Abonné (abonnements par extraction de données (pull)) dans la page Emplacement de l'Agent de distribution ou dans la page Emplacement de l'Agent de fusion , selon le type de publication.For a pull subscription, select Run each agent at its Subscriber (pull subscriptions) on the Distribution Agent Location page or Merge Agent Location page, depending on the type of publication.

  • Spécifiez des Abonnés et des bases de données d'abonnement.Specify Subscribers and subscription databases.

  • Spécifiez les noms de connexion et mots de passe utilisés pour les connexions établies par les Agents de réplication :Specify the logins and passwords used for connections made by replication agents:

    • Pour les abonnements aux publications d'instantané et transactionnelles, spécifiez les informations d'identification dans la page Sécurité de l'Agent de distribution .For subscriptions to snapshot and transactional publications, specify credentials on the Distribution Agent Security page.

    • Pour les abonnements aux publications de fusion, spécifiez les informations d'identification dans la page Sécurité de l'Agent de fusion .For subscriptions to merge publications, specify credentials on the Merge Agent Security page.

    Pour plus d’informations sur les autorisations requises par chaque agent, consultez Modèle de sécurité de l’Agent de réplication.For information about the permissions required by each agent, see Replication Agent Security Model.

  • Spécifiez une planification de la synchronisation et le moment choisi pour initialiser l'Abonné.Specify a synchronization schedule and when the Subscriber should be initialized.

  • Spécifiez les autres options pour les publications de fusion : type d'abonnement, valeurs pour le filtrage paramétré, informations pour la synchronisation via HTTPS si la publication est activée pour la synchronisation Web.Specify additional options for merge publications: subscription type; values for parameterized filtering; and information for synchronization through HTTPS if the publication is enabled for Web synchronization.

  • Spécifiez les autres options pour les publications transactionnelles qui autorisent la mise à jour des abonnements : si les Abonnés doivent valider immédiatement les modifications sur le serveur de publication ou les écrire dans une file d'attente ou encore les informations d'identification utilisées pour la connexion de l'Abonné au serveur de publication.Specify additional options for transactional publications that allow updating subscriptions: whether Subscribers should commit changes at the Publisher immediately or write them to a queue; credentials used to connect from the Subscriber to the Publisher.

  • Créez éventuellement un script pour l'abonnement.Optionally script the subscription.

Pour créer un abonnement par extraction de données à partir du serveur de publicationTo create a pull subscription from the Publisher

  1. Connectez-vous au serveur de publication dans MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio, puis développez le nœud du serveur.Connect to the Publisher in MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio, and then expand the server node.

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

  3. Cliquez avec le bouton droit sur la publication pour laquelle vous souhaitez créer un ou plusieurs abonnements puis cliquez sur Nouveaux abonnements.Right-click the publication for which you want to create one or more subscriptions, and then click New Subscriptions.

  4. Exécutez les étapes de l'Assistant Nouvel abonnement.Complete the pages in the New Subscription Wizard.

Nous sommes à votre écoute : Si vous trouvez des informations obsolètes ou incorrectes dans cet article, par exemple une étape ou une erreur dans un code, n’hésitez pas à nous en faire part.We are listening: If you find something outdated or incorrect in this article, such as a step or a code example, please tell us. Vous pouvez cliquer sur le bouton Cette page dans la section Commentaires au bas de cette page.You can click the This page button in the Feedback section at the bottom of this page. Nous lisons chaque commentaire concernant SQL, généralement le jour suivant.We read every item of feedback about SQL, typically the next day. Nous vous remercions.Thanks.

Pour créer un abonnement par extraction de données à partir de l'AbonnéTo create a pull subscription from the Subscriber

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

  2. Développez le dossier Réplication .Expand the Replication folder.

  3. Cliquez avec le bouton droit sur le dossier Abonnements locaux , puis cliquez sur Nouveaux abonnements.Right-click the Local Subscriptions folder, and then click New Subscriptions.

  4. Dans la page Publication de l’Assistant Nouvel abonnement, sélectionnez <Rechercher un serveur de publication SQL> ou <Rechercher un serveur de publication Oracle> dans la liste déroulante Serveur de publication.On the Publication page of the New Subscription Wizard, select <Find SQL Server Publisher> or <Find Oracle Publisher> from the Publisher drop-down list.

  5. Connectez-vous au serveur de publication dans la boîte de dialogue Se connecter au serveur .Connect to the Publisher in the Connect to Server dialog box.

  6. Sélectionnez une publication dans la page Publication .Select a publication on the Publication page.

  7. Exécutez les étapes de l'Assistant Nouvel abonnement.Complete the pages in the New Subscription Wizard.

Utilisation de Transact-SQLUsing Transact-SQL

Les abonnements par extraction de données peuvent être créés par programme en utilisant des procédures stockées de réplication.Pull subscriptions can be created programmatically using replication stored procedures. Les procédures stockées utilisées dépendent du type de publication auquel l'abonnement appartient.The stored procedures used will depend on the type of publication to which the subscription belongs.

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

  1. Sur le serveur de publication, vérifiez que la publication prend en charge les abonnements par extraction en exécutant sp_helppublication (Transact-SQL).At the Publisher, verify that the publication supports pull subscriptions by executing sp_helppublication (Transact-SQL).

    • Si la valeur de allow_pull dans le jeu de résultats est 1, la publication prend en charge les abonnements par extraction de données.If the value of allow_pull in the result set is 1, then the publication supports pull subscriptions.

    • Si la valeur de allow_pull est 0, exécutez sp_changepublication (Transact-SQL) en spécifiant allow_pull pour @property et true pour @value.If the value of allow_pull is 0, execute sp_changepublication (Transact-SQL), specifying allow_pull for @property and true for @value.

  2. Sur l’Abonné, exécutez sp_addpullsubscription (Transact-SQL).At the Subscriber, execute sp_addpullsubscription (Transact-SQL). Spécifiez @publisher et @publication.Specify @publisher and @publication. Pour plus d'informations sur la mise à jour des abonnements, consultez Créer un abonnement pouvant être mis à jour pour une publication transactionnelle.For information about updating subscriptions, see Create an Updatable Subscription to a Transactional Publication.

  3. Sur l’Abonné, exécutez sp_addpullsubscription_agent (Transact-SQL).At the Subscriber, execute sp_addpullsubscription_agent (Transact-SQL). Spécifiez les éléments suivants :Specify the following:

    • Les paramètres @publisher, @publisher_db et @publication.The @publisher, @publisher_db, and @publication parameters.

    • Les informations d’identification MicrosoftMicrosoft Windows sous lesquelles l’Agent de distribution est exécuté sur l’Abonné pour @job_login et @job_password.The MicrosoftMicrosoft Windows credentials under which the Distribution Agent at the Subscriber runs for @job_login and @job_password.

      Notes

      Les connexions effectuées à l’aide de l’authentification intégrée Windows utilisent toujours les informations d’identification Windows spécifiées par @job_login et @job_password.Connections made using Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. L'Agent de distribution établit toujours la connexion locale à l'Abonné à l'aide de l'authentification intégrée Windows.The Distribution Agent always makes the local connection to the Subscriber using Windows Integrated Authentication. Par défaut, l'Agent se connecte au serveur de distribution à l'aide de ces informations.By default, the agent will connect to the Distributor using Windows Integrated Authentication.

    • (Facultatif) La valeur 0 pour @distributor_security_mode et les informations de connexion SQL Server pour @distributor_login et @distributor_password, si vous devez utiliser l’authentification SQL Server lors de la connexion au serveur de distribution.(Optional) A value of 0 for @distributor_security_mode and the SQL Server login information for @distributor_login and @distributor_password, if you need to use SQL Server Authentication when connecting to the Distributor.

    • Planification du travail de l'Agent de distribution pour cet abonnement.A schedule for the Distribution Agent job for this subscription. Pour plus d’informations, consultez Spécifier des planifications de synchronisation.For more information, see Specify Synchronization Schedules.

  4. Sur le serveur de publication, exécutez sp_addsubscription (Transact-SQL) pour inscrire l’abonnement par extraction.At the Publisher, execute sp_addsubscription (Transact-SQL) to register the pull subscription. Spécifiez @publication, @subscriber et @destination_db.Specify @publication, @subscriber, and @destination_db. Affectez la valeur pull à @subscription_type.Specify a value of pull for @subscription_type.

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

  1. Sur le serveur de publication, vérifiez que la publication prend en charge les abonnements par extraction en exécutant sp_helpmergepublication (Transact-SQL).At the Publisher, verify that the publication supports pull subscriptions by executing sp_helpmergepublication (Transact-SQL).

    • Si la valeur de allow_pull dans le jeu de résultats est 1, la publication prend en charge les abonnements par extraction de données.If the value of allow_pull in the result set is 1, then the publication supports pull subscriptions.

    • Si la valeur de allow_pull est 0, exécutez sp_changemergepublication (Transact-SQL) en spécifiant allow_pull pour @property et true pour @value.If the value of allow_pull is 0, execute sp_changemergepublication (Transact-SQL), specifying allow_pull for @property and true for @value.

  2. Sur l’Abonné, exécutez sp_addmergepullsubscription (Transact-SQL).At the Subscriber, execute sp_addmergepullsubscription (Transact-SQL). Spécifiez @publisher, @publisher_db, @publication et les paramètres suivants :Specify @publisher, @publisher_db, @publication, and the following parameters:

    • @subscriber_type : spécifiez local pour un abonnement client et global pour un abonnement serveur.@subscriber_type – specify local for a client subscription and global for a server subscription.

    • @subscription_priority : spécifiez la priorité de l’abonnement (de 0,00 à 99,99).@subscription_priority – Specify a priority for the subscription (0.00 to 99.99). Ceci est requis uniquement pour un abonnement serveur.This is only required for a server subscription.

      Pour plus d’informations, consultez Détection et résolution avancées des conflits de réplication de fusion.For more information, see Advanced Merge Replication Conflict Detection and Resolution.

  3. Sur l’Abonné, exécutez sp_addmergepullsubscription_agent (Transact-SQL).At the Subscriber, execute sp_addmergepullsubscription_agent (Transact-SQL). Spécifiez les paramètres suivants :Specify the following parameters:

    • @publisher, @publisher_db et @publication.@publisher, @publisher_db, and @publication.

    • Informations d’identification Windows sous lesquelles l’Agent de fusion est exécuté sur l’Abonné pour @job_login et @job_password.The Windows credentials under which the Merge Agent at the Subscriber runs for @job_login and @job_password.

      Notes

      Les connexions effectuées à l’aide de l’authentification intégrée Windows utilisent toujours les informations d’identification Windows spécifiées par @job_login et @job_password.Connections made using Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. L'Agent de fusion crée toujours la connexion locale à l'abonné à l'aide de l'authentification intégrée Windows.The Merge Agent always makes the local connection to the Subscriber using Windows Integrated Authentication. Par défaut, l'Agent se connecte au serveur de distribution et au serveur de publication à l'aide de ces informations.By default, the agent will connect to the Distributor and Publisher using Windows Integrated Authentication.

    • (Facultatif) La valeur 0 pour @distributor_security_mode et les informations de connexion SQL ServerSQL Server pour @distributor_login et @distributor_password, si vous devez utiliser l’authentification SQL ServerSQL Server lors de la connexion au serveur de distribution.(Optional) A value of 0 for @distributor_security_mode and the SQL ServerSQL Server login information for @distributor_login and @distributor_password, if you need to use SQL ServerSQL Server Authentication when connecting to the Distributor.

    • (Facultatif) La valeur 0 pour @publisher_security_mode et les informations de connexion SQL ServerSQL Server pour @publisher_login et @publisher_password si vous devez utiliser l’authentification SQL ServerSQL Server lors de la connexion au serveur de publication.(Optional) A value of 0 for @publisher_security_mode and the SQL ServerSQL Server login information for @publisher_login and @publisher_password, if you need to use SQL ServerSQL Server Authentication when connecting to the Publisher.

    • Une planification du travail de l'Agent de fusion pour cet abonnement.A schedule for the Merge Agent job for this subscription. Pour plus d'informations, voir Créer un abonnement pouvant être mis à jour pour une publication transactionnelle.For more information, see Create an Updatable Subscription to a Transactional Publication.

  4. Sur le serveur de publication, exécutez sp_addmergesubscription (Transact-SQL).At the Publisher, execute sp_addmergesubscription (Transact-SQL). Spécifiez @publication, @subscriber, @subscriber_db et la valeur pull pour @subscription_type.Specify @publication, @subscriber, @subscriber_db, and a value of pull for @subscription_type. L'abonnement par extraction est inscrit.This registers the pull subscription.

Exemples (Transact-SQL)Examples (Transact-SQL)

L'exemple suivant crée un abonnement par extraction de données vers une publication transactionnelle.The following example creates a pull subscription to a transactional publication. Le premier traitement est exécuté sur l'abonné, et le second sur le serveur de publication.The first batch is executed at the Subscriber, and the second batch is executed at the Publisher. Les valeurs de connexion et le mot de passe sont fournis lors de l'exécution à l'aide des variables de script sqlcmd.Login and password values are supplied at runtime using sqlcmd scripting variables.

-- This script uses sqlcmd scripting variables. They are in the form  
-- $(MyVariable). For information about how to use scripting variables    
-- on the command line and in SQL Server Management Studio, see the   
-- "Executing Replication Scripts" section in the topic  
-- "Programming Replication Using System Stored Procedures".  
  
-- 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'AdventureWorks';  
  
-- At the subscription database, create a pull subscription   
-- to a transactional publication.  
USE [AdventureWorksReplica]  
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'AdventureWorksReplica';  
  
-- 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  
  

L'exemple suivant crée un abonnement par extraction de données vers une publication de fusion.The following example creates a pull subscription to a merge publication. Le premier traitement est exécuté sur l'abonné, et le second sur le serveur de publication.The first batch is executed at the Subscriber, and the second batch is executed at the Publisher. Les valeurs de connexion et le mot de passe sont fournis lors de l'exécution à l'aide des variables de script sqlcmd .Login and password values are supplied at runtime using sqlcmd scripting variables.

-- This script uses sqlcmd scripting variables. They are in the form  
-- $(MyVariable). For information about how to use scripting variables    
-- on the command line and in SQL Server Management Studio, see the   
-- "Executing Replication Scripts" section in the topic  
-- "Programming Replication Using System Stored Procedures".  
  
-- 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'AdventureWorks';  
SET @hostname = N'adventure-works\david8';  
  
-- At the subscription database, create a pull subscription   
-- to a merge publication.  
USE [AdventureWorksReplica]  
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'AdventureWorksReplica';  
  
-- At the Publisher, register the subscription, using the defaults.  
USE [AdventureWorks]  
EXEC sp_addmergesubscription @publication = @myMergePub,   
@subscriber = @mySub, @subscriber_db = @mySubDB,   
@subscription_type = N'pull';  
GO  

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

Les classes RMO utilisées pour créer un abonnement par extraction de données (pull) sont fonction du type de publication à laquelle l'abonnement appartient.The RMO classes used to create a pull subscription depend on the type of publication to which the subscription belongs.

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

  1. Créez une connexion à l'Abonné et au serveur de publication à l'aide de la classe ServerConnection .Create connections to both the Subscriber and Publisher by using the ServerConnection Class.

  2. Créez une instance de la classe TransPublication en utilisant la connexion au serveur de publication de l'étape 1.Create an instance of the TransPublication class by using the Publisher connection from step 1. Spécifiez Name, DatabaseName et ConnectionContext.Specify Name, DatabaseName and ConnectionContext.

  3. Appelez la méthode LoadProperties .Call the LoadProperties method. Si cette méthode retourne false, les propriétés spécifiées à l'étape 2 sont incorrectes ou la publication n'existe pas sur le serveur.If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Effectuez une opération AND logique au niveau du bit ( & dans Visual C# et And dans Visual Basic) entre la propriété Attributes et AllowPull.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. Si le résultat est None, appliquez à Attributes le résultat d'une opération OR logique au niveau du bit ( | dans Visual C# et Or dans Visual Basic) entre Attributes et AllowPull.If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. Ensuite, appelez CommitPropertyChanges pour activer les abonnements par extraction de données (pull).Then, call CommitPropertyChanges to enable pull subscriptions.

  5. Si la base de données d'abonnements n'existe pas, créez-la en utilisant la classe Database .If the subscription database does not exist, create it by using the Database class. Pour plus d’informations, consultez Création, modification et suppression de bases de données.For more information, see Creating, Altering, and Removing Databases.

  6. Créez une instance de la classe TransPullSubscription .Create an instance of the TransPullSubscription class.

  7. Définissez les propriétés suivantes des abonnements :Set the following subscription properties:

  8. Appelez la méthode Create .Call the Create method.

  9. Au moyen de l'instance de la classe TransPublication de l'étape 2, appelez la méthode MakePullSubscriptionWellKnown pour inscrire l'abonnement par extraction de données (pull) sur le serveur de publication.Using the instance of the TransPublication class from step 2, call the MakePullSubscriptionWellKnown method to register the pull subscription with the Publisher. Si l'abonnement est déjà inscrit dans le Registre, une erreur se produit.If this registration already exists, an exception occurs.

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

  1. Créez des connexions à la fois à l'Abonné et au serveur de publication au moyen de la classe ServerConnection .Create connections to both the Subscriber and Publisher by using the ServerConnection class.

  2. Créez une instance de la classe MergePublication en utilisant la connexion au serveur de publication de l'étape 1.Create an instance of the MergePublication class by using the Publisher connection from step 1. Spécifiez Name, DatabaseNameet ConnectionContext.Specify Name, DatabaseName, and ConnectionContext.

  3. Appelez la méthode LoadProperties .Call the LoadProperties method. Si cette méthode retourne false, les propriétés spécifiées à l'étape 2 sont incorrectes ou la publication n'existe pas sur le serveur.If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Effectuez une opération AND logique au niveau du bit ( & dans Visual C# et And dans Visual Basic) entre la propriété Attributes et AllowPull.Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. Si le résultat est None, appliquez à Attributes le résultat d'une opération OR logique au niveau du bit ( | dans Visual C# et Or dans Visual Basic) entre Attributes et AllowPull.If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. Ensuite, appelez CommitPropertyChanges pour activer les abonnements par extraction de données (pull).Then, call CommitPropertyChanges to enable pull subscriptions.

  5. Si la base de données d'abonnements n'existe pas, créez-la en utilisant la classe Database .If the subscription database does not exist, create it by using the Database class. Pour plus d’informations, consultez Création, modification et suppression de bases de données.For more information, see Creating, Altering, and Removing Databases.

  6. Créez une instance de la classe MergePullSubscription .Create an instance of the MergePullSubscription class.

  7. Définissez les propriétés suivantes des abonnements :Set the following subscription properties:

  8. Appelez la méthode Create .Call the Create method.

  9. Au moyen de l'instance de la classe MergePublication de l'étape 2, appelez la méthode MakePullSubscriptionWellKnown pour inscrire l'abonnement par extraction de données (pull) sur le serveur de publication.Using the instance of the MergePublication class from step 2, call the MakePullSubscriptionWellKnown method to register the pull subscription with the Publisher. Si l'abonnement est déjà inscrit dans le Registre, une erreur se produit.If this registration already exists, an exception occurs.

Exemple (RMO)Example (RMO)

Cet exemple crée un abonnement par extraction de données (pull) vers une publication transactionnelle.This example creates a pull subscription to a transactional publication. Les informations d'identification de compte MicrosoftMicrosoft utilisées pour créer le travail d'agent de distribution sont transmises au moment de l'exécution.The MicrosoftMicrosoft Windows account credentials used to create the Distribution Agent job are passed at runtime.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksProductTran";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
  
//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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
  
'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  
  

Cet exemple crée un abonnement par extraction de données (pull) vers une publication de fusion.This example creates a pull subscription to a merge publication. Les informations d'identification de compte Windows utilisées pour créer le travail d'agent de fusion sont transmises au moment de l'exécution.The Windows account credentials used to create the Merge Agent job are passed at runtime.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksSalesOrdersMerge";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
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  

Cet exemple crée un abonnement par extraction de données (pull) vers une publication de fusion sans créer de travail d'agent et de métadonnées d'abonnement associés dans MSsubscription_properties.This example creates a pull subscription to a merge publication without creating an associated agent job and subscription metadata in MSsubscription_properties. Les informations d'identification de compte Windows utilisées pour créer le travail d'agent de fusion sont transmises au moment de l'exécution.The Windows account credentials used to create the Merge Agent job are passed at runtime.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksSalesOrdersMerge";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
  
//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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
  
'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  

Cet exemple crée un abonnement par envoi de données (pull) vers une publication de fusion qui peut être synchronisée via Internet au moyen de la synchronisation Web.This example creates a pull subscription to a merge publication that can be synchronized over the Internet using Web synchronization. Les informations d'identification de compte Windows utilisées pour créer le travail d'agent de fusion sont transmises au moment de l'exécution.The Windows account credentials used to create the Merge Agent job are passed at runtime. Pour plus d'informations, voir Configurer la synchronisation web.For more information, see Configure Web Synchronization.

// Define the Publisher, publication, and databases.  
string publicationName = "AdvWorksSalesOrdersMerge";  
string publisherName = publisherInstance;  
string subscriberName = subscriberInstance;  
string subscriptionDbName = "AdventureWorksReplica";  
string publicationDbName = "AdventureWorks";  
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 = "AdventureWorksReplica"  
Dim publicationDbName As String = "AdventureWorks"  
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  

Voir aussiSee Also

Concepts liés à RMO (Replication Management Objects) Replication Management Objects Concepts
Afficher et modifier les propriétés d’un abonnement par extraction View and Modify Pull Subscription Properties
Configurer la synchronisation web Configure Web Synchronization
S’abonner aux Publications Subscribe to Publications
Bonnes pratiques en matière de sécurité de la réplicationReplication Security Best Practices