Bagikan melalui


Membuat Langganan Pull

Berlaku untuk: SQL Server Azure SQL Managed Instance

Topik ini menjelaskan cara membuat langganan pull di SQL Server dengan menggunakan SQL Server Management Studio, Transact-SQL, atau Replication Management Objects (RMO).

Menyiapkan langganan pull untuk replikasi P2P dimungkinkan oleh skrip, tetapi tidak tersedia melalui wizard.

Menggunakan SQL Server Management Studio

Buat langganan penarikan di Penerbit atau Pelanggan menggunakan Wizard Langganan Baru. Ikuti halaman dalam wizard untuk:

  • Tentukan Penerbit dan publikasi.

  • Pilih tempat agen replikasi akan berjalan. Untuk langganan penarikan, pilih Jalankan setiap agen di Pelanggannya (tarik langganan) di halaman Lokasi Agen Distribusi atau halaman Gabungkan Lokasi Agen, tergantung pada jenis publikasi.

  • Tentukan Pelanggan dan database langganan.

  • Tentukan login dan kata sandi yang digunakan untuk koneksi yang dibuat oleh agen replikasi:

    • Agar langganan rekam jepret dan publikasi transaksional, tentukan kredensial di halaman Keamanan Agen Distribusi.

    • Agar langganan dapat menggabungkan publikasi, tentukan kredensial di halaman Gabungkan Keamanan Agen.

    Untuk informasi tentang izin yang diperlukan oleh setiap agen, lihat Model Keamanan Agen Replikasi.

  • Tentukan jadwal sinkronisasi dan kapan Pelanggan harus diinisialisasi.

  • Tentukan opsi tambahan untuk publikasi gabungan: jenis langganan; nilai untuk pemfilteran berparameter; dan informasi untuk sinkronisasi melalui HTTPS jika publikasi diaktifkan untuk sinkronisasi Web.

  • Tentukan opsi tambahan untuk publikasi transaksional yang memungkinkan pembaruan langganan: apakah Pelanggan harus segera melakukan perubahan di Penerbit atau menulisnya ke antrean; kredensial yang digunakan untuk menyambungkan dari Pelanggan ke Penerbit.

  • Secara opsional skrip langganan.

Untuk membuat langganan penarikan dari Publisher

  1. Sambungkan ke Publisher di Microsoft SQL Server Management Studio, lalu perluas simpul server.

  2. Perluas folder Replikasi, lalu perluas folder Publikasi Lokal.

  3. Klik kanan publikasi yang ingin Anda buatkan satu atau beberapa langganan, lalu klik Langganan Baru.

  4. Selesaikan halaman di Panduan Langganan Baru.

Untuk membuat langganan penarikan dari Pelanggan

  1. Sambungkan ke Pelanggan di SQL Server Management Studio, lalu perluas simpul server.

  2. Perluas folder Replikasi.

  3. Klik kanan folder Langganan Lokal, lalu klik Langganan Baru.

  4. Pada halaman Publikasi Wizard Langganan Baru, pilih <Temukan Penerbit> SQL Server atau <Temukan Penerbit> Oracle dari daftar drop-down Penerbit.

  5. Sambungkan ke Publisher dalam kotak dialog Sambungkan ke Server .

  6. Pilih publikasi di halaman Publikasi .

  7. Selesaikan halaman di Panduan Langganan Baru.

Menggunakan T-SQL

Langganan penarikan dapat dibuat secara terprogram menggunakan prosedur tersimpan replikasi. Prosedur tersimpan yang digunakan akan bergantung pada jenis publikasi tempat langganan berada.

Untuk membuat langganan penarikan ke rekam jepret atau publikasi transaksi

  1. Di Publisher, verifikasi bahwa publikasi mendukung langganan penarikan dengan menjalankan sp_helppublication (Transact-SQL).

    • Jika nilai allow_pull dalam tataan hasil adalah 1, maka publikasi mendukung langganan penarikan.

    • Jika nilai allow_pull adalah 0, jalankan sp_changepublication (Transact-SQL), menentukan allow_pull untuk @property dan true untuk @value.

  2. Di Pelanggan, jalankan sp_addpullsubscription (Transact-SQL). Tentukan @publisher dan @publication. Untuk informasi tentang memperbarui langganan, lihat Membuat Langganan yang Dapat Diperbarui ke Publikasi Transaksional.

  3. Di Pelanggan, jalankan sp_addpullsubscription_agent (Transact-SQL). Tentukan yang berikut ini:

    • Parameter @publisher, @publisher_db, dan @publication .

    • Kredensial Microsoft Windows tempat Agen Distribusi di Pelanggan berjalan untuk @job_login dan @job_password.

      Catatan

      Koneksi yang dibuat menggunakan Autentikasi Terintegrasi Windows selalu menggunakan kredensial Windows yang ditentukan oleh @job_login dan @job_password. Agen Distribusi selalu membuat koneksi lokal ke Pelanggan menggunakan Autentikasi Terintegrasi Windows. Secara default, agen akan terhubung ke Distributor menggunakan Autentikasi Terintegrasi Windows.

    • (Opsional) Nilai 0 untuk @distributor_security_mode dan informasi masuk SQL Server untuk @distributor_login dan @distributor_password, jika Anda perlu menggunakan Autentikasi SQL Server saat menyambungkan ke Distributor.

    • Jadwal untuk pekerjaan Agen Distribusi untuk langganan ini. Untuk informasi selengkapnya, lihat Menentukan Jadwal Sinkronisasi.

  4. Di Publisher, jalankan sp_addsubscription (Transact-SQL) untuk mendaftarkan langganan pull. Tentukan @publication, @subscriber, dan @destination_db. Tentukan nilai tarik untuk @subscription_type.

Untuk membuat langganan penarikan ke publikasi gabungan

  1. Di Publisher, verifikasi bahwa publikasi mendukung langganan penarikan dengan menjalankan sp_helpmergepublication (Transact-SQL).

    • Jika nilai allow_pull dalam tataan hasil adalah 1, maka publikasi mendukung langganan penarikan.

    • Jika nilai allow_pull adalah 0, jalankan sp_changemergepublication (Transact-SQL), tentukan allow_pull untuk @property dan true untuk @value.

  2. Di Pelanggan, jalankan sp_addmergepullsubscription (Transact-SQL). Tentukan @publisher, @publisher_db, @publication, dan parameter berikut:

    • @subscriber_type - tentukan lokal untuk langganan klien dan global untuk langganan server.

    • @subscription_priority - Tentukan prioritas untuk langganan (0,00 hingga 99,99). Ini hanya diperlukan untuk langganan server.

      Untuk informasi selengkapnya, lihat Deteksi dan Resolusi Konflik Replikasi Gabungan Tingkat Lanjut.

  3. Di Pelanggan, jalankan sp_addmergepullsubscription_agent (Transact-SQL). Tentukan parameter berikut:

    • @publisher, @publisher_db, dan @publication.

    • Kredensial Windows tempat Agen Penggabungan di Pelanggan berjalan untuk @job_login dan @job_password.

      Catatan

      Koneksi yang dibuat menggunakan Autentikasi Terintegrasi Windows selalu menggunakan kredensial Windows yang ditentukan oleh @job_login dan @job_password. Agen Penggabungan selalu membuat koneksi lokal ke Pelanggan menggunakan Autentikasi Terintegrasi Windows. Secara default, agen akan tersambung ke Distributor dan Penerbit menggunakan Autentikasi Terintegrasi Windows.

    • (Opsional) Nilai 0 untuk @distributor_security_mode dan informasi masuk SQL Server untuk @distributor_login dan @distributor_password, jika Anda perlu menggunakan Autentikasi SQL Server saat menyambungkan ke Distributor.

    • (Opsional) Nilai 0 untuk @publisher_security_mode dan informasi masuk SQL Server untuk @publisher_login dan @publisher_password, jika Anda perlu menggunakan Autentikasi SQL Server saat menyambungkan ke Penerbit.

    • Jadwal untuk pekerjaan Agen Penggabungan untuk langganan ini. Untuk informasi selengkapnya, lihat Membuat Langganan yang Dapat Diperbarui ke Publikasi Transaksi.

  4. Di Publisher, jalankan sp_addmergesubscription (Transact-SQL). Tentukan @publication, @subscriber, @subscriber_db, dan nilai tarik untuk @subscription_type. Ini mendaftarkan langganan penarikan.

Contoh (Transact-SQL)

Contoh berikut membuat langganan penarikan ke publikasi transaksi. Batch pertama dijalankan di Pelanggan, dan batch kedua dijalankan di Publisher. Nilai login dan kata sandi disediakan saat runtime menggunakan variabel pembuatan skrip sqlcmd.

-- 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  
  

Contoh berikut membuat langganan penarikan ke publikasi gabungan. Batch pertama dijalankan di Pelanggan, dan batch kedua dijalankan di Publisher. Nilai login dan kata sandi disediakan saat runtime menggunakan variabel pembuatan skrip sqlcmd .

-- 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  

Menggunakan Objek Manajemen Replikasi (RMO)

Kelas RMO yang digunakan untuk membuat langganan pull bergantung pada jenis publikasi tempat langganan berada.

Untuk membuat langganan penarikan ke rekam jepret atau publikasi transaksi

  1. Buat koneksi ke Pelanggan dan Penerbit dengan menggunakan ServerConnection Kelas .

  2. Buat instans TransPublication kelas dengan menggunakan koneksi Publisher dari langkah 1. Tentukan Name, DatabaseName dan ConnectionContext.

  3. Panggil LoadProperties metode. Jika metode ini mengembalikan false, properti yang ditentukan di langkah 2 salah atau publikasi tidak ada di server.

  4. Lakukan bitwise logis AND (& di Visual C# dan Dan di Visual Basic) antara Attributes properti dan AllowPull. Jika hasilnya adalah None, atur Attributes ke hasil bitwise logis OR (| di Visual C# dan Atau di Visual Basic) antara Attributes dan AllowPull. Kemudian, panggil CommitPropertyChanges untuk mengaktifkan langganan penarikan.

  5. Jika database langganan tidak ada, buat dengan menggunakan Database kelas . Untuk informasi selengkapnya, lihat Membuat, Mengubah, dan Menghapus Database.

  6. Membuat instans kelas TransPullSubscription.

  7. Atur properti langganan berikut ini:

  8. Panggil Create metode.

  9. Menggunakan instans TransPublication kelas dari langkah 2, panggil MakePullSubscriptionWellKnown metode untuk mendaftarkan langganan pull dengan Publisher. Jika pendaftaran ini sudah ada, pengecualian terjadi.

Untuk membuat langganan penarikan ke publikasi gabungan

  1. Buat koneksi ke Pelanggan dan Penerbit dengan menggunakan ServerConnection kelas .

  2. Buat instans MergePublication kelas dengan menggunakan koneksi Publisher dari langkah 1. Tentukan Name, DatabaseName, dan ConnectionContext.

  3. Panggil LoadProperties metode. Jika metode ini mengembalikan false, properti yang ditentukan di langkah 2 salah atau publikasi tidak ada di server.

  4. Lakukan bitwise logis AND (& di Visual C# dan Dan di Visual Basic) antara Attributes properti dan AllowPull. Jika hasilnya adalah None, atur Attributes ke hasil bitwise logis OR (| di Visual C# dan Atau di Visual Basic) antara Attributes dan AllowPull. Kemudian, panggil CommitPropertyChanges untuk mengaktifkan langganan penarikan.

  5. Jika database langganan tidak ada, buat dengan menggunakan Database kelas . Untuk informasi selengkapnya, lihat Membuat, Mengubah, dan Menghapus Database.

  6. Membuat instans kelas MergePullSubscription.

  7. Atur properti langganan berikut ini:

  8. Panggil Create metode.

  9. Menggunakan instans MergePublication kelas dari langkah 2, panggil MakePullSubscriptionWellKnown metode untuk mendaftarkan langganan pull dengan Publisher. Jika pendaftaran ini sudah ada, pengecualian terjadi.

Contoh (RMO)

Contoh ini membuat langganan penarikan ke publikasi transaksi. Kredensial akun Microsoft Windows yang digunakan untuk membuat pekerjaan Agen Distribusi diteruskan saat 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  
  

Contoh ini membuat langganan penarikan ke publikasi gabungan. Kredensial akun Windows yang digunakan untuk membuat pekerjaan Agen Penggabungan diteruskan saat 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  

Contoh ini membuat langganan penarikan ke publikasi gabungan tanpa membuat pekerjaan agen terkait dan metadata langganan di MSsubscription_properties. Kredensial akun Windows yang digunakan untuk membuat pekerjaan Agen Penggabungan diteruskan saat 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  

Contoh ini membuat langganan penarikan ke publikasi gabungan yang dapat disinkronkan melalui Internet menggunakan sinkronisasi Web. Kredensial akun Windows yang digunakan untuk membuat pekerjaan Agen Penggabungan diteruskan saat runtime. Untuk informasi selengkapnya, lihat Mengonfigurasi Sinkronisasi Web.

// 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  

Lihat Juga

Konsep Objek Manajemen Replikasi
Menampilkan dan Mengubah Properti Langganan Pull
Mengonfigurasi Sinkronisasi Web
Berlangganan Publikasi
Praktik Terbaik Keamanan Replikasi