Sincronizzazione di una sottoscrizione pullSynchronize a Pull Subscription

In questo argomento viene descritto come sincronizzare una sottoscrizione pull in SQL Server 2017SQL Server 2017 tramite SQL Server Management StudioSQL Server Management Studio, agenti di replicao RMO (Replication Management Objects).This topic describes how to synchronize a pull subscription in SQL Server 2017SQL Server 2017 by using SQL Server Management StudioSQL Server Management Studio, replication agents, or Replication Management Objects (RMO).

Contenuto dell'argomentoIn This Topic

Utilizzo di SQL Server Management Studio Using SQL Server Management Studio

Le sottoscrizioni vengono sincronizzate dall'agente di distribuzione, per la replica snapshot e transazionale, o dall'agente di merge, per la replica di tipo merge.Subscriptions are synchronized by the Distribution Agent (for snapshot and transactional replication) or the Merge Agent (for merge replication). Gli agenti possono essere in esecuzione continuamente, essere in esecuzione su richiesta o essere in esecuzione su una pianificazione.Agents can run continuously, run on demand, or run on a schedule. Per altre informazioni sull'impostazione delle pianificazioni della sincronizzazione, vedere Specificare le pianificazioni della sincronizzazione.For more information about specifying synchronization schedules, see Specify Synchronization Schedules.

Sincronizzare una sottoscrizione su richiesta dalla cartella Sottoscrizioni locali in 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.

Per sincronizzare una sottoscrizione pull su richiesta in Management StudioTo synchronize a pull subscription on demand in Management Studio

  1. Connettersi al Sottoscrittore in Management StudioManagement Studioe quindi espandere il nodo del server.Connect to the Subscriber in Management StudioManagement Studio, and then expand the server node.

  2. Espandere la cartella Replica e quindi la cartella Sottoscrizioni locali .Expand the Replication folder, and then expand the Local Subscriptions folder.

  3. Fare clic con il pulsante destro del mouse sulla sottoscrizione che si desidera sincronizzare e quindi scegliere Visualizza stato sincronizzazione.Right-click the subscription you want to synchronize, and then click View Synchronization Status.

  4. Nella finestra di dialogo Visualizza stato sincronizzazione - <Sottoscrittore>:<DatabaseSottoscrizione> fare clic su Avvia.In the View Synchronization Status - <Subscriber>:<SubscriptionDatabase> dialog box, click Start. Al termine della sincronizzazione verrà visualizzato il messaggio Sincronizzazione completata .When synchronization is complete, the message Synchronization completed is displayed.

  5. Scegliere Chiudi.Click Close.

Replication Agents Replication Agents

Le sottoscrizioni pull possono essere sincronizzate a livello di programmazione e su richiesta richiamando il file eseguibile dell'agente di replica appropriato dal prompt dei comandi.Pull subscriptions can be synchronized programmatically and on-demand by invoking the appropriate replication agent executable file from the command prompt. Il file eseguibile dell'agente di replica richiamato dipenderà dal tipo di pubblicazione a cui appartiene la sottoscrizione pull.The replication agent executable file that is invoked will depend on the type of publication to which the pull subscription belongs. Per altre informazioni, vedere Replication Agents.For more information, see Replication Agents.

Nota

Gli agenti di replica si connettono al server locale con le credenziali dell'autenticazione di Windows dell'utente che avvia l'agente dal prompt dei comandi.Replication agents connect to the local server using the Windows Authentication credentials of the user who started the agent from the command prompt. Tali credenziali di Windows vengono inoltre utilizzate per la connessione ai server remoti tramite l'autenticazione integrata di Windows.These Windows credentials are also used when connecting to remote servers using Windows Integrated Authentication.

Per avviare l'agente di distribuzione dal prompt dei comandi o da un file batchTo start the distribution agent from the command prompt or from a batch file

  1. Dal prompt dei comandi o in un file batch, avviare l' Agente distribuzione repliche eseguendo distrib.execon gli argomenti della riga di comando seguenti: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

      Se si utilizza l'autenticazione di SQL ServerSQL Server , è inoltre necessario specificare gli argomenti seguenti: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

Per avviare l'agente di merge dal prompt dei comandi o da un file batchTo start the merge agent from the command prompt or from a batch file

  1. Dal prompt dei comandi o in un file batch, avviare l' Agente merge repliche eseguendo replmerg.execon gli argomenti della riga di comando seguenti: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

      Se si utilizza l'autenticazione di SQL ServerSQL Server , è inoltre necessario specificare gli argomenti seguenti: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

Esempi (agenti di replica) Examples (Replication Agents)

Nell'esempio seguente viene avviato l'agente di distribuzione per sincronizzare una sottoscrizione pull.The following example starts the Distribution Agent to synchronize a pull subscription. Tutte le connessioni vengono eseguite con l'autenticazione di 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;  

Nell'esempio seguente viene avviato l'agente di merge per sincronizzare una sottoscrizione pull.The following example starts the Merge Agent to synchronize a pull subscription. Tutte le connessioni vengono eseguite con l'autenticazione di 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 ;  

Utilizzo di RMO (Replication Management Objects) Using Replication Management Objects (RMO)

È possibile sincronizzare le sottoscrizioni pull a livello di programmazione tramite gli oggetti RMO (Replication Management Objects) e l'accesso tramite codice gestito alle funzionalità dell'agente di replica.You can synchronize pull subscriptions programmatically by using Replication Management Objects (RMO) and managed code access to replication agent functionalities. Le classi utilizzate per la sincronizzazione di una sottoscrizione pull dipendono dal tipo di pubblicazione a cui appartiene la sottoscrizione.The classes you use to synchronize a pull subscription depend on the type of publication to which the subscription belongs.

Nota

Se si desidera avviare una sincronizzazione eseguita in modo autonomo senza effetti sull'applicazione, avviare l'agente in modo asincrono.If you want to start a synchronization that runs autonomously without affecting your application, start the agent asynchronously. Se invece si desidera monitorare i risultati della sincronizzazione e ricevere callback dall'agente durante il processo di sincronizzazione (ad esempio per la visualizzazione di una barra di stato) è necessario avviare l'agente in modo sincrono.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.

Per sincronizzare una sottoscrizione pull di una pubblicazione snapshot o transazionaleTo synchronize a pull subscription to a snapshot or transactional publication

  1. Creare una connessione al Sottoscrittore tramite la classe ServerConnection.Create a connection to the Subscriber by using the ServerConnection class.

  2. Creare un'istanza della classe TransPullSubscription e impostare le proprietà seguenti:Create an instance of the TransPullSubscription class, and set the following properties:

  3. Chiamare il metodo LoadProperties per recuperare le proprietà rimanenti della sottoscrizione.Call the LoadProperties method to get the remaining subscription properties. Se il metodo restituisce false, verificare che la sottoscrizione esista.If this method returns false, verify that the subscription exists.

  4. Avviare l'agente di distribuzione nel Sottoscrittore in uno dei modi seguenti:Start the Distribution Agent at the Subscriber in one of the following ways:

Per sincronizzare una sottoscrizione pull di una pubblicazione di tipo mergeTo synchronize a pull subscription to a merge publication

  1. Creare una connessione al Sottoscrittore tramite la classe ServerConnection.Create a connection to the Subscriber by using the ServerConnection class.

  2. Creare un'istanza della classe MergePullSubscription e impostare le proprietà seguenti:Create an instance of the MergePullSubscription class, and set the following properties:

  3. Chiamare il metodo LoadProperties per recuperare le proprietà rimanenti della sottoscrizione.Call the LoadProperties method to get the remaining subscription properties. Se il metodo restituisce false, verificare che la sottoscrizione esista.If this method returns false, verify that the subscription exists.

  4. Avviare l'agente di merge nel Sottoscrittore in uno dei modi seguenti:Start the Merge Agent at the Subscriber in one of the following ways:

Esempi (RMO) Examples (RMO)

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione transazionale, con avvio asincrono dell'agente utilizzando il processo dell'agente.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  

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione transazionale, con avvio sincrono dell'agente.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  

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge, con avvio asincrono dell'agente utilizzando il processo dell'agente.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  

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge, con avvio sincrono dell'agente.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  

In questo esempio viene illustrata la sincronizzazione di una sottoscrizione pull di una pubblicazione di tipo merge con la sincronizzazione tramite il Web.This example synchronizes a pull subscription to a merge publication using Web synchronization. La sottoscrizione è stata creata senza il processo dell'agente e i metadati correlati, pertanto l'agente deve essere avviato in modo sincrono e vengono fornite informazioni aggiuntive sulla sottoscrizione.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  

Vedere ancheSee Also

Sincronizzare i dati Synchronize Data
Creare una sottoscrizione pull Create a Pull Subscription
Replication Security Best Practices Replication Security Best Practices