Redaguoti

Bendrinti naudojant


Create a push subscription

Applies to: SQL Server Azure SQL Database

This topic describes how to create a push subscription in SQL Server by using SQL Server Management Studio, Transact-SQL, or Replication Management Objects (RMO). For information about creating a push subscription for a non- SQL Server Subscriber, see Create a subscription for a non-SQL Server Subscriber.

Note

Azure SQL Managed Instance can be a publisher, distributor, and subscriber for snapshot and transactional replication. Databases in Azure SQL Database can only be push subscribers for snapshot and transactional replication. For more information, see Transactional replication with Azure SQL Database and Azure SQL Managed Instance.

Using SQL Server Management Studio

Create a push subscription at the Publisher or the Subscriber by using the New Subscription Wizard. Follow the pages in the wizard to:

  • Specify the Publisher and publication.

  • Select where replication agents will run. For a push subscription, select Run all agents at the Distributor (push subscriptions) on the Distribution Agent Location page or Merge Agent Location page, depending on the type of publication.

  • Specify Subscribers and subscription databases.

  • Specify the logins and passwords used for connections made by replication agents:

    • For subscriptions to snapshot and transactional publications, specify credentials on the Distribution Agent Security page.

    • For subscriptions to merge publications, specify credentials on the Merge Agent Security page.

      For information about the permissions that each agent requires, see Replication agent security model.

  • Specify a synchronization schedule and when the Subscriber should be initialized.

  • Specify additional options for merge publications: subscription type and values for parameterized filtering.

  • Specify additional options for transactional publications that allow updating subscriptions. One option is to decide whether Subscribers should commit changes at the Publisher immediately or write them to a queue. Another option is setting up credentials used to connect from the Subscriber to the Publisher.

  • Optionally, script the subscription.

To create a push subscription from the Publisher

  1. Connect to the Publisher in Microsoft SQL Server Management Studio, and then expand the server node.

  2. Expand the Replication folder, and then expand the Local Publications folder.

  3. Right-click the publication for which you want to create one or more subscriptions, and then select New Subscriptions.

  4. Complete the pages in the New Subscription Wizard.

To create a push subscription from the Subscriber

  1. Connect to the Subscriber in SQL Server Management Studio, and then expand the server node.

  2. Expand the Replication folder.

  3. Right-click the Local Subscriptions folder, and then select New Subscriptions.

  4. On the Publication page of the New Subscription Wizard, select <Find SQL Server Publisher> or <Find Oracle Publisher> from the Publisher drop-down list.

  5. Connect to the Publisher in the Connect to Server dialog box.

  6. Select a publication on the Publication page.

  7. Complete the pages in the New Subscription Wizard.

Using Transact-SQL

You can create push subscriptions programmatically by using replication stored procedures. The stored procedures used will depend on the type of publication to which the subscription belongs.

Important

When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

To create a push subscription to a snapshot or transactional publication

  1. At the Publisher on the publication database, verify that the publication supports push subscriptions by running sp_helppublication.

    • If the value of allow_push is 1, push subscriptions are supported.

    • If the value of allow_push is 0, run sp_changepublication. Specify allow_push for @property and true for @value.

  2. At the Publisher on the publication database, run sp_addsubscription. Specify @publication, @subscriber, and @destination_db. Specify a value of push for @subscription_type. For information about how to update subscriptions, see Create an updatable subscription to a transactional publication.

  3. At the Publisher on the publication database, run sp_addpushsubscription_agent. Specify the following:

    • The @subscriber, @subscriber_db, and @publication parameters.

    • The Microsoft Windows credentials under which the Distribution Agent at the Distributor runs for @job_login and @job_password.

      Note

      Connections made through Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. The Distribution Agent always makes the local connection to the Distributor by using Windows Integrated Authentication. By default, the agent will connect to the Subscriber by using Windows Integrated Authentication.

    • (Optional) A value of 0 for @subscriber_security_mode and the Microsoft SQL Server login information for @subscriber_login and @subscriber_password. Specify these parameters if you need to use SQL Server Authentication when connecting to the Subscriber.

    • A schedule for the Distribution Agent job for this subscription. For more information, see Specify synchronization schedules.

Important

When you're creating a push subscription at a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its remote Distributor before running this stored procedure. For more information, see Enable encrypted connections to the database engine (SQL Server Configuration Manager).

To create a push subscription to a merge publication

  1. At the Publisher on the publication database, verify that the publication supports push subscriptions by running sp_helpmergepublication.

    • If the value of allow_push is 1, the publication supports push subscriptions.

    • If the value of allow_push is not 1, run sp_changemergepublication. Specify allow_push for @property and true for @value.

  2. At the Publisher on the publication database, run sp_addmergesubscription. Specify the following parameters:

    • @publication. This is the name of the publication.

    • @subscriber_type. For a client subscription, specify local. For a server subscription, specify global.

    • @subscription_priority. For a server subscription, specify a priority for the subscription (0.00 to 99.99).

    For more information, see Advanced merge replication conflict detection and resolution.

  3. At the Publisher on the publication database, run sp_addmergepushsubscription_agent. Specify the following:

    • The @subscriber, @subscriber_db, and @publication parameters.

    • The Windows credentials under which the Merge Agent at the Distributor runs for @job_login and @job_password.

      Note

      Connections made through Windows Integrated Authentication always use the Windows credentials specified by @job_login and @job_password. The Merge Agent always makes the local connection to the Distributor by using Windows Integrated Authentication. By default, the agent will connect to the Subscriber by using Windows Integrated Authentication.

    • (Optional) A value of 0 for @subscriber_security_mode and the SQL Server login information for @subscriber_login and @subscriber_password. Specify these parameters if you need to use SQL Server Authentication when connecting to the Subscriber.

    • (Optional) A value of 0 for @publisher_security_mode and the SQL Server login information for @publisher_login and @publisher_password. Specify these values if you need to use SQL Server Authentication when connecting to the Publisher.

    • A schedule for the Merge Agent job for this subscription. For more information, see Specify synchronization schedules.

Important

When you're creating a push subscription at a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its remote Distributor before running this stored procedure. For more information, see Enable encrypted connections to the database engine (SQL Server Configuration Manager).

Examples (Transact-SQL)

The following example creates a push subscription to a transactional publication. Login and password values are supplied at runtime through sqlcmd scripting variables.

-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables  
-- on the command line and in SQL Server Management Studio, see the 
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2022Replica';

--Add a push subscription to a transactional publication.
USE [AdventureWorks2022]
EXEC sp_addsubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @destination_db = @subscriptionDB, 
  @subscription_type = N'push';

--Add an agent job to synchronize the push subscription.
EXEC sp_addpushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO

The following example creates a push subscription to a merge publication. Login and password values are supplied at runtime through sqlcmd scripting variables.

-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables  
-- on the command line and in SQL Server Management Studio, see the 
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorksReplica'; 
SET @hostname = N'adventure-works\david8'

-- Add a push subscription to a merge publication.
USE [AdventureWorks2022];
EXEC sp_addmergesubscription 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @subscription_type = N'push',
  @hostname = @hostname;

--Add an agent job to synchronize the push subscription.
EXEC sp_addmergepushsubscription_agent 
  @publication = @publication, 
  @subscriber = @subscriber, 
  @subscriber_db = @subscriptionDB, 
  @job_login = $(Login), 
  @job_password = $(Password);
GO

Using Replication Management Objects

You can create push subscriptions programmatically by using Replication Management Objects (RMO). The RMO classes that you use to create a push subscription depend on the type of publication to which the subscription is created.

Important

When possible, prompt users to enter security credentials at runtime. If you must store credentials, use the cryptographic services that the Microsoft Windows .NET Framework provides.

To create a push subscription to a snapshot or transactional publication

  1. Create a connection to the Publisher by using the ServerConnection class.

  2. Create an instance of the TransPublication class by using the Publisher connection from step 1. Specify Name, DatabaseName, and ConnectionContext.

  3. Call the LoadProperties method. If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPush. Then, call CommitPropertyChanges to enable push subscriptions.

  5. If the subscription database does not exist, create it by using the Database class. For more information, see Creating, altering, and removing databases.

  6. Create an instance of the TransSubscription class.

  7. Set the following subscription properties:

  8. Call the Create method.

Important

When you're creating a push subscription at a Publisher with a remote Distributor, the values supplied for all properties, including SynchronizationAgentProcessSecurity, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its remote Distributor before calling the Create method. For more information, see Enable encrypted connections to the database engine (SQL Server Configuration Manager).

To create a push subscription to a merge publication

  1. Create a connection to the Publisher by using the ServerConnection class.

  2. Create an instance of the MergePublication class by using the Publisher connection from step 1. Specify Name, DatabaseName, and ConnectionContext.

  3. Call the LoadProperties method. If this method returns false, either the properties specified in step 2 are incorrect or the publication does not exist on the server.

  4. Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPush. Then, call CommitPropertyChanges to enable push subscriptions.

  5. If the subscription database does not exist, create it by using the Database class. For more information, see Creating, altering, and removing databases.

  6. Create an instance of the MergeSubscription class.

  7. Set the following subscription properties:

  8. Call the Create method.

Important

When you're creating a push subscription at a Publisher with a remote Distributor, the values supplied for all properties, including SynchronizationAgentProcessSecurity, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its remote Distributor before calling the Create method. For more information, see Enable encrypted connections to the database engine (SQL Server Configuration Manager).

Examples (RMO)

This example creates a new push subscription to a transactional publication. The Windows account credentials that you use to run the Distribution Agent job are passed at runtime.

           // Define the Publisher, publication, and databases.
           string publicationName = "AdvWorksProductTran";
           string publisherName = publisherInstance;
           string subscriberName = subscriberInstance;
           string subscriptionDbName = "AdventureWorks2022Replica";
           string publicationDbName = "AdventureWorks2022";

           //Create a connection to the Publisher.
           ServerConnection conn = new ServerConnection(publisherName);

           // Create the objects that we need.
           TransPublication publication;
           TransSubscription subscription;

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

               // Ensure that the publication exists and that 
               // it supports push subscriptions.
               publication = new TransPublication();
               publication.Name = publicationName;
               publication.DatabaseName = publicationDbName;
               publication.ConnectionContext = conn;

               if (publication.IsExistingObject)
               {
                   if ((publication.Attributes & PublicationAttributes.AllowPush) == 0)
                   {
                       publication.Attributes |= PublicationAttributes.AllowPush;
                   }

                   // Define the push subscription.
                   subscription = new TransSubscription();
                   subscription.ConnectionContext = conn;
                   subscription.SubscriberName = subscriberName;
                   subscription.PublicationName = publicationName;
                   subscription.DatabaseName = publicationDbName;
                   subscription.SubscriptionDBName = subscriptionDbName;

                   // Specify the Windows login credentials for the Distribution Agent job.
                   subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
                   subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

                   // 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 push subscription.
                   subscription.Create();
               }
               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
           {
               conn.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 = "AdventureWorks2022Replica"
Dim publicationDbName As String = "AdventureWorks2022"

'Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As TransPublication
Dim subscription As TransSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports push subscriptions.
    publication = New TransPublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = conn

    If publication.IsExistingObject Then
        If (publication.Attributes And PublicationAttributes.AllowPush) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPush
        End If

        ' Define the push subscription.
        subscription = New TransSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName

        ' Specify the Windows login credentials for the Distribution Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' 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 push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try

This example creates a new push subscription to a merge publication. The Windows account credentials that you use to run the Merge Agent job are passed at runtime.

// Define the Publisher, publication, and databases.
string publicationName = "AdvWorksSalesOrdersMerge";
string publisherName = publisherInstance;
string subscriberName = subscriberInstance;
string subscriptionDbName = "AdventureWorks2022Replica";
string publicationDbName = "AdventureWorks2022";
string hostname = @"adventure-works\garrett1";

//Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);

// Create the objects that we need.
MergePublication publication;
MergeSubscription subscription;

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

    // Ensure that the publication exists and that 
    // it supports push subscriptions.
    publication = new MergePublication();
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;
    publication.ConnectionContext = conn;

    if (publication.IsExistingObject)
    {
        if ((publication.Attributes & PublicationAttributes.AllowPush) == 0)
        {
            publication.Attributes |= PublicationAttributes.AllowPush;
        }

        // Define the push subscription.
        subscription = new MergeSubscription();
        subscription.ConnectionContext = conn;
        subscription.SubscriberName = subscriberName;
        subscription.PublicationName = publicationName;
        subscription.DatabaseName = publicationDbName;
        subscription.SubscriptionDBName = subscriptionDbName;
        subscription.HostName = hostname;

        // Set a schedule to synchronize the subscription every 2 hours
        // during weekdays from 6am to 10pm.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly;
        subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32(0x003E);
        subscription.AgentSchedule.FrequencyRecurrenceFactor = 1;
        subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour;
        subscription.AgentSchedule.FrequencySubDayInterval = 2;
        subscription.AgentSchedule.ActiveStartDate = 20051108;
        subscription.AgentSchedule.ActiveEndDate = 20071231;
        subscription.AgentSchedule.ActiveStartTime = 060000;
        subscription.AgentSchedule.ActiveEndTime = 100000;

        // Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin;
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword;

        // Create the push subscription.
        subscription.Create();
    }
    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
{
    conn.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 = "AdventureWorks2022Replica"
Dim publicationDbName As String = "AdventureWorks2022"
Dim hostname As String = "adventure-works\garrett1"

'Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

' Create the objects that we need.
Dim publication As MergePublication
Dim subscription As MergeSubscription

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

    ' Ensure that the publication exists and that 
    ' it supports push subscriptions.
    publication = New MergePublication()
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName
    publication.ConnectionContext = conn

    If publication.IsExistingObject Then
        If (publication.Attributes And PublicationAttributes.AllowPush) = 0 Then
            publication.Attributes = publication.Attributes _
            Or PublicationAttributes.AllowPush
        End If

        ' Define the push subscription.
        subscription = New MergeSubscription()
        subscription.ConnectionContext = conn
        subscription.SubscriberName = subscriberName
        subscription.PublicationName = publicationName
        subscription.DatabaseName = publicationDbName
        subscription.SubscriptionDBName = subscriptionDbName
        subscription.HostName = hostname

        ' Set a schedule to synchronize the subscription every 2 hours
        ' during weekdays from 6am to 10pm.
        subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Weekly
        subscription.AgentSchedule.FrequencyInterval = Convert.ToInt32("0x003E", 16)
        subscription.AgentSchedule.FrequencyRecurrenceFactor = 1
        subscription.AgentSchedule.FrequencySubDay = ScheduleFrequencySubDay.Hour
        subscription.AgentSchedule.FrequencySubDayInterval = 2
        subscription.AgentSchedule.ActiveStartDate = 20051108
        subscription.AgentSchedule.ActiveEndDate = 20071231
        subscription.AgentSchedule.ActiveStartTime = 60000
        subscription.AgentSchedule.ActiveEndTime = 100000

        ' Specify the Windows login credentials for the Merge Agent job.
        subscription.SynchronizationAgentProcessSecurity.Login = winLogin
        subscription.SynchronizationAgentProcessSecurity.Password = winPassword

        ' Create the push subscription.
        subscription.Create()
    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
    conn.Disconnect()
End Try