Erstellen einer Veröffentlichung

Gilt für:SQL ServerAzure SQL Managed Instance

In diesem Artikel wird beschrieben, wie Sie eine Veröffentlichung in SQL Server mithilfe von SQL Server Management Studio, Transact-SQL oder Replikationsverwaltungsobjekten (RMO) erstellen.

Einschränkungen und Beschränkungen

  • Veröffentlichungs- und Artikelnamen dürfen folgende Zeichen nicht enthalten: %, *, [, ], |, :, ", ?, ', \, /, < oder >. Wenn Objekte in der Datenbank eines dieser Zeichen enthalten, und Sie die Objekte replizieren möchten, müssen Sie einen Artikelnamen angeben, der sich von dem Objektnamen im Dialogfeld Artikeleigenschaften - <Article> unterscheidet. Dieses Dialogfeld ist im Assistenten auf der Seite Artikel verfügbar.

Sicherheit

Fordern Sie Benutzer nach Möglichkeit auf, Sicherheitsanmeldeinformationen zur Laufzeit einzugeben. Wenn Sie Anmeldeinformationen speichern müssen, verwenden Sie die Kryptografiedienste von Microsoft Windows .NET Framework.

Verwenden von SQL Server Management Studio

Mit dem Assistenten für neue Veröffentlichung erstellen Sie Veröffentlichungen und definieren Artikel. Rufen Sie nach der Erstellung einer Veröffentlichung das Dialogfeld Veröffentlichungseigenschaften – <Veröffentlichung> auf, um die Eigenschaften anzuzeigen und zu ändern. Weitere Informationen zum Erstellen von Veröffentlichungen aus einer Oracle-Datenbank finden Sie unter Erstellen einer Veröffentlichung aus einer Oracle-Datenbank.

Erstellen einer Veröffentlichung und Definieren von Artikeln

  1. Stellen Sie mit dem Verleger in Microsoft SQL Server Management Studio eine Verbindung her, und erweitern Sie dann den Serverknoten.

  2. Erweitern Sie den Ordner Replikation , und klicken Sie dann mit der rechten Maustaste auf den Ordner Lokale Veröffentlichungen .

  3. Wählen Sie Neue Veröffentlichung aus.

  4. Gehen Sie die Seiten im Assistenten für neue Veröffentlichungen durch, um Folgendes zu tun:

    • Angeben eines Verteilers, falls die Verteilung auf dem Server nicht konfiguriert wurde. Weitere Informationen zum Konfigurieren der Verteilung finden Sie unter Konfigurieren der Veröffentlichung und der Verteilung.

      Wenn Sie auf der Seite Verteiler angeben, dass der Verleger als eigener Verteiler fungiert (lokaler Verteiler) und der Server nicht als Verteiler konfiguriert ist, erfolgt die Konfiguration des Servers durch den Assistenten für neue Veröffentlichung. Auf der Seite Snapshotordner geben Sie einen Standard-Snapshotordner für den Distributor an. Ein Snapshotordner ist einfach ein Verzeichnis, das Sie als Freigabe festgelegt haben; Agenten, die aus diesem Ordner lesen oder in ihn schreiben, müssen über ausreichende Berechtigungen verfügen, um darauf zugreifen zu können. Weitere Informationen zum Sichern des Ordners finden Sie unter Sichern des Momentaufnahmeordners.

      Wenn Sie angeben, dass ein anderer Server als Verteiler fungieren soll, müssen Sie auf der Seite Administratorkennwort ein Kennwort für Verbindungen eingeben, die zwischen dem Verleger und dem Verteiler hergestellt werden. Dieses Kennwort muss mit dem Kennwort übereinstimmen, dass bei der Aktivierung des Verlegers auf dem Remoteverteiler angegeben wurde.

      Weitere Informationen finden Sie unter Configure Distribution.

    • Auswählen einer Veröffentlichungsdatenbank.

    • Auswählen eines Veröffentlichungstyps. Weitere Informationen finden Sie unter Replikationstypen.

    • Angeben von Daten und Datenbankobjekten, die veröffentlicht werden sollen. Optional können Sie Spalten aus Tabellenartikeln filtern und Artikeleigenschaften angeben.

    • Optionales Filtern von Zeilen aus Tabellenartikeln. Weitere Informationen finden Sie unter Filtern von veröffentlichten Daten.

    • Legen Sie den Zeitplan für den Snapshot-Agent fest.

    • Geben Sie die Anmeldeinformationen an, unter denen die folgenden Replikations-Agents ausgeführt werden und Verbindungen herstellen:

    • Optionale Erstellung eines Skripts für die Veröffentlichung. Weitere Informationen finden Sie unter Scripting Replication.

    • Angeben eines Namens für die Veröffentlichung.

Verwenden von Transact-SQL

Veröffentlichungen können programmgesteuert mit gespeicherten Replikationsprozeduren erstellt werden. Welche gespeicherten Prozeduren Sie verwenden, hängt vom Typ der zu erstellenden Veröffentlichung ab.

Erstellen Sie eine Snapshot- oder Transaktionsveröffentlichung

  1. Führen Sie beim Verleger in der Veröffentlichungsdatenbank sp_replicationdboption (Transact-SQL) aus, um die Veröffentlichung der aktuellen Datenbank für die Snapshot- oder Transaktionsreplikation zu aktivieren.

  2. Ermitteln Sie bei einer Transaktionsveröffentlichung, ob für die Publikationsdatenbank ein Auftrag des Log Reader-Agents vorhanden ist. (Dieser Schritt ist für Momentaufnahmeveröffentlichungen nicht erforderlich.)

    • Wenn ein Auftrag für den Protokolllese-Agent für die Veröffentlichungsdatenbank existiert, fahren Sie mit Schritt 3 fort.

    • Wenn Sie sich nicht sicher sind, ob für eine veröffentlichte Datenbank ein Protokolllese-Agent-Auftrag vorhanden ist, führen Sie beim Verleger in der veröffentlichten Datenbank sp_helplogreader_agent (Transact-SQL) aus.

    • Wenn die Ergebnismenge leer ist, erstellen Sie einen Job für den Protokolllese-Agent. Führen Sie beim Verleger sp_addlogreader_agent (Transact-SQL) aus. Geben Sie die Microsoft Windows-Anmeldeinformationen, unter denen der Agent ausgeführt wird, für @job_name und @password an. Wenn der Agent zum Herstellen der Verbindung mit dem Verleger die SQL Server-Authentifizierung verwendet, müssen Sie zudem den Wert von 0 für @publisher_security_mode und die SQL Server-Anmeldeinformationen für @publisher_login und @publisher_password angeben. Fahren Sie mit Schritt 3 fort.

  3. Führen Sie beim Verleger sp_addpublication (Transact-SQL) aus. Geben Sie einen Veröffentlichungsnamen für @publication und für den @repl_freq-Parameter einen Wert von snapshot bei einer Momentaufnahmeveröffentlichung oder einen Wert von continuous bei einer Transaktionsveröffentlichung an. Geben Sie eventuell weitere Veröffentlichungsoptionen an. Dadurch wird die Veröffentlichung definiert.

    Hinweis

    Veröffentlichungsnamen dürfen die folgenden Zeichen nicht enthalten:

    %, *, [, ], |, :, ", ?, \, /, < oder >.

  4. Führen Sie beim Verleger sp_addpublication_snapshot (Transact-SQL) aus. Geben Sie den in Schritt 3 für @publication verwendeten Veröffentlichungsnamen sowie die Windows-Anmeldeinformationen an, unter denen der Snapshot-Agent für @snapshot_job_name und @password ausgeführt wird. Wenn der Agent zum Herstellen der Verbindung mit dem Verleger die SQL Server-Authentifizierung verwendet, müssen Sie zudem den Wert von 0 für @publisher_security_mode und die SQL Server-Anmeldeinformationen für @publisher_login und publisher_password angeben. Dadurch wird ein Snapshot-Agent-Auftrag für die Publikation erstellt.

    Wichtig

    Beim Konfigurieren eines Verlegers mit einem Remoteverteiler werden die Werte, die für alle Parameter, einschließlich job_login und job_password, bereitgestellt werden, als Nur-Text an den Verteiler gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie diese gespeicherte Prozedur ausführen. Weitere Informationen finden Sie unter Aktivieren von verschlüsselten Verbindungen zur Datenbank-Engine (SQL Server-Konfigurations-Manager).

  5. Fügen Sie der Veröffentlichung Artikel hinzu. Weitere Informationen finden Sie unter Definieren eines Artikels.

  6. Starten Sie den Auftrag des Snapshot-Agents, um den initialen Snapshot für diese Publikation zu generieren. Weitere Informationen finden Sie unter Create and Apply the Initial Snapshot.

Erstellen Sie eine Zusammenführungsveröffentlichung

  1. Führen Sie auf dem Verleger sp_replicationdboption (Transact-SQL) aus, um die aktuelle Datenbank für die Veröffentlichung mittels Mergereplikation zu aktivieren.

  2. Führen Sie beim Publisher in der Veröffentlichungsdatenbank sp_addmergepublication (Transact-SQL) aus. Geben Sie einen Veröffentlichungsnamen für @publication und eventuell weitere Veröffentlichungsoptionen an. Dadurch wird die Veröffentlichung definiert.

    Hinweis

    Veröffentlichungsnamen dürfen die folgenden Zeichen nicht enthalten:

    %, *, [, ], |, :, ", ?, \, /, < oder >.

  3. Führen Sie beim Verleger sp_addpublication_snapshot (Transact-SQL) aus. Geben Sie den in Schritt 2 für @publication verwendeten Veröffentlichungsnamen sowie die Windows-Anmeldeinformationen an, unter denen der Momentaufnahme-Agent für @snapshot_job_name und @password ausgeführt wird. Wenn der Agent zum Herstellen der Verbindung mit dem Verleger die SQL Server-Authentifizierung verwendet, müssen Sie zudem den Wert von 0 für @publisher_security_mode und die SQL Server-Anmeldeinformationen für @publisher_login und @publisher_password angeben. Dadurch wird ein Snapshot-Agent-Auftrag für die Publikation erstellt.

    Wichtig

    Beim Konfigurieren eines Verlegers mit einem Remoteverteiler werden die Werte, die für alle Parameter, einschließlich job_login und job_password, bereitgestellt werden, als Nur-Text an den Verteiler gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie diese gespeicherte Prozedur ausführen. Weitere Informationen finden Sie unter Aktivieren von verschlüsselten Verbindungen zur Datenbank-Engine (SQL Server-Konfigurations-Manager).

  4. Fügen Sie der Veröffentlichung Artikel hinzu. Weitere Informationen finden Sie unter Definieren eines Artikels.

  5. Starten Sie den Auftrag des Snapshot-Agents, um den ersten Snapshot für diese Veröffentlichung zu generieren. Weitere Informationen finden Sie unter Create and Apply the Initial Snapshot.

Beispiel (Transact-SQL)

In diesem Beispiel wird eine Transaktionsveröffentlichung erstellt. Skriptvariablen werden verwendet, um Windows-Anmeldeinformationen zu übergeben, die zum Erstellen von Aufträgen für den Snapshot-Agent und den Log Reader-Agent erforderlich sind.

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

In diesem Beispiel wird eine Mergepublikation erstellt. Skriptvariablen werden verwendet, um Windows-Anmeldeinformationen zu übergeben, die zum Erstellen des Auftrags für den Snapshot-Agent erforderlich sind.

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

Verwenden von Replikationsverwaltungsobjekten (RMO)

Sie können Veröffentlichungen mithilfe von Replikationsverwaltungsobjekten (RMO) programmgesteuert erstellen. Welche RMO-Klassen Sie zum Erstellen von Veröffentlichungen verwenden, hängt vom Typ der zu erstellenden Veröffentlichung ab.

Erstellen Sie eine Snapshot- oder Transaktionsveröffentlichung

  1. Erstellen Sie eine Verbindung mit dem Verleger, indem Sie die ServerConnection -Klasse verwenden.

  2. Erstellen Sie eine Instanz der ReplicationDatabase -Klasse für die Veröffentlichungsdatenbank, legen Sie die ConnectionContext -Eigenschaft auf die Instanz von ServerConnection aus Schritt 1 fest, und rufen Sie die LoadProperties -Methode auf. Wenn LoadProperties den Wert false zurückgibt, vergewissern Sie sich, dass die Datenbank vorhanden ist.

  3. Hat die EnabledTransPublishing-Eigenschaft den Wert false, dann legen Sie ihren Wert auf true fest.

  4. Überprüfen Sie für eine Transaktionsveröffentlichung den Wert der LogReaderAgentExists -Eigenschaft. Wenn diese Eigenschaft den Wert true hat, ist ein Protokolllese-Agentauftrag für diese Datenbank bereits vorhanden. Hat diese Eigenschaft den Wert false, gehen Sie wie folgt vor:

  5. Erstellen Sie eine Instanz der TransPublication -Klasse, und legen Sie die folgenden Eigenschaften für dieses Objekt fest:

  6. Rufen Sie die Create -Methode auf, um die Veröffentlichung zu erstellen.

    Wichtig

    Beim Konfigurieren eines Publishers mit einem Remote-Distributor werden die für alle Eigenschaften angegebenen Werte, einschließlich SnapshotGenerationAgentProcessSecurity, als Klartext an den Distributor gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie die Create-Methode aufrufen. Weitere Informationen finden Sie unter Aktivieren von verschlüsselten Verbindungen zur Datenbank-Engine (SQL Server-Konfigurations-Manager).

  7. Rufen Sie die CreateSnapshotAgent-Methode auf, um den Momentaufnahme-Agent-Auftrag für die Publikation zu erstellen.

Erstellen Sie eine Zusammenführungsveröffentlichung

  1. Erstellen Sie eine Verbindung mit dem Verleger, indem Sie die ServerConnection -Klasse verwenden.

  2. Erstellen Sie eine Instanz der ReplicationDatabase -Klasse für die Veröffentlichungsdatenbank, legen Sie die ConnectionContext -Eigenschaft auf die Instanz von ServerConnection aus Schritt 1 fest, und rufen Sie die LoadProperties -Methode auf. Wenn LoadProperties den Wert false zurückgibt, vergewissern Sie sich, dass die Datenbank vorhanden ist.

  3. Wenn die EnabledMergePublishing-Eigenschaft den Wert false hat, legen Sie sie auf true fest, und rufen Sie CommitPropertyChanges auf.

  4. Erstellen Sie eine Instanz der MergePublication -Klasse, und legen Sie die folgenden Eigenschaften für dieses Objekt fest:

    • Die ServerConnection aus Schritt 1 für ConnectionContext.

    • Der Name der veröffentlichten Datenbank für DatabaseName.

    • Ein Name für die Veröffentlichung für Name.

    • Geben Sie in die Felder Login und Password in SnapshotGenerationAgentProcessSecurity die Anmeldeinformationen für das Windows-Konto ein, unter dem der Snapshot-Agent ausgeführt wird. Dieses Konto wird auch verwendet, wenn der Momentaufnahme-Agent Verbindungen zum lokalen Verteiler herstellt, sowie für alle Remoteverbindungen bei Verwendung der Windows-Authentifizierung.

      Hinweis

      Das Festlegen von SnapshotGenerationAgentProcessSecurity ist nicht erforderlich, wenn die Veröffentlichung von einem Mitglied der festen Serverrolle sysadmin erstellt wird. Weitere Informationen finden Sie unter Replication Agent Security Model.

    • (Optional) Verwenden Sie den inklusiven logischen OR-Operator (| in Visual C# und Or in Visual Basic) und den exklusiven logischen OR-Operator (^ in Visual C# und Xor in Visual Basic), um die PublicationAttributes-Werte für die Attributes-Eigenschaft festzulegen.

  5. Rufen Sie die Create -Methode auf, um die Veröffentlichung zu erstellen.

    Wichtig

    Beim Konfigurieren eines Publishers mit einem Remote-Distributor werden die für alle Eigenschaften angegebenen Werte, einschließlich SnapshotGenerationAgentProcessSecurity, als Klartext an den Distributor gesendet. Sie sollten die Verbindung zwischen dem Verleger und dem zugehörigen Remoteverteiler verschlüsseln, bevor Sie die Create-Methode aufrufen. Weitere Informationen finden Sie unter Aktivieren von verschlüsselten Verbindungen zur Datenbank-Engine (SQL Server-Konfigurations-Manager).

  6. Rufen Sie die CreateSnapshotAgent-Methode auf, um den Momentaufnahme-Agent-Auftrag für die Publikation zu erstellen.

Beispiele (RMO)

In diesem Beispiel wird die AdventureWorks-Datenbank für Transaktionsveröffentlichung aktiviert, ein Protokolllese-Agentauftrag definiert und die AdvWorksProductTran-Veröffentlichung erstellt. Für diese Veröffentlichung muss ein Artikel definiert sein. Die Anmeldeinformationen des Windows-Kontos, die zum Erstellen des Protokolllese-Agentauftrags und des Snapshot-Agentauftrags erforderlich sind, werden zur Laufzeit übergeben. Informationen darüber, wie RMO verwendet wird, um Momentaufnahme- und Transaktionsartikel zu definieren, finden Sie unter 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

In diesem Beispiel wird die Datenbank AdventureWorks für die Mergepublikation aktiviert und die Publikation AdvWorksSalesOrdersMerge erstellt. Für diese Veröffentlichung müssen ebenfalls Artikel definiert sein. Die Anmeldeinformationen für das Windows-Konto, die zum Erstellen des Auftrags des Momentaufnahme-Agents erforderlich sind, werden zur Laufzeit übergeben. Informationen darüber, wie RMO verwendet wird, um Mergeartikel zu definieren, finden Sie unter 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