Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
В этом разделе описывается, как синхронизировать пулловую подписку в SQL Server 2014 с помощью SQL Server Management Studio, агентов репликации или объектов управления репликацией (RMO).
Использование среды SQL Server Management Studio
Подписки синхронизируются агентом распространения (для снимка и транзакционной репликации) или агентом слияния (для репликации слиянием). Агенты могут работать непрерывно, запускаться по запросу или выполняться по расписанию. Дополнительные сведения об указании расписаний синхронизации см. в разделе "Указание расписаний синхронизации".
Синхронизация подписки по запросу из папки локальных подписок в SQL Server Management Studio.
Синхронизация подписки по запросу в Management Studio
Подключитесь к подписчику в Management Studio и разверните узел сервера.
Раскройте папку Репликация , а затем — папку Локальные подписки .
Щелкните правой кнопкой мыши подписку, которую требуется синхронизировать, и выберите пункт "Просмотреть состояние синхронизации".
В диалоговом окне "Просмотр состояния синхронизации - <Подписчик>:<SubscriptionDatabase>", нажмите кнопку "Запуск". После завершения синхронизации отображается сообщение Синхронизация завершена.
Нажмите кнопку Закрыть.
Агенты репликации
Подписки по запросу можно синхронизировать программным способом и по запросу, вызвав соответствующий исполняемый файл агента репликации из командной строки. Исполняемый файл агента репликации, который вызывается, будет зависеть от типа публикации, к которому принадлежит подписка на выборку. Дополнительные сведения см. в разделе "Агенты репликации".
Замечание
Агенты репликации подключаются к локальному серверу с помощью учетных данных проверки подлинности Windows пользователя, который запустил агент из командной строки. Эти учетные данные Windows также используются при подключении к удаленным серверам с помощью встроенной проверки подлинности Windows.
Запуск агента распространителя из командной строки или из пакетного файла
В командной строке или пакетном файле запустите агент распространителя репликации , выполнив distrib.exe, указав следующие аргументы командной строки:
-Издатель
-PublisherDB
-Распределитель
-DistributorSecurityMode = 1
-Абонент
-SubscriberDB
-SubscriberSecurityMode = 1
-SubscriptionType = 1
При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы:
-DistributorLogin
-Пароль дистрибьютора
-DistributorSecurityMode = 0
-PublisherLogin
-PublisherPassword
-PublisherSecurityMode = 0
-SubscriberLogin
-SubscriberPassword
-SubscriberSecurityMode = 0
Запуск агента слияния из командной строки или из пакетного файла
В командной строке или пакетном файле запустите агент слияния репликации , выполнив replmerg.exe, указав следующие аргументы командной строки:
-Издатель
-PublisherDB
-PublisherSecurityMode = 1
-Публикация
-Распределитель
-DistributorSecurityMode = 1
-Абонент
-SubscriberSecurityMode = 1
-SubscriberDB
-SubscriptionType = 1
При использовании проверки подлинности SQL Server необходимо также указать следующие аргументы:
-DistributorLogin
-Пароль дистрибьютора
-DistributorSecurityMode = 0
-PublisherLogin
-PublisherPassword
-PublisherSecurityMode = 0
-SubscriberLogin
-SubscriberPassword
-SubscriberSecurityMode = 0
Примеры (агенты репликации)
В следующем примере агент распределения запускается для синхронизации подписки на извлечение. Все подключения выполняются с помощью проверки подлинности Windows.
SET instancename=USERTEST2
REM<snippetbat_synctranpullsub_10>
REM -- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks2012
SET SubscriptionDB=AdventureWorks2012Replica
SET Publication=AdvWorksProductsTran
REM -- Start the Distribution Agent.
REM -- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\120\COM\DISTRIB.EXE" -Subscriber %Subscriber%
-SubscriberDB %SubscriptionDB% -SubscriberSecurityMode 1 -Publication %Publication%
-Publisher %Publisher% -PublisherDB %PublicationDB% -Distributor %Publisher%
-DistributorSecurityMode 1 -Continuous -SubscriptionType 1
REM</snippetbat_synctranpullsub_10>
PAUSE
В следующем примере агент слияния запускается для синхронизации подписки по запросу. Все подключения выполняются с помощью проверки подлинности Windows.
@ECHO OFF
SET instancename=USERTEST2
REM<snippetbat_syncmergepullsub_10>
REM -- Declare the variables.
SET Publisher=%instancename%
SET Subscriber=%instancename%
SET PublicationDB=AdventureWorks2012
SET SubscriptionDB=AdventureWorks2012Replica
SET Publication=AdvWorksSalesOrdersMerge
REM --Start the Merge Agent with concurrent upload and download processes.
REM -- The following command must be supplied without line breaks.
"C:\Program Files\Microsoft SQL Server\120\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
REM</snippetbat_syncmergepullsub_10>
PAUSE
Использование объектов управления репликацией (RMO)
Вы можете программно синхронизировать подписки pull, используя объекты управления репликацией (RMO) и доступ к функциям агента репликации в управляемом коде. Классы, которые используются для синхронизации подписки пул, зависят от типа публикации, к которой относится подписка.
Замечание
Если вы хотите запустить синхронизацию, которая выполняется автономно, не влияя на приложение, запустите агент асинхронно. Однако если вы хотите отслеживать результаты синхронизации и получать обратные вызовы от агента во время процесса синхронизации (например, для отображения индикатора выполнения), необходимо запустить агент синхронно. Для подписчиков MicrosoftSQL Server 2005 Express Edition необходимо запустить агент синхронно.
Синхронизация подписки по запросу с моментальным снимком или публикацией транзакций
Создайте подключение к подписчику ServerConnection с помощью класса.
Создайте экземпляр TransPullSubscription класса и задайте следующие свойства:
Имя базы данных подписки для DatabaseName.
Название публикации, к которой принадлежит подписка для PublicationName.
Название базы данных публикаций для PublicationDBName.
Имя издателя для PublisherName.
Соединение, созданное на шаге 1 для ConnectionContext.
LoadProperties Вызовите метод, чтобы получить оставшиеся свойства подписки. Если этот метод возвращается
false, убедитесь, что подписка существует.Запустите агент распространения на подписчике одним из этих способов:
Вызовите метод SynchronizeWithJob на экземпляре TransPullSubscription, как указано на шаге 2. Этот метод запускает агент распространителя асинхронно, а управление немедленно возвращается в приложение во время выполнения задания агента. Этот метод нельзя вызывать для подписчиков SQL Server 2005 Express Edition или если подписка была создана со значением
falseдля CreateSyncAgentByDefault (по умолчанию).Получите экземпляр TransSynchronizationAgent класса из SynchronizationAgent свойства и вызовите Synchronize метод. Этот метод запускает агент синхронно, а управление остается на работающем задании агента. Во время синхронного выполнения можно обрабатывать событие Status, пока агент работает.
Замечание
Если вы указали значение
falseдля CreateSyncAgentByDefault (по умолчанию) при создании подписки на вытягивание, необходимо также указать Distributor, DistributorSecurityMode и, при необходимости, DistributorLogin и DistributorPassword, поскольку метаданные, связанные с заданием агента для подписки, недоступны в MSsubscription_properties.
Для синхронизации подписки pull с публикацией по слиянию
Создайте подключение к подписчику ServerConnection с помощью класса.
Создайте экземпляр MergePullSubscription класса и задайте следующие свойства:
Имя базы данных подписки для DatabaseName.
Название публикации, к которой принадлежит подписка для PublicationName.
Имя опубликованной базы данных для PublicationDBName.
Имя издателя для PublisherName.
Соединение, созданное на шаге 1 для ConnectionContext.
LoadProperties Вызовите метод, чтобы получить оставшиеся свойства подписки. Если этот метод возвращается
false, убедитесь, что подписка существует.Запустите агент слияния на подписчике одним из способов, перечисленных ниже:
Вызовите метод SynchronizeWithJob на экземпляре MergePullSubscription, как указано на шаге 2. Этот метод запускает агент слияния асинхронно, и управление возвращается в ваше приложение немедленно во время выполнения задания агента. Этот метод нельзя вызывать для подписчиков SQL Server 2005 Express Edition или если подписка была создана со значением
falseдля CreateSyncAgentByDefault (по умолчанию).Получите экземпляр MergeSynchronizationAgent класса из SynchronizationAgent свойства и вызовите Synchronize метод. Этот метод запускает агент слияния синхронно, а управление остается у запущенного задания агента. Во время синхронного выполнения можно обрабатывать событие Status, пока агент работает.
Замечание
Если вы указали значение
falseдля CreateSyncAgentByDefault (по умолчанию) при создании подписки на вытягивание, необходимо также указать Distributor, DistributorSecurityMode, PublisherSecurityMode, HostName, SubscriptionType, ExchangeType, и при необходимости DistributorLogin, DistributorPassword, PublisherLogin и PublisherPassword, поскольку связанные с заданием агента метаданные для подписки недоступны в MSsubscription_properties.
Примеры (RMO)
В этом примере подписка на выборку синхронизируется с транзакционной публикацией, где агент запускается асинхронно через задание агента.
// Define server, publication, and database names.
String subscriberName = subscriberInstance;
String publisherName = publisherInstance;
String publicationName = "AdvWorksProductTran";
String publicationDbName = "AdventureWorks2012";
String subscriptionDbName = "AdventureWorks2012Replica";
// 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 = "AdventureWorks2012"
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
' 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
В этом примере подписка с вытягиванием синхронизируется с транзакционной публикацией, где агент запускается синхронно.
// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string publicationName = "AdvWorksProductTran";
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
// 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
' 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
В этом примере выполняется синхронизация подписки по запросу с публикацией слиянием, в которой агент запускается асинхронно с помощью задания агента.
// Define server, publication, and database names.
String subscriberName = subscriberInstance;
String publisherName = publisherInstance;
String publicationName = "AdvWorksSalesOrdersMerge";
String publicationDbName = "AdventureWorks2012";
String subscriptionDbName = "AdventureWorks2012Replica";
// 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 = "AdventureWorks2012"
Dim subscriptionDbName As String = "AdventureWorks2012Replica"
' 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
В этом примере выполняется синхронизация подписки по запросу с публикацией слиянием, в которой агент запускается синхронно.
// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
// 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
' 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
В этом примере вытягивающая подписка синхронизируется с публикацией слияния с помощью веб-синхронизации. Подписка была создана без задания агента и связанных метаданных подписки, поэтому агент должен быть запущен в синхронном режиме, и предоставляется дополнительная информация о подписке.
// Define the server, publication, and database names.
string subscriberName = subscriberInstance;
string publisherName = publisherInstance;
string distributorName = distributorInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string subscriptionDbName = "AdventureWorks2012Replica";
string publicationDbName = "AdventureWorks2012";
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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
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
См. также
Синхронизация данных
Создать выборочную подписку
Рекомендации по обеспечению безопасности репликации