게시 만들기

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

항목 내용

  • 시작하기 전 주의 사항

    제한 사항

    보안

  • 게시를 만들고 아티클을 정의하려면:

    SQL Server Management Studio

    Transact-SQL

    RMO(복제 관리 개체)

시작하기 전 주의 사항

제한 사항

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

보안

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

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘[Top]

SQL Server Management Studio 사용

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

게시를 만들고 아티클을 정의하려면

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

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

  3. 새 게시를 클릭합니다.

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

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

      배포자 페이지에서 게시자 서버가 자신의 고유 배포자(로컬 배포자) 역할을 하는 것으로 지정했지만 서버가 배포자로 구성되어 있지 않은 경우 새 게시 마법사가 서버를 구성합니다. 스냅숏 폴더 페이지에서 배포자에 대해 기본 스냅숏 폴더를 지정하게 됩니다. 스냅숏 폴더는 공유하도록 지정된 디렉터리일 뿐이며 이 폴더에 읽기/쓰기 작업을 수행하려면 에이전트에게 충분한 액세스 권한이 있어야 합니다. 폴더에 보안을 설정하는 방법은 스냅숏 폴더 보안 설정을 참조하십시오.

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

      자세한 내용은 배포 구성을 참조하십시오.

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

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

    • 게시할 데이터와 데이터베이스 개체를 지정합니다. 필요에 따라 테이블 아티클에서 열을 필터링하고 아티클 속성을 설정합니다.

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

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

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

      - 모든 게시에 대한 스냅숏 에이전트

      - 모든 트랜잭션 게시에 대한 로그 판독기 에이전트

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

      자세한 내용은 복제 에이전트 보안 모델복제 보안을 위한 최선의 구현 방법을 참조하십시오.

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

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

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘[Top]

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 인증을 사용하면 @publisher_security_mode에 값 0을 지정하고 @publisher_login@publisher_password에 Microsoft 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 인증을 사용하면 @publisher_security_mode에 대해 값 0을 지정하고 @publisher_login@publisher_password에 대해 SQL Server 로그인 정보를 지정해야 합니다. 이렇게 하면 게시에 대해 스냅숏 에이전트 작업이 만들어집니다.

    보안 정보보안 정보

    게시자를 원격 배포자로 구성할 경우 job_login 및 job_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 인증을 사용하면 @publisher_security_mode에 대해 값 0을 지정하고 @publisher_login@publisher_password에 대해 SQL Server 로그인 정보를 지정해야 합니다. 이렇게 하면 게시에 대해 스냅숏 에이전트 작업이 만들어집니다.

    보안 정보보안 정보

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

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

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

예(Transact-SQL)

다음 예에서는 트랜잭션 게시를 만듭니다. 스크립팅 변수는 스냅숏 에이전트 및 로그 판독기 에이전트에 대한 작업을 만드는 데 필요한 Windows 자격 증명을 전달하는 데 사용됩니다.

-- To avoid storing the login and password in the script file, the values 
-- are passed into SQLCMD as scripting variables. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks'; 
SET @publication = N'AdvWorksProductTran'; 
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login); 
-- This should be passed at runtime.
SET @password = $(Password); 

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

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

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

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

다음 예에서는 병합 게시를 만듭니다. 스크립팅 변수는 스냅숏 에이전트에 대한 작업을 만드는 데 필요한 Windows 자격 증명을 전달하는 데 사용됩니다.

-- To avoid storing the login and password in the script file, the value 
-- is passed into SQLCMD as a scripting variable. For information about 
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Declarations for adding a merge publication
DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks2012'; 
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 [AdventureWorks2012]
EXEC sp_addmergepublication 
-- These parameters are optional.
  @publication = @publication,
  -- optional parameters 
  @description = N'Merge publication of AdventureWorks2012.',
  @publication_compatibility_level  = N'110RTM';

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

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘[Top]

RMO(복제 관리 개체) 사용

RMO(복제 관리 개체)를 사용하여 프로그래밍 방식으로 게시를 만들 수 있습니다. 게시를 만드는 데 사용하는 RMO 클래스는 만드는 게시 유형에 따라 달라집니다.

스냅숏 또는 트랜잭션 게시를 만들려면

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

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

  3. EnabledTransPublishing 속성이 false이면 true로 설정합니다.

  4. 트랜잭션 게시에 대한 LogReaderAgentExists 속성의 값을 확인합니다. 이 속성이 true이면 이 데이터베이스에 대한 로그 판독기 에이전트 작업이 이미 존재하는 것입니다. 이 속성이 false이면 다음을 수행합니다.

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

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

    보안 정보보안 정보

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

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

병합 게시를 만들려면

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

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

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

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

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

    보안 정보보안 정보

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

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

예(RMO)

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

            // Set the Publisher, publication database, and publication names.
            string publicationName = "AdvWorksProductTran";
            string publicationDbName = "AdventureWorks2012";
            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 AdventureWorks2012 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 = "AdventureWorks2012"
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 AdventureWorks2012 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를 사용하여 병합 아티클을 정의하는 방법은 아티클 정의를 참조하십시오.

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

            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 = "AdventureWorks2012"

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

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘[Top]

참고 항목

개념

스크립팅 변수와 함께 sqlcmd 사용

데이터 및 데이터베이스 개체 게시

복제 관리 개체 개념

아티클 정의

게시 속성 보기 및 수정

배포 구성

배포자 보안 설정

게시자 보안 설정