パブリケーションの作成

適用対象: SQL ServerAzure SQL Managed Instance

このアーティクルは、SQL Server Management Studio、Transact-SQL、またはレプリケーション管理オブジェクト (RMO) を使用して SQL Server のパブリケーションを作成する方法について説明します。

制限事項と制約事項

  • パブリケーション名およびアーティクル名には、 %*[]|:"?'\/<、 または >を使用できません。 データベースのオブジェクトにこれらの文字が含まれ、これらをレプリケートする場合は、[アーティクルのプロパティ - <アーティクル> ダイアログ ボックスで、オブジェクト名と異なるアーティクル名を指定する必要があります。このダイアログ ボックスは、ウィザードの [アーティクル] ページより利用可能です。

セキュリティ

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

SQL Server Management Studio を使用する

パブリケーションの新規作成ウィザードにより、パブリケーションを作成し、アーティクルを定義します。 パブリケーションを作成したら、[パブリケーションのプロパティ - <パブリケーション]> ダイアログ ボックスでパブリケーションのプロパティを表示および変更します。 Oracle データベースからパブリケーションを作成する方法については、「Create a Publication from an Oracle Database」(Oracle データベースからパブリケーションを作成する) をご覧ください。

パブリケーションを作成し、アーティクルを定義する

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

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

  3. [新しいパブリケーション] を選択します。

  4. パブリケーションの新規作成ウィザードのページに従い、以下の操作を実行します。

    • サーバーでディストリビューションが構成されていない場合は、ディストリビューターを指定します。 ディストリビューションの構成の詳細については、「Configure Publishing and Distribution」(パブリッシュとディストリビューションの構成) をご覧ください。

      [ディストリビューター] ページで、パブリッシャー サーバーが独自のディストリビューター (ローカル ディストリビューター) として機能するように指定した場合、このサーバーはディストリビューターとして構成されていないため、パブリケーションの新規作成ウィザードでサーバーを構成します。 [スナップショット フォルダー] ページで、ディストリビューターの既定のスナップショット フォルダーを指定します。 スナップショット フォルダーは、共有として指定したディレクトリです。このフォルダーの読み取りと書き込みをするエージェントには、このフォルダーへのアクセスを可能にする十分な権限が必要です。 フォルダーの適切なセキュリティ保護の詳細については、「Secure the Snapshot Folder」(スナップショット フォルダーのセキュリティ保護) をご覧ください。

      別のサーバーがディストリビューターとして機能するように指定する場合は、パブリッシャーからディストリビューターへの接続のため、 [管理パスワード] ページでパスワードを入力する必要があります。 このパスワードは、リモート ディストリビューターでパブリッシャーを有効にしたときに指定したパスワードと一致する必要があります。

      詳しくは、「 Configure Distribution」を参照してください。

    • パブリケーション データベースを選択します。

    • パブリケーションの種類を選択します。 詳細については、「Types of Replication」(レプリケーションの種類) をご覧ください。

    • パブリッシュするデータおよびデータベース オブジェクトを指定します。必要に応じて、テーブル アーティクルから列をフィルター選択し、アーティクルのプロパティを設定します。

    • 必要に応じて、テーブル アーティクルから行をフィルター選択します。 詳細については、「パブリッシュされたデータのフィルター選択」を参照してください。

    • スナップショット エージェントのスケジュールを設定します。

    • 以下のレプリケーション エージェントの実行および接続に使用される資格情報を指定します。

      • すべてのパブリケーション用のスナップショット エージェント。

      • すべてのトランザクショナル パブリケーション用のログ リーダー エージェント。

      • 更新サブスクリプションを許可するトランザクショナル パブリケーションのキュー リーダー エージェント。

        詳細については、「 Replication Agent Security Model 」および「 Replication Security Best Practices」を参照してください。

    • 必要に応じて、パブリケーションのスクリプトを作成します。 詳細については、「レプリケーションのスクリプト作成」を参照してください。

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

Transact-SQL の使用

パブリケーションは、レプリケーションのストアド プロシージャを使用してプログラムから作成できます。 どのストアド プロシージャを使用するかは、作成するパブリケーションの種類によって異なります。

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

  1. パブリッシャーのパブリケーション データベースで sp_replicationdboption (Transact-SQL) を実行し、スナップショット レプリケーションまたはトランザクション レプリケーションを使用して現在のデータベースのパブリケーションを有効にします。

  2. トランザクション パブリケーションの場合は、パブリケーション データベースのログ リーダー エージェント ジョブが存在するかどうかを確認します。 (スナップショット パブリケーションの場合、この手順は不要です。)

    • パブリケーション データベースのログ リーダー エージェント ジョブが存在する場合は、手順 3. に進みます。

    • パブリッシュされたデータベース用のログ リーダー エージェント ジョブが存在するかどうかわからない場合は、パブリッシャー側のパブリケーション データベースに対して sp_helplogreader_agent (Transact-SQL) を実行します。

    • 結果セットが空の場合は、ログ リーダー エージェント ジョブを作成します。 パブリッシャーで、sp_addlogreader_agent (Transact-SQL) を実行します。 エージェントの実行に使用される Microsoft Windows 資格情報を @job_name@passwordを使用して、トランザクション パブリケーションに対するサブスクリプションの更新を有効にする方法について説明します。 エージェントがパブリッシャーに接続する際に SQL Server 認証を使用する場合、さらに @publisher_security_mode0 の値を指定し、 @publisher_login@publisher_password のSQL Server ログイン情報を指定してください。 手順 3. に進みます。

  3. パブリッシャーで、sp_addpublication (Transact-SQL) を実行します。 @publication にパブリケーション名を指定し、@repl_freq パラメーターを指定し、snapshot (スナップショット パブリケーションの場合)の snapshot または continuous (トランザクション パブリケーションの場合)の continuous の値を指定します。 必要に応じて、その他のパブリケーション オプションを指定してください。 これにより、パブリケーションが定義されます。

    Note

    パブリケーション名に、次の文字を含めることはできません。

    %*[]|:"?\/<、または >

  4. パブリッシャーで sp_addpublication_snapshot (Transact-SQL) を実行します。 手順 3. で使用したパブリケーション名を @publication に指定し、スナップショット エージェントを実行するときに使用される Windows 資格情報を @snapshot_job_name@passwordを使用して、トランザクション パブリケーションに対するサブスクリプションの更新を有効にする方法について説明します。 エージェントがパブリッシャーに接続する際に SQL Server 認証を使用する場合、さらに @publisher_security_mode0 の値を指定し、 @publisher_loginpublisher_password のSQL Server ログイン情報を指定してください。 これにより、パブリケーション用のスナップショット エージェント ジョブが作成されます。

    重要

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

  5. パブリケーションにアーティクルを追加します。 詳しくは、「 アーティクルを定義」をご覧ください。

  6. スナップショット エージェント ジョブを起動して、このパブリケーションの初期スナップショットを生成します。 詳しくは、「 初期スナップショットの作成および適用」をご覧ください。

統合 パブリケーションを作成するには

  1. パブリッシャーで sp_replicationdboption (Transact-SQL) を実行し、マージ レプリケーションを使用して現在のデータベースのパブリケーションを有効にします。

  2. パブリッシャー側のパブリケーション データベースに対して、sp_addmergepublication (Transact-SQL) を実行します。 @publication にパブリケーションの名前を指定し、必要に応じて他のパブリケーション オプションを指定します。 これにより、パブリケーションが定義されます。

    Note

    パブリケーション名に、次の文字を含めることはできません。

    %*[]|:"?\/<、または >

  3. パブリッシャーで sp_addpublication_snapshot (Transact-SQL) を実行します。 手順 2. で使用したパブリケーション名を @publication に指定し、スナップショット エージェントを実行するときに使用される Windows 資格情報を @snapshot_job_name@passwordを使用して、トランザクション パブリケーションに対するサブスクリプションの更新を有効にする方法について説明します。 エージェントがパブリッシャーに接続する際に SQL Server 認証を使用する場合、さらに @publisher_security_mode0 の値を指定し、 @publisher_login@publisher_password のSQL Server ログイン情報を指定してください。 これにより、パブリケーション用のスナップショット エージェント ジョブが作成されます。

    重要

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

  4. パブリケーションにアーティクルを追加します。 詳しくは、「 アーティクルを定義」をご覧ください。

  5. スナップショット エージェント ジョブを起動して、このパブリケーションの初期スナップショットを生成します。 詳しくは、「 初期スナップショットの作成および適用」をご覧ください。

例 (Transact-SQL)

この例では、トランザクション パブリケーションを作成します。 スナップショット エージェント ジョブおよびログ リーダー エージェント ジョブの作成に必要な Windows 資格情報は、スクリプト変数を使用して渡しています。

-- To avoid storing the login and password in the script file, the values 
-- are passed into SQLCMD as scripting variables. 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 @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks'; 
SET @publication = N'AdvWorksProductTran'; 
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login); 
-- This should be passed at runtime.
SET @password = $(Password); 

-- Enable transactional or snapshot replication on the publication database.
EXEC sp_replicationdboption 
    @dbname=@publicationDB, 
    @optname=N'publish',
    @value = N'true';

-- Execute sp_addlogreader_agent to create the agent job. 
EXEC sp_addlogreader_agent 
    @job_login = @login, 
    @job_password = @password,
    -- Explicitly specify the use of Windows Integrated Authentication (default) 
    -- when connecting to the Publisher.
    @publisher_security_mode = 1;

-- Create a new transactional publication with the required properties. 
EXEC sp_addpublication 
    @publication = @publication, 
    @status = N'active',
    @allow_push = N'true',
    @allow_pull = N'true',
    @independent_agent = N'true';

-- Create a new snapshot job for the publication, using a default schedule.
EXEC sp_addpublication_snapshot 
    @publication = @publication, 
    @job_login = @login, 
    @job_password = @password,
    -- Explicitly specify the use of Windows Integrated Authentication (default) 
    -- when connecting to the Publisher.
    @publisher_security_mode = 1;
GO

この例では、マージ パブリケーションを作成します。 スナップショット エージェント ジョブの作成に必要な Windows 資格情報は、スクリプト変数を使用して渡しています。

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. 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".

--Declarations for adding a merge publication
DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks2022'; 
SET @publication = N'AdvWorksSalesOrdersMerge'; 
SET @login = $(Login);
SET @password = $(Password);

-- Enable merge replication on the publication database, using defaults.
USE master
EXEC sp_replicationdboption 
  @dbname=@publicationDB, 
  @optname=N'merge publish',
  @value = N'true' 

-- Create a new merge publication, explicitly setting the defaults. 
USE [AdventureWorks2022]
EXEC sp_addmergepublication 
-- These parameters are optional.
  @publication = @publication,
  -- optional parameters 
  @description = N'Merge publication of AdventureWorks2022.',
  @publication_compatibility_level  = N'120RTM';

-- Create a new snapshot job for the publication.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = @login, 
  @job_password = @password;
GO

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

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

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

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

  2. パブリケーション データベースに ReplicationDatabase クラスのインスタンスを作成するには、 ConnectionContext プロパティに手順 1. の ServerConnection インスタンスを設定し、 LoadProperties メソッドを呼び出します。 LoadPropertiesfalse を返す場合、データベースが存在するかどうか確認してください。

  3. EnabledTransPublishing プロパティが false の場合、これを true に設定します。

  4. トランザクション パブリケーションの場合は、LogReaderAgentExists プロパティの値を確認します。 このプロパティが true の場合、このデータベースに対するログ リーダー エージェント ジョブが既に存在しています。 このプロパティが false の場合、次の操作を実行してください。

  5. TransPublication クラスのインスタンスを作成し、このオブジェクトに次のプロパティを設定します。

  6. Create メソッドを呼び出して、パブリケーションを作成します。

    重要

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

  7. CreateSnapshotAgent メソッドを呼び出して、パブリケーションに対するスナップショット エージェント ジョブを作成します。

統合 パブリケーションを作成するには

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

  2. パブリケーション データベースに ReplicationDatabase クラスのインスタンスを作成するには、 ConnectionContext プロパティに手順 1. の ServerConnection インスタンスを設定し、 LoadProperties メソッドを呼び出します。 LoadPropertiesfalse を返す場合、データベースが存在するかどうか確認してください。

  3. EnabledMergePublishing プロパティが false の場合、このプロパティを true に設定し、CommitPropertyChanges を呼び出します。

  4. MergePublication クラスのインスタンスを作成し、このオブジェクトに次のプロパティを設定します。

    • 手順 1. の ServerConnectionConnectionContextに指定します。

    • パブリッシュするデータベースの名前を DatabaseNameに指定します。

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

    • SnapshotGenerationAgentProcessSecurityLogin フィールドおよび Password フィールドに、スナップショット エージェントの実行に使用する Windows アカウントの資格情報を指定します。 このアカウントは、Windows 認証を使用している場合に、スナップショット エージェントがローカル ディストリビューターへの接続や任意のリモート接続を行うときにも使用されます。

      Note

      パブリケーションが sysadmin 固定サーバー ロールのメンバーにより作成される場合、SnapshotGenerationAgentProcessSecurity の設定は不要です。 詳細については、「 レプリケーション エージェント セキュリティ モデル」を参照してください。

    • (省略可) 包括的論理和演算子 (Visual C# では |、Visual Basic では Or) および排他的論理和演算子 (Visual C# では ^、Visual Basic では Xor) を使用して、PublicationAttributes プロパティに Attributes の値を設定します。

  5. Create メソッドを呼び出して、パブリケーションを作成します。

    重要

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

  6. CreateSnapshotAgent メソッドを呼び出して、パブリケーションに対するスナップショット エージェント ジョブを作成します。

例 (RMO)

次の例では、AdventureWorks データベースでトランザクション パブリッシュを有効にして、ログ リーダー エージェント ジョブを定義し、AdvWorksProductTran パブリケーションを作成します。 このパブリケーションには、アーティクルを定義する必要があります。 ログ リーダー エージェント ジョブとスナップショット エージェント ジョブの作成に必要な Windows アカウントの資格情報は、実行時に渡されます。 RMO を使用してスナップショット アーティクルとトランザクション アーティクルを定義する方法については、「 Define an Article」を参照してください。

// Set the Publisher, publication database, and publication names.
string publicationName = "AdvWorksProductTran";
string publicationDbName = "AdventureWorks2022";
string publisherName = publisherInstance;

ReplicationDatabase publicationDb;
TransPublication publication;

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


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

    // Enable the AdventureWorks2022 database for transactional publishing.
    publicationDb = new ReplicationDatabase(publicationDbName, conn);

    // If the database exists and is not already enabled, 
    // enable it for transactional publishing.
    if (publicationDb.LoadProperties())
    {
        if (!publicationDb.EnabledTransPublishing)
        {
            publicationDb.EnabledTransPublishing = true;
        }

        // If the Log Reader Agent does not exist, create it.
        if (!publicationDb.LogReaderAgentExists)
        {
            // Specify the Windows account under which the agent job runs.
            // This account will be used for the local connection to the 
            // Distributor and all agent connections that use Windows Authentication.
            publicationDb.LogReaderAgentProcessSecurity.Login = winLogin;
            publicationDb.LogReaderAgentProcessSecurity.Password = winPassword;

            // Explicitly set authentication mode for the Publisher connection
            // to the default value of Windows Authentication.
            publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = true;

            // Create the Log Reader Agent job.
            publicationDb.CreateLogReaderAgent();
        }
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The {0} database does not exist at {1}.",
            publicationDb, publisherName));
    }

    // Set the required properties for the transactional publication.
    publication = new TransPublication();
    publication.ConnectionContext = conn;
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;

    // Specify a transactional publication (the default).
    publication.Type = PublicationType.Transactional;

    // Activate the publication so that we can add subscriptions.
    publication.Status = State.Active;

    // Enable push and pull subscriptions and independent Distribition Agents.
    publication.Attributes |= PublicationAttributes.AllowPull;
    publication.Attributes |= PublicationAttributes.AllowPush;
    publication.Attributes |= PublicationAttributes.IndependentAgent;

    // Specify the Windows account under which the Snapshot Agent job runs.
    // This account will be used for the local connection to the 
    // Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

    // Explicitly set the security mode for the Publisher connection
    // Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

    if (!publication.IsExistingObject)
    {
        // Create the transactional publication.
        publication.Create();

        // Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent();
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The {0} publication already exists.", publicationName));
    }
}

catch (Exception ex)
{
    // Implement custom application error handling here.
    throw new ApplicationException(String.Format(
        "The publication {0} could not be created.", publicationName), ex);
}
finally
{
    conn.Disconnect();
}
' Set the Publisher, publication database, and publication names.
Dim publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks2022"
Dim publisherName As String = publisherInstance

Dim publicationDb As ReplicationDatabase
Dim publication As TransPublication

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

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

    ' Enable the AdventureWorks2022 database for transactional publishing.
    publicationDb = New ReplicationDatabase(publicationDbName, conn)

    ' If the database exists and is not already enabled, 
    ' enable it for transactional publishing.
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledTransPublishing Then
            publicationDb.EnabledTransPublishing = True
        End If

        ' If the Log Reader Agent does not exist, create it.
        If Not publicationDb.LogReaderAgentExists Then
            ' Specify the Windows account under which the agent job runs.
            ' This account will be used for the local connection to the 
            ' Distributor and all agent connections that use Windows Authentication.
            publicationDb.LogReaderAgentProcessSecurity.Login = winLogin
            publicationDb.LogReaderAgentProcessSecurity.Password = winPassword

            ' Explicitly set authentication mode for the Publisher connection
            ' to the default value of Windows Authentication.
            publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = True

            ' Create the Log Reader Agent job.
            publicationDb.CreateLogReaderAgent()
        End If
    Else
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist at {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the transactional publication.
    publication = New TransPublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Specify a transactional publication (the default).
    publication.Type = PublicationType.Transactional

    'Enable push and pull subscriptions and independent Distribition Agents.
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPull
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.AllowPush
    publication.Attributes = _
    publication.Attributes Or PublicationAttributes.IndependentAgent

    ' Activate the publication so that we can add subscriptions.
    publication.Status = State.Active

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    If Not publication.IsExistingObject Then
        ' Create the transactional publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try

次の例では、AdventureWorks データベースでマージ パブリッシュを有効にし、AdvWorksSalesOrdersMerge パブリケーションを作成します。 このパブリケーションには、アーティクルを定義する必要があります。 スナップショット エージェント ジョブの作成に必要な Windows アカウントの資格情報は、実行時に渡されます。 RMO を使用してマージ アーティクルを定義する方法については、「 Define an Article」を参照してください。

// Set the Publisher, publication database, and publication names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2022";

ReplicationDatabase publicationDb;
MergePublication publication;

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

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

    // Enable the database for merge publication.				
    publicationDb = new ReplicationDatabase(publicationDbName, conn);
    if (publicationDb.LoadProperties())
    {
        if (!publicationDb.EnabledMergePublishing)
        {
            publicationDb.EnabledMergePublishing = true;
        }
    }
    else
    {
        // Do something here if the database does not exist. 
        throw new ApplicationException(String.Format(
            "The {0} database does not exist on {1}.",
            publicationDb, publisherName));
    }

    // Set the required properties for the merge publication.
    publication = new MergePublication();
    publication.ConnectionContext = conn;
    publication.Name = publicationName;
    publication.DatabaseName = publicationDbName;

    // Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True;

    // Specify the Windows account under which the Snapshot Agent job runs.
    // This account will be used for the local connection to the 
    // Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

    // Explicitly set the security mode for the Publisher connection
    // Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

    // Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;
    publication.Attributes |= PublicationAttributes.DynamicFilters;

    // Enable pull and push subscriptions.
    publication.Attributes |= PublicationAttributes.AllowPull;
    publication.Attributes |= PublicationAttributes.AllowPush;

    if (!publication.IsExistingObject)
    {
        // Create the merge publication.
        publication.Create();
        
        // Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent();
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The {0} publication already exists.", publicationName));
    }
}

catch (Exception ex)
{
    // Implement custom application error handling here.
    throw new ApplicationException(String.Format(
        "The publication {0} could not be created.", publicationName), ex);
}
finally
{
    conn.Disconnect();
}
' Set the Publisher, publication database, and publication names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2022"

Dim publicationDb As ReplicationDatabase
Dim publication As MergePublication

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

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

    ' Enable the database for merge publication.				
    publicationDb = New ReplicationDatabase(publicationDbName, conn)
    If publicationDb.LoadProperties() Then
        If Not publicationDb.EnabledMergePublishing Then
            publicationDb.EnabledMergePublishing = True
        End If
    Else
        ' Do something here if the database does not exist. 
        Throw New ApplicationException(String.Format( _
         "The {0} database does not exist on {1}.", _
         publicationDb, publisherName))
    End If

    ' Set the required properties for the merge publication.
    publication = New MergePublication()
    publication.ConnectionContext = conn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName

    ' Enable precomputed partitions.
    publication.PartitionGroupsOption = PartitionGroupsOption.True

    ' Specify the Windows account under which the Snapshot Agent job runs.
    ' This account will be used for the local connection to the 
    ' Distributor and all agent connections that use Windows Authentication.
    publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin
    publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword

    ' Explicitly set the security mode for the Publisher connection
    ' Windows Authentication (the default).
    publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = True

    ' Enable Subscribers to request snapshot generation and filtering.
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowSubscriberInitiatedSnapshot
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.DynamicFilters

    ' Enable pull and push subscriptions
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPull
    publication.Attributes = publication.Attributes Or _
        PublicationAttributes.AllowPush

    If Not publication.IsExistingObject Then
        ' Create the merge publication.
        publication.Create()

        ' Create a Snapshot Agent job for the publication.
        publication.CreateSnapshotAgent()
    Else
        Throw New ApplicationException(String.Format( _
            "The {0} publication already exists.", publicationName))
    End If
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
        "The publication {0} could not be created.", publicationName), ex)
Finally
    conn.Disconnect()
End Try

関連項目