게시 만들기

적용 대상:SQL ServerAzure SQL Managed Instance

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

제한 사항

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

보안

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

SQL Server Management Studio 사용

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

게시 만들기 및 문서 정의

  1. Microsoft SQL Server Management Studio의 게시자에 커넥트 서버 노드를 확장합니다.

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

  3. 새 발행물을 선택합니다.

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

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

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

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

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

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

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

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

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

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

    • 다음 복제본(replica) 에이전트가 실행되고 연결을 만드는 자격 증명을 지정합니다.

      • 모든 게시에 대한 스냅샷 에이전트.

      • 모든 트랜잭션 게시에 대한 로그 판독기 에이전트입니다.

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

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

    • 필요에 따라 게시를 스크립깅합니다. 자세한 내용은 복제 스크립팅을 참조 하세요.

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

Transact-SQL 사용

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

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

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

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

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

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

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

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

    참고 항목

    게시 이름에는 다음 문자를 포함할 수 없습니다.

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때 job_login 및 job_password 비롯한 모든 매개 변수에 제공된 값은 일반 텍스트로 배포자로 전송됩니다. 이 저장 프로시저를 실행하기 전에 게시자와 해당 원격 배포자 간의 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진(SQL Server 구성 관리자)에 대한 암호화된 커넥트온을 사용하도록 설정하세요.

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

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

병합 게시 만들기

  1. 게시자에서 sp_복제본(replica)tiondboption(Transact-SQL)을 실행하여 병합 복제본(replica) 사용하여 현재 데이터베이스를 게시할 수 있도록 합니다.

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

    참고 항목

    게시 이름에는 다음 문자를 포함할 수 없습니다.

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때 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 인스턴스를 만들고, 속성을 1단계의 ServerConnection 인스턴스로 설정하고ConnectionContext, 메서드를 호출합니다LoadProperties. 반환false되는 경우 LoadProperties 데이터베이스가 있는지 확인합니다.

  3. 속성이 EnabledTransPublishingfalse면 으로 true설정합니다.

  4. 트랜잭션 게시의 경우 속성 값을 LogReaderAgentExists 검사. 이 속성이 true면 이 데이터베이스에 대한 로그 읽기 에이전트 작업이 이미 있습니다. 이 속성이 false면 다음을 수행합니다.

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

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

    Important

    원격 배포자를 사용하여 게시자를 구성할 때를 포함하여 SnapshotGenerationAgentProcessSecurity모든 속성에 대해 제공된 값은 일반 텍스트로 배포자로 전송됩니다. Create 메서드를 호출하기 전에 게시자와 해당 원격 배포자 간 연결을 암호화해야 합니다. 자세한 내용은 데이터베이스 엔진(SQL Server 구성 관리자)에 대한 암호화된 커넥트온을 사용하도록 설정하세요.

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

병합 게시 만들기

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

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

  3. 속성이falseEnabledMergePublishing 설정 하 고 호출 CommitPropertyChanges합니다true.

  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

참고 항목