Skapa en publikation

gäller för:SQL ServerAzure SQL Managed Instance

Den här artikeln beskriver hur man skapar en publikation i SQL Server genom att använda SQL Server Management Studio, Transact-SQL eller Replication Management Objects (RMO).

Begränsningar och restriktioner

  • Publikations- och artikelnamn får inte innehålla någon av följande tecken: %, , , [, |], , ":, '?\/<eller .>* Om objekt i databasen innehåller någon av dessa tecken och du vill replikera dem, måste du ange ett artikelnamn som skiljer sig från objektnamnet i dialogrutan Artikel Egenskaper - <Artikel> , som finns tillgänglig från Artiklarsidan i guiden.

Security

När det är möjligt uppmanar du användarna att ange säkerhetsautentiseringsuppgifter vid körning. Om du måste lagra autentiseringsuppgifter använder du de kryptografiska tjänster som tillhandahålls av Microsoft Windows .NET Framework.

Använd SQL Server Management Studio

Skapa publikationer och definiera artiklar med New Publication Wizard. Efter att en publikation har skapats, visa och ändra publikationsegenskaper i dialogrutan Publikationsegenskaper - <Publikation> . För information om hur du skapar en publikation från en Oracle-databas, se Skapa en publikation från en Oracle-databas.

Skapa en publikation och definiera artiklar

  1. Anslut till utgivaren i Microsoft SQL Server Management Studio och expandera sedan servernoden.

  2. Expandera mappen Replikering och högerklicka sedan på mappen Lokala publikationer .

  3. Välj ny publikation.

  4. Följ sidorna i Guiden för ny publikation för att:

    • Ange en distributör om distributionen inte har konfigurerats på servern. För mer information om att konfigurera distribution, se Configure Publishing and Distribution.

      Om du anger på Distributor-sidan att Publisher-servern ska fungera som sin egen Distributor (en lokal Distributor), och servern inte är konfigurerad som Distributor, så konfigurerar New Publication Wizard servern. Du kommer att ange en standardmapp för snapshot för distributören på sidan Snapshot Folder . Snapshot-mappen är helt enkelt en katalog som du har utsett som en shared; agenter som läser från och skriver till denna mapp måste ha tillräckliga behörigheter för att komma åt den. För mer information om hur mappen säkras på rätt sätt, se Secure the Snapshot Folder.

      Om du specificerar att en annan server ska agera som distributör måste du ange ett lösenord på sidan för administrativt lösenord för anslutningar som görs från Publisher till distributören. Detta lösenord måste matcha det lösenord som angavs när Publisher aktiverades hos den fjärranslutna distributören.

      Mer information finns i Konfigurera distribution.

    • Välj en publikationsdatabas.

    • Välj en publikationstyp. För mer information, se Typer av replikation.

    • Specificera data och databasobjekt att publicera; filtrera kolumner från tabellartiklar och ställa in artikelegenskaper.

    • Filtrera rader från tabellartiklar valfritt. Mer information finns i Filtrera publicerade data.

    • Ställ in schemat för Snapshot Agent.

    • Ange vilka autentiseringsuppgifter som följande replikeringsagenter körs under och använder för att upprätta anslutningar:

    • Valfritt: skriv ett skript för publiceringen. För mer information, se Scripting Replication.

    • Ange ett namn för publikationen.

Använda Transact-SQL

Publikationer kan skapas programmatiskt med hjälp av replikationslagrade procedurer. De lagrade procedurer som används beror på vilken typ av publikation som skapas.

Skapa en ögonblicksbild eller transaktionell publikation

  1. Vid Publisher i publiceringsdatabasen, kör sp_replicationdboption (Transact-SQL) för att möjliggöra publicering av den aktuella databasen med hjälp av snapshot eller transaktionell replikering.

  2. För en transaktionell publikation, avgör om det finns ett jobb som Log Reader Agent för publikationsdatabasen. (Detta steg krävs inte för snapshot-publikationer.)

    • Om det finns ett jobb som loggläsaragent för publikationsdatabasen, gå vidare till steg 3.

    • Om du är osäker på om det finns ett Log Reader Agent-jobb för en publicerad databas, kör sp_helplogreader_agent (Transact-SQL) vid Publisher i publikationsdatabasen.

    • Om resultatuppsättningen är tom, skapa ett jobb för Log Reader Agent. Vid Publisher, utför sp_addlogreader_agent (Transact-SQL). Ange de Microsoft Windows inloggningsuppgifter under vilka agenten körs för @job_name och @password. Om agenten använder SQL Server-autentisering när den ansluter till Publisher, måste du också ange ett värde för 0 för @publisher_security_mode och SQL Server-inloggningsinformationen för @publisher_login och @publisher_password. Fortsätt till steg 3.

  3. Vid Publisher, utför sp_addpublication (Transact-SQL). Ange ett publiceringsnamn för @publication, och för parametern @repl_freq , ange ett värde på snapshot för en snapshot-publikation eller ett värde för continuous en transaktionell publikation. Ange eventuella andra publiceringsalternativ. Detta definierar publikationen.

    Note

    Publikationsnamn kan inte inkludera följande karaktärer:

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

  4. Vid Publisher, utför sp_addpublication_snapshot (Transact-SQL). Ange publiceringsnamnet som användes i steg 3 för @publication och Windows-uppgifterna under vilka Snapshot Agent körs för @snapshot_job_name och @password. Om agenten använder SQL Server-autentisering när den ansluter till Publisher, måste du också ange ett värde för 0 för @publisher_security_mode och SQL Server-inloggningsinformationen för @publisher_login och publisher_password. Detta skapar ett Snapshot Agent-jobb för publikationen.

    Important

    När du konfigurerar en utgivare med en fjärransluten distributör skickas de värden som anges för alla parametrar, inklusive job_login och job_password, till distributören som oformaterad text. Du bör kryptera anslutningen mellan Utgivaren och dess fjärranslutna distributör innan du kör den här lagrade proceduren. Mer information finns i Aktivera krypterade anslutningar till databasmotorn (SQL Server Configuration Manager).

  5. Lägg till artiklar i publikationen. Mer information finns i Definiera en artikel.

  6. Starta Snapshot Agent-jobbet för att generera den inledande ögonblicksbilden för den här publikationen. Mer information finns i Skapa och tillämpa den första ögonblicksbilden.

Skapa en sammanslagningspublikation

  1. Vid Publisher, kör sp_replicationdboption (Transact-SQL) för att möjliggöra publicering av den aktuella databasen med hjälp av sammanslagningsreplikering.

  2. Hos utgivaren i publiceringsdatabasen kör du sp_addmergepublication (Transact-SQL). Ange ett namn för publikationen @publication och eventuella andra publiceringsalternativ. Detta definierar publikationen.

    Note

    Publikationsnamn kan inte inkludera följande karaktärer:

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

  3. Vid Publisher, utför sp_addpublication_snapshot (Transact-SQL). Ange publiceringsnamnet som användes i steg 2 för @publication och Windows-uppgifterna under vilka Snapshot Agent körs för @snapshot_job_name och @password. Om agenten använder SQL Server-autentisering när den ansluter till Publisher, måste du också ange ett värde för 0 för @publisher_security_mode och SQL Server-inloggningsinformationen för @publisher_login och @publisher_password. Detta skapar ett Snapshot Agent-jobb för publikationen.

    Important

    När du konfigurerar en utgivare med en fjärransluten distributör skickas de värden som anges för alla parametrar, inklusive job_login och job_password, till distributören som oformaterad text. Du bör kryptera anslutningen mellan Utgivaren och dess fjärranslutna distributör innan du kör den här lagrade proceduren. Mer information finns i Aktivera krypterade anslutningar till databasmotorn (SQL Server Configuration Manager).

  4. Lägg till artiklar i publikationen. Mer information finns i Definiera en artikel.

  5. Starta Snapshot Agent-jobbet för att generera den inledande ögonblicksbilden för den här publikationen. Mer information finns i Skapa och tillämpa den första ögonblicksbilden.

Exempel (Transact-SQL)

Detta exempel skapar en transaktionell publikation. Skriptvariabler används för att skicka Windows-inloggningsuppgifter som behövs för att skapa jobb för Snapshot Agent och Log Reader Agent.

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

Detta exempel skapar en sammanslagningspublikation. Skriptvariabler används för att vidarebefordra Windows-autentiseringsuppgifter som krävs för att skapa jobbet för Snapshot Agent.

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

Använd Replication Management Objects (RMO)

Du kan skapa publikationer programmatiskt genom att använda Replication Management Objects (RMO). De RMO-klasser du använder för att skapa en publikation beror på vilken typ av publikation du skapar.

Skapa en ögonblicksbild eller transaktionell publikation

  1. Skapa en anslutning till Publisher med hjälp av klassen ServerConnection.

  2. Skapa en instans av ReplicationDatabase klassen för publiceringsdatabasen, sätt egenskapen ConnectionContext till instansen av ServerConnection från steg 1 och anropa metoden LoadProperties . Om LoadProperties returnerar false, verifiera att databasen existerar.

  3. Om egenskapen EnabledTransPublishing är false, sätt den till true.

  4. I en transaktionspublikation kontrollerar du värdet för egenskapen LogReaderAgentExists. Om denna egenskap är true, finns det redan ett Log Read Agent-jobb för denna databas. Om denna egenskap är false, gör följande:

  5. Skapa en instans av TransPublication klassen och sätt följande egenskaper för detta objekt:

  6. Anropa metoden Create för att skapa publikationen.

    Important

    När en Publisher konfigureras med en fjärrdistributör skickas värdena som tillhandahålls för alla egenskaper, inklusive SnapshotGenerationAgentProcessSecurity, till distributören som klartext. Du bör kryptera anslutningen mellan Publisher och dess fjärranslutna distributör innan du Create anropar metoden. Mer information finns i Aktivera krypterade anslutningar till databasmotorn (SQL Server Configuration Manager).

  7. Anropa CreateSnapshotAgent metoden för att skapa Snapshot Agent-jobbet för publikationen.

Skapa en sammanslagningspublikation

  1. Skapa en anslutning till Publisher med hjälp av klassen ServerConnection.

  2. Skapa en instans av ReplicationDatabase klassen för publiceringsdatabasen, sätt egenskapen ConnectionContext till instansen av ServerConnection från steg 1 och anropa metoden LoadProperties . Om LoadProperties returnerar false, verifiera att databasen existerar.

  3. Om EnabledMergePublishing Egenskapen är false, sätt den till true, och anropa CommitPropertyChanges.

  4. Skapa en instans av MergePublication klassen och sätt följande egenskaper för detta objekt:

  5. Anropa metoden Create för att skapa publikationen.

    Important

    När en Publisher konfigureras med en fjärrdistributör skickas värdena som tillhandahålls för alla egenskaper, inklusive SnapshotGenerationAgentProcessSecurity, till distributören som klartext. Du bör kryptera anslutningen mellan Publisher och dess fjärranslutna distributör innan du Create anropar metoden. Mer information finns i Aktivera krypterade anslutningar till databasmotorn (SQL Server Configuration Manager).

  6. Anropa CreateSnapshotAgent metoden för att skapa Snapshot Agent-jobbet för publikationen.

Exempel (RMO)

Detta exempel möjliggör AdventureWorks databasen för transaktionell publicering, definierar ett Log Reader Agent-jobb och skapar publikationen AdvWorksProductTran . En artikel måste definieras för denna publikation. Autentiseringsuppgifterna för Windows-kontot som behövs för att skapa Log Reader Agent-jobbet och Snapshot Agent-jobbet överförs vid körning. För att lära dig hur man använder RMO för att definiera snapshot- och transaktionsartiklar, se Definiera en artikel.

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

Detta exempel möjliggör AdventureWorks databasen för sammanslagen publicering och skapar publikationen AdvWorksSalesOrdersMerge . Artiklar måste fortfarande definieras för denna publikation. De autentiseringsuppgifter för Windows-kontot som behövs för att skapa Snapshot Agent-jobbet skickas vid körning. För att lära dig hur man använder RMO för att definiera sammanslagna artiklar, se Definiera en artikel.

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