다음을 통해 공유


게시 만들기

적용 대상: SQL Server Azure SQL Managed Instance

이 문서에서는 SQL Server Management Studio, Transact-SQL 또는 RMO(복제 관리 개체)를 사용하여 SQL Server에서 게시를 만드는 방법에 대해 설명합니다.

제한 사항

  • 게시 및 아티클 이름에는 다음 %, *, [, ], |, :, ", ?, ', \, /, < 또는 > 문자를 포함할 수 없습니다. 이러한 문자를 포함하는 데이터베이스 개체를 복제하려면 아티클 속성 - <아티클> 대화 상자(마법사의 아티클 페이지에서 사용 가능)에서 개체 이름과 다른 아티클 이름을 지정해야 합니다.

보안

가능한 경우 런타임 시 사용자에게 보안 자격 증명을 입력하라는 메시지가 표시됩니다. 자격 증명을 저장해야 하는 경우 Microsoft Windows .NET Framework에서 제공하는 암호화 서비스를 사용합니다.

SQL Server Management Studio 사용

새 게시 마법사를 사용하여 게시를 만들고 아티클을 정의합니다. 게시를 만든 후 게시 속성 - <게시>> 대화 상자에서 게시 속성을 보고 수정합니다. Oracle 데이터베이스에서 게시를 만드는 방법에 대한 자세한 내용은 Oracle Database에서 게시 만들기를 참조하세요.

게시 만들기 및 문서 정의

  1. Microsft SQL Server Management Studio에서 게시자에 연결한 다음 해당 서버 노드를 확장합니다.

  2. 복제 폴더를 확장한 다음 로컬 게시 폴더를 마우스 오른쪽 단추로 클릭합니다.

  3. 새 게시를 선택합니다.

  4. 새 게시 마법사의 페이지에 따라 다음을 수행하세요.

    • 배포가 서버에 구성되지 않은 경우 배포자를 지정합니다. 배포 구성에 대한 자세한 내용은 게시 및 배포 구성을 참조하세요.

      배포자 페이지에서 게시자 서버가 자체 배포자(로컬 배포자)로 작동하도록 지정하고 서버가 배포자로 구성되지 않은 경우 새 게시 마법사가 서버를 구성합니다. 스냅샷 폴더 페이지에서 배포자에 기본 스냅샷 폴더를 지정합니다. 스냅샷 폴더는 공유로 지정한 디렉터리일 뿐이며 이 폴더에 읽기/쓰기 작업을 수행하려면 에이전트에게 충분한 액세스 권한이 있어야 합니다. 폴더의 적절한 보안 유지 방법에 대한 자세한 내용은 스냅샷 폴더 보안 설정을 참조하세요.

      다른 서버가 배포자로 작동하도록 지정하는 경우 게시자에서 배포자로 연결하기 위해 관리 비밀번호 페이지에 비밀번호를 입력해야 합니다. 이 비밀번호는 원격 배포자에서 게시자를 사용할 때 지정한 비밀번호와 일치해야 합니다.

      자세한 내용은 배포 구성을 참조하세요.

    • 게시 데이터베이스를 선택합니다.

    • 보고서 유형을 선택합니다. 자세한 내용은 복제 형식을 참조하세요.

    • 게시할 데이터 및 데이터베이스 개체를 지정하고 선택적으로 테이블 아티클에서 열을 필터링하고 아티클 속성을 설정합니다.

    • 필요에 따라 테이블 아티클에서 행을 필터링합니다. 자세한 정보는 게시된 데이터 필터링을 참조하세요.

    • 스냅샷 에이전트 일정을 설정합니다.

    • 다음 복제 에이전트가 실행되는 자격 증명을 지정하고 연결합니다.

      • 스냅샷 에이전트(모든 게시용)

      • 모든 트랜잭션 게시용 로그 판독기 에이전트

      • 구독 업데이트를 허용하는 트랜잭션 게시에 대한 큐 판독기 에이전트

        자세한 내용은 복제 에이전트 보안 모델복제 보안 모범 사례를 참조하세요.

    • 선택적으로 게시를 스크립팅합니다. 자세한 내용은 복제 스크립팅을 참조하세요.

    • 게시의 이름을 지정합니다.

Transact-SQL 사용

복제 저장 프로시저를 사용하여 프로그래밍 방식으로 게시를 만들 수 있습니다. 사용하는 저장 프로시저는 만든 게시 유형에 따라 달라집니다.

스냅샷 또는 트랜잭션 게시 만들기

  1. 게시 데이터베이스의 게시자에서 sp_replicationdboption(Transact-SQL)을 실행하여 스냅샷 또는 트랜잭션 복제를 통해 현재 데이터베이스를 게시할 수 있도록 설정합니다.

  2. 트랜잭션 게시의 경우 게시 데이터베이스에 대한 로그 판독기 에이전트 작업이 있는지 확인합니다. (스냅샷 게시에는 이 단계가 필요하지 않습니다.)

    • 게시 데이터베이스에 로그 판독기 에이전트 작업이 있는 경우 3단계로 진행합니다.

    • 게시된 데이터베이스에 로그 판독기 에이전트 작업이 존재하는지 확실하지 않으면 게시 데이터베이스의 게시자에서 sp_helplogreader_agent(Transact-SQL)를 실행합니다.

    • 결과 집합이 비어 있으면 로그 판독기 에이전트 작업을 만듭니다. 게시자에서 sp_addlogreader_agent(Transact-SQL)를 실행합니다. @job_name@password에 에이전트가 실행되는 Microsoft Windows 자격 증명을 지정합니다. 게시자에 연결할 때 에이전트가 SQL Server 인증을 사용하면 0 값을 @publisher_security_mode에 지정하고 @publisher_login@publisher_password에 SQL Server 로그인 정보도 지정해야 합니다. 3단계로 진행합니다.

  3. 게시자에서 sp_addpublication(Transact-SQL)을 실행합니다. @publication@repl_freq 매개 변수에 게시 이름을 지정하거나 스냅샷 게시에 snapshot 값을 지정하거나 트랜잭션 게시에 continuous 값을 지정합니다. 다른 게시 옵션을 지정합니다. 이렇게 하면 게시가 정의됩니다.

    참고 항목

    게시 이름은 다음과 같은 문자를 포함할 수 없습니다.

    %, *, [, ], |, :, ", ?, \, /, < 또는 >

  4. 게시자에서 sp_addpublication_snapshot(Transact-SQL)을 실행합니다. @publication에 3단계에서 사용한 게시 이름을 지정하고 @snapshot_job_name@password에 스냅샷 에이전트가 실행되는 Windows 자격 증명을 지정합니다. 게시자에 연결할 때 에이전트가 SQL Server 인증을 사용하면 0 값을 @publisher_security_mode에 지정하고 @publisher_loginpublisher_password에 SQL Server 로그인 정보도 지정해야 합니다. 이렇게 하면 게시에 대해 스냅샷 에이전트 작업이 만들어집니다.

    Important

    게시자에서 원격 배포자를 사용하여 밀어넣기 구독을 만드는 경우 job_loginjob_password를 비롯한 모든 매개 변수에 제공된 값이 일반 텍스트로 배포자에게 보내집니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 대한 암호화된 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  5. 게시에 아티클을 추가합니다. 자세한 내용은 아티클 정의를 참조하세요.

  6. 스냅샷 에이전트 작업을 시작하여 이 게시의 초기 스냅샷을 생성합니다. 자세한 내용은 초기 스냅샷 만들기 및 적용을 참조하세요.

병합 게시 만들기

  1. 게시자에서 sp_replicationdboption(Transact-SQL)을 실행하여 병합 복제를 통해 현재 데이터베이스를 게시할 수 있도록 설정합니다.

  2. 게시 데이터베이스의 게시자에서 sp_addmergepublication(Transact-SQL)을 실행합니다. @publication에 게시 이름을 지정하고 기타 게시 옵션을 지정합니다. 이렇게 하면 게시가 정의됩니다.

    참고 항목

    게시 이름은 다음과 같은 문자를 포함할 수 없습니다.

    %, *, [, ], |, :, ", ?, \, /, < 또는 >

  3. 게시자에서 sp_addpublication_snapshot(Transact-SQL)을 실행합니다. @publication에 2단계에서 사용한 게시 이름을 지정하고 @snapshot_job_name@password에 스냅샷 에이전트가 실행되는 Windows 자격 증명을 지정합니다. 게시자에 연결할 때 에이전트가 SQL Server 인증을 사용하면 0 값을 @publisher_security_mode에 지정하고 @publisher_login@publisher_password에 SQL Server 로그인 정보도 지정해야 합니다. 이렇게 하면 게시에 대해 스냅샷 에이전트 작업이 만들어집니다.

    Important

    게시자에서 원격 배포자를 사용하여 밀어넣기 구독을 만드는 경우 job_loginjob_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 메서드를 호출하여 게시를 만듭니다.

    Important

    원격 배포자가 있는 게시자를 구성하는 경우 SnapshotGenerationAgentProcessSecurity를 비롯한 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 대한 암호화된 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  7. CreateSnapshotAgent 메서드를 호출하여 게시에 대한 스냅샷 에이전트 작업을 만듭니다.

병합 게시 만들기

  1. ServerConnection 클래스를 사용하여 게시자 연결을 만듭니다.

  2. 게시 데이터베이스에 대한 ReplicationDatabase 클래스의 인스턴스를 만들고, ConnectionContext 속성을 1단계의 ServerConnection 인스턴스로 설정하며, LoadProperties 메서드를 호출합니다. LoadPropertiesfalse를 반환하는 경우 데이터베이스가 있는지 확인합니다.

  3. EnabledMergePublishing 속성이 false면 이를 true로 설정하고 CommitPropertyChanges를 호출합니다.

  4. MergePublication 클래스의 인스턴스를 만들고 이 개체에 대해 다음 속성을 설정합니다.

  5. Create 메서드를 호출하여 게시를 만듭니다.

    Important

    원격 배포자가 있는 게시자를 구성하는 경우 SnapshotGenerationAgentProcessSecurity를 비롯한 모든 속성에 제공된 값이 일반 텍스트로 배포자에게 보내집니다. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진에 대한 암호화된 연결 사용(SQL Server 구성 관리자)을 참조하세요.

  6. CreateSnapshotAgent 메서드를 호출하여 게시에 대한 스냅샷 에이전트 작업을 만듭니다.

예제(RMO)

이 예제에서는 트랜잭션 게시를 위해 AdventureWorks 데이터베이스를 사용하도록 설정하고, 로그 판독기 에이전트 작업을 정의하고, AdvWorksProductTran 게시를 만듭니다. 이 게시에 대한 아티클을 정의해야 합니다. 로그 판독기 에이전트 작업 및 스냅샷 에이전트 작업을 만드는 데 필요한 Windows 계정 자격 증명은 런타임에 전달됩니다. RMO를 사용하여 스냅샷과 병합 아티클을 정의하는 방법은 아티클 정의를 참조하세요.

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

참고 항목