Share via


プッシュ サブスクリプションの作成

このトピックでは、SQL Server 2012 で SQL Server Management Studio、Transact-SQL、またはレプリケーション管理オブジェクト (RMO) を使用して、プッシュ サブスクリプションを作成する方法について説明します。 SQL Server 以外のサブスクライバーのプッシュ サブスクリプションの作成に関する詳細については、「SQL Server 以外のサブスクライバーのサブスクリプションの作成」を参照してください。

このトピックの内容

  • プッシュ サブスクリプションを作成するために使用するもの:

    SQL Server Management Studio

    Transact-SQL

    レプリケーション管理オブジェクト (RMO)

SQL Server Management Studio の使用

サブスクリプションの新規作成ウィザードを使用して、パブリッシャーまたはサブスクライバーでプッシュ サブスクリプションを作成します。 ウィザードのページに従って、次の操作を実行します。

  • パブリッシャーとパブリケーションを指定します。

  • レプリケーション エージェントが実行される場所を選択します。 プッシュ サブスクリプションでは、パブリケーションの種類に応じて、[ディストリビューション エージェントの場所] ページまたは [マージ エージェントの場所] ページで [ディストリビューター <Distributor> ですべてのエージェントを実行する (プッシュ サブスクリプション)] を選択します。

  • サブスクライバーとサブスクリプション データベースを指定します。

  • レプリケーション エージェントによって作成された接続に対して使用されるログインとパスワードを指定します。

    • スナップショット パブリケーションとトランザクション パブリケーションに対するサブスクリプションでは、[ディストリビューション エージェント セキュリティ] ページで資格情報を指定します。

    • マージ パブリケーションに対するサブスクリプションでは、[マージ エージェント セキュリティ] ページで資格情報を指定します。

    各エージェントで必要な権限の詳細については、「レプリケーション エージェントのセキュリティ モデル」を参照してください。

  • 同期スケジュール、およびサブスクライバーをいつ初期化するかを指定します。

  • マージ パブリケーションの追加オプションとして、サブスクリプションの種類、およびパラメーター化されたフィルターの値を指定します。

  • サブスクリプションの更新が許可されるトランザクション パブリケーションの追加オプションを指定します。サブスクライバーがパブリッシャーで変更をすぐにコミットするかどうか、変更をキューに書き込むかどうか、およびサブスクライバーからパブリッシャーへの接続に使用される資格情報を指定します。

  • 必要に応じて、サブスクリプションのスクリプトを作成します。

パブリッシャーからプッシュ サブスクリプションを作成するには

  1. Microsoft SQL Server Management Studio でパブリッシャーに接続し、サーバー ノードを展開します。

  2. [レプリケーション] フォルダーを展開し、[ローカル パブリケーション] フォルダーを展開します。

  3. 1 つ以上のサブスクリプションを作成するパブリケーションを右クリックし、[新しいサブスクリプション] をクリックします。

  4. サブスクリプションの新規作成ウィザードのページに従って操作を実行します。

サブスクライバーからプッシュ サブスクリプションを作成するには

  1. SQL Server Management Studio でサブスクライバーに接続して、サーバー ノードを展開します。

  2. [レプリケーション] フォルダーを展開します。

  3. [ローカル サブスクリプション] フォルダーを右クリックし、[新しいサブスクリプション] をクリックします。

  4. サブスクリプションの新規作成ウィザードの [パブリケーション] ページで、[パブリッシャー] ボックスの一覧から [<パブリッシャーの検索.>] または [<Oracle パブリッシャーの検索>] を選択します。

  5. [サーバーへの接続] ダイアログ ボックスでパブリッシャーに接続します。

  6. [パブリケーション] ページでパブリケーションを選択します。

  7. サブスクリプションの新規作成ウィザードのページに従って操作を実行します。

[トップに戻る] リンクで使用される矢印アイコン[Top]

Transact-SQL の使用

プッシュ サブスクリプションは、レプリケーション ストアド プロシージャを使用してプログラムで作成できます。 使用するストアド プロシージャは、サブスクリプションが属するパブリケーションの種類によって変わります。

セキュリティに関する注意セキュリティに関する注意

可能であれば、実行時にセキュリティ資格情報の入力を求めるメッセージをユーザーに対して表示します。 スクリプト ファイルに資格情報を格納する必要がある場合、不正なアクセスを防ぐために、ファイルをセキュリティ保護する必要があります。

スナップショット パブリケーションまたはトランザクション パブリケーションに対するプッシュ サブスクリプションを作成するには

  1. パブリッシャー側のパブリケーション データベースに対して、sp_helppublication を実行して、パブリケーションがプッシュ サブスクリプションをサポートしていることを確認します。

    • allow_push の値が 1 の場合、プッシュ サブスクリプションがサポートされます。

    • allow_push の値が 0 の場合は、@propertyallow_push を、@valuetrue を指定して、sp_changepublication を実行します。

  2. パブリッシャー側のパブリケーション データベースに対して、sp_addsubscription を実行します。 @publication@subscriber、および @destination_db を指定します。 @subscription_type には push を指定します。 サブスクリプションの更新方法の詳細については、「トランザクション パブリケーションの更新可能なサブスクリプションの作成」を参照してください。

  3. パブリッシャー側のパブリケーション データベースに対して、sp_addpushsubscription_agent を実行します。 次の指定を行います。

    • @subscriber パラメーター、@subscriber_db パラメーター、および @publication パラメーター。

    • ディストリビューターで実行されるディストリビューション エージェントが使用する Microsoft Windows 資格情報。@job_login および @job_password に指定します。

      注意

      Windows 統合認証を使用して行われる接続では、常に @job_login および @job_password で指定された Windows 資格情報が使用されます。 ディストリビューション エージェントは、常に Windows 統合認証を使用してディストリビューターにローカル接続します。 既定では、エージェントは Windows 統合認証を使用してサブスクライバーに接続します。

    • (省略可) @subscriber_security_mode0 を指定し、@subscriber_login および @subscriber_password に Microsoft SQL Server ログイン情報を指定します。 サブスクライバーに接続するときに SQL Server 認証を使用する必要がある場合、これらのパラメーターを指定します。

    • このサブスクリプションでのディストリビューション エージェント ジョブのスケジュール。 詳細については、「同期スケジュールの指定」を参照してください。

    セキュリティに関する注意セキュリティに関する注意

    リモート ディストリビューターを使用するパブリッシャー側でプッシュ サブスクリプションを作成する場合は、job_login および job_password を含むすべてのパラメーターに指定された値がディストリビューターにプレーン テキストとして送信されます。 このストアド プロシージャを実行する前に、パブリッシャーとそのリモート ディストリビューター間の接続を暗号化する必要があります。 詳細については、「データベース エンジンへの暗号化接続の有効化 (SQL Server 構成マネージャー)」を参照してください。

マージ パブリケーションに対するプッシュ サブスクリプションを作成するには

  1. パブリッシャー側のパブリケーション データベースに対して、sp_helpmergepublication を実行して、パブリケーションがプッシュ サブスクリプションをサポートしていることを確認します。

    • allow_push の値が 1 の場合、パブリケーションでプッシュ サブスクリプションがサポートされます。

    • allow_push の値が 1 ではない場合は、@propertyallow_push を、@valuetrue を指定して、sp_changemergepublication を実行します。

  2. パブリッシャー側のパブリケーション データベースに対して、sp_addmergesubscription を実行します。次のパラメーターを指定します。

    • @publication。 これはパブリケーションの名前です。

    • @subscriber_type。 クライアント サブスクリプションの場合は local を指定し、サーバー サブスクリプションの場合は global を指定します。

    • @subscription_priority。 サーバー サブスクリプションの場合、サブスクリプションの優先度 (0.0099.99) を指定します。

      詳細については、「マージ レプリケーションの競合検出および解決の詳細」を参照してください。

  3. パブリッシャー側のパブリケーション データベースに対して、sp_addmergepushsubscription_agent を実行します。 次の指定を行います。

    • @subscriber パラメーター、@subscriber_db パラメーター、および @publication パラメーター。

    • ディストリビューターで実行されるマージ エージェントが使用する Windows 資格情報。@job_login および @job_password に指定します。

      注意

      Windows 統合認証を使用して行われる接続では、常に @job_login および @job_password で指定された Windows 資格情報が使用されます。 マージ エージェントは、常に Windows 統合認証を使用してディストリビューターにローカル接続します。 既定では、エージェントは Windows 統合認証を使用してサブスクライバーに接続します。

    • (省略可) @subscriber_security_mode0 を指定し、@subscriber_login および @subscriber_password に SQL Server ログイン情報を指定します。 サブスクライバーに接続するときに SQL Server 認証を使用する必要がある場合、これらのパラメーターを指定します。

    • (省略可) @publisher_security_mode0 を指定し、@publisher_login および @publisher_password に SQL Server ログイン情報を指定します。 パブリッシャーに接続するときに SQL Server 認証を使用する必要がある場合、これらの値を指定します。

    • このサブスクリプションでのマージ エージェント ジョブのスケジュール。 詳細については、「同期スケジュールの指定」を参照してください。

    セキュリティに関する注意セキュリティに関する注意

    リモート ディストリビューターを使用するパブリッシャー側でプッシュ サブスクリプションを作成する場合は、job_login および job_password を含むすべてのパラメーターに指定された値がディストリビューターにプレーン テキストとして送信されます。 このストアド プロシージャを実行する前に、パブリッシャーとそのリモート ディストリビューター間の接続を暗号化する必要があります。 詳細については、「データベース エンジンへの暗号化接続の有効化 (SQL Server 構成マネージャー)」を参照してください。

例 (Transact-SQL)

次の例では、トランザクション パブリケーションに対するプッシュ サブスクリプションを作成します。 ログインとパスワードの値は、実行時に 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".

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

--Add a push subscription to a transactional publication.
USE [AdventureWorks2012]
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

次の例では、マージ パブリケーションに対するプッシュ サブスクリプションを作成します。 ログインとパスワードの値は、実行時に 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".

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 [AdventureWorks2012];
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

[トップに戻る] リンクで使用される矢印アイコン[Top]

レプリケーション管理オブジェクト (RMO) の使用

レプリケーション管理オブジェクト (RMO) を使用することで、プログラムによってプッシュ サブスクリプションを作成できます。 プッシュ サブスクリプションを作成する際に使用する RMO クラスは、作成するサブスクリプションの対象となるパブリケーションの種類によって異なります。

セキュリティに関する注意セキュリティに関する注意

可能であれば、実行時にセキュリティ資格情報の入力を求めるメッセージを表示します。 資格情報を保存する必要がある場合は、Microsoft Windows .NET Framework に用意されている暗号化サービスを使用します。

スナップショット パブリケーションまたはトランザクション パブリケーションに対するプッシュ サブスクリプションを作成するには

  1. ServerConnection クラスを使用して、パブリッシャーへの接続を作成します。

  2. 手順 1. のパブリッシャー接続を使用して、TransPublication クラスのインスタンスを作成します。 NameDatabaseName、および ConnectionContext を指定します。

  3. LoadProperties メソッドを呼び出します。 このメソッドが false を返す場合、手順 2. で指定したプロパティが誤っているか、サーバーにパブリケーションが存在していません。

  4. Attributes プロパティと AllowPush のビットごとの論理積演算 (Visual C# では &、Visual Basic では And) を実行します。 結果が None の場合は、Attributes に対して、ビットごとの論理 OR ( |(Visual C#) および Or (Visual Basic)) を AttributesAllowPush の間で実行した結果を設定します。 次に、CommitPropertyChanges を呼び出してプッシュ サブスクリプションを有効にします。

  5. サブスクリプション データベースが存在しない場合は、Database クラスを使用して作成します。 詳細については、「データベースの作成、変更、および削除」を参照してください。

  6. TransSubscription クラスのインスタンスを作成します。

  7. 次のサブスクリプション プロパティを設定します。

    • 手順 1. で作成した、パブリッシャーに対する ServerConnectionConnectionContext に指定します。

    • サブスクリプション データベース名を SubscriptionDBName に指定します。

    • サブスクライバー名を SubscriberName に指定します。

    • パブリケーション データベース名を DatabaseName に指定します。

    • パブリケーション名を PublicationName に指定します。

    • SynchronizationAgentProcessSecurityLogin フィールドおよび Password (または SecurePassword) フィールド。これにより、ディストリビューターでディストリビューション エージェントを実行するときに使用される Microsoft Windows アカウントの資格情報が得られます。 このアカウントは、ディストリビューターとのローカル接続を確立したり、Windows 認証を使用したリモート接続を確立するときに使用されます。

      注意

      サブスクリプションが sysadmin 固定サーバー ロールのメンバーにより作成される場合、SynchronizationAgentProcessSecurity の設定は必須ではありませんが、推奨されます。 この場合、エージェントは SQL Server エージェントのアカウントを借用します。 詳細については、「レプリケーション エージェントのセキュリティ モデル」を参照してください。

    • (省略可) サブスクリプションを同期するために使用されるエージェント ジョブを作成する場合は、CreateSyncAgentByDefault に true (既定値) を指定します。 false を指定した場合、サブスクリプションはプログラムでのみ同期が可能になります。

    • (省略可) SQL Server 認証を使用してサブスクライバーに接続する場合、SubscriberSecuritySqlStandardLogin フィールドおよび SqlStandardPassword (または SecureSqlStandardPassword) フィールドを設定します。

  8. Create メソッドを呼び出します。

    セキュリティに関する注意セキュリティに関する注意

    リモート ディストリビューターを使用するパブリッシャー側でプッシュ サブスクリプションを作成する場合は、SynchronizationAgentProcessSecurity を含むすべてのプロパティに指定された値がディストリビューターにプレーン テキストとして送信されます。 Create メソッドを呼び出す前に、パブリッシャーとそのリモート ディストリビューター間の接続を暗号化する必要があります。 詳細については、「データベース エンジンへの暗号化接続の有効化 (SQL Server 構成マネージャー)」を参照してください。

マージ パブリケーションに対するプッシュ サブスクリプションを作成するには

  1. ServerConnection クラスを使用して、パブリッシャーへの接続を作成します。

  2. 手順 1. のパブリッシャー接続を使用して、MergePublication クラスのインスタンスを作成します。 NameDatabaseName、および ConnectionContext を指定します。

  3. LoadProperties メソッドを呼び出します。 このメソッドが false を返す場合、手順 2. で指定したプロパティが誤っているか、サーバーにパブリケーションが存在していません。

  4. Attributes プロパティと AllowPush のビットごとの論理積演算 (Visual C# では &、Visual Basic では And) を実行します。 結果が None の場合は、Attributes に対して、ビットごとの論理 OR ( |(Visual C#) および Or (Visual Basic)) を AttributesAllowPush の間で実行した結果を設定します。 次に、CommitPropertyChanges を呼び出してプッシュ サブスクリプションを有効にします。

  5. サブスクリプション データベースが存在しない場合は、Database クラスを使用して作成します。 詳細については、「データベースの作成、変更、および削除」を参照してください。

  6. MergeSubscription クラスのインスタンスを作成します。

  7. 次のサブスクリプション プロパティを設定します。

    • 手順 1. で作成した、パブリッシャーに対する ServerConnectionConnectionContext に指定します。

    • サブスクリプション データベース名を SubscriptionDBName に指定します。

    • サブスクライバー名を SubscriberName に指定します。

    • パブリケーション データベース名を DatabaseName に指定します。

    • パブリケーション名を PublicationName に指定します。

    • SynchronizationAgentProcessSecurityLogin フィールドおよび Password (または SecurePassword) フィールド。これにより、ディストリビューターでマージ エージェントを実行するときに使用される Microsoft Windows アカウントの資格情報が得られます。 このアカウントは、ディストリビューターとのローカル接続を確立したり、Windows 認証を使用したリモート接続を確立するときに使用されます。

      注意

      サブスクリプションが sysadmin 固定サーバー ロールのメンバーにより作成される場合、SynchronizationAgentProcessSecurity の設定は必須ではありませんが、推奨されます。 この場合、エージェントは SQL Server エージェントのアカウントを借用します。 詳細については、「レプリケーション エージェントのセキュリティ モデル」を参照してください。

    • (省略可) サブスクリプションを同期するために使用されるエージェント ジョブを作成する場合は、CreateSyncAgentByDefault に true (既定値) を指定します。 false を指定した場合、サブスクリプションはプログラムでのみ同期が可能になります。

    • (省略可) SQL Server 認証を使用してサブスクライバーに接続する場合、SubscriberSecuritySqlStandardLogin フィールドおよび SqlStandardPassword (または SecureSqlStandardPassword) フィールドを設定します。

    • (省略可) SQL Server 認証を使用してパブリッシャーに接続する場合、PublisherSecuritySqlStandardLogin フィールドおよび SqlStandardPassword (または SecureSqlStandardPassword) フィールドを設定します。

  8. Create メソッドを呼び出します。

    セキュリティに関する注意セキュリティに関する注意

    リモート ディストリビューターを使用するパブリッシャー側でプッシュ サブスクリプションを作成する場合は、SynchronizationAgentProcessSecurity を含むすべてのプロパティに指定された値がディストリビューターにプレーン テキストとして送信されます。 Create メソッドを呼び出す前に、パブリッシャーとリモート ディストリビューター間の接続を暗号化する必要があります。 詳細については、「データベース エンジンへの暗号化接続の有効化 (SQL Server 構成マネージャー)」を参照してください。

例 (RMO)

次の例では、トランザクション パブリケーションに対する新しいプッシュ サブスクリプションを作成します。 ディストリビューション エージェント ジョブを実行するために使用される Windows アカウントの資格情報は、実行時に渡されます。

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

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

            // 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"

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

' 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

次の例では、マージ パブリケーションに対する新しいプッシュ サブスクリプションを作成します。 マージ エージェント ジョブを実行するために使用される Windows アカウントの資格情報は、実行時に渡されます。

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

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

            // 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 = "AdventureWorks2012Replica"
Dim publicationDbName As String = "AdventureWorks2012"
Dim hostname As String = "adventure-works\garrett1"

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

' 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

[トップに戻る] リンクで使用される矢印アイコン[Top]

関連項目

概念

プッシュ サブスクリプションのプロパティの表示または変更

レプリケーション セキュリティの推奨事項

パブリケーションの作成

レプリケーション管理オブジェクトの概念

プッシュ サブスクリプションの作成

プッシュ サブスクリプションの同期

パブリケーションのサブスクライブ

sqlcmd でのスクリプト変数の使用