定義發行項

適用於:SQL Server

本主題說明如何使用 SQL Server Management Studio、Transact-SQL 或 Replication Management Objects (RMO),在 SQL Server 中定義發行項。

本主題內容

開始之前

限制事項

  • 發行項名稱不能包含下列任何字元:% , * , [ , ] , | , : , " , ? 、 ' 、 \ 、 / 、 < 、 >。 如果資料庫中的物件包含這些字元的任何一個,而且您要複寫它們,則必須指定一個不同於物件名稱的發行項名稱。

安全性

可能的話,會在執行階段提示使用者輸入安全性認證。 如果您必須儲存認證,請使用 Microsoft Windows .NET Framework 提供的密碼編譯服務

使用 SQL Server Management Studio

使用「新增發行集精靈」建立發行集並定義發行項。 建立發行集之後,您可以在 [發行集屬性 - <發行集>] 對話方塊中,檢視及修改發行集屬性。 如需從 Oracle 資料庫建立發行集的詳細資訊,請參閱從 Oracle 資料庫建立發行集

建立發行集並定義發行項

  1. 連線到 Microsoft SQL Server Management Studio 中的發行者,然後展開伺服器節點。

  2. 展開 [複寫] 資料夾,然後以滑鼠右鍵按一下 [本機發行集] 資料夾。

  3. 按一下 [新增發行集]

  4. 遵循「新增發行集精靈」中的頁面,執行:

    • 如果尚未在伺服器上設定散發,則請指定「散發者」。 如需設定散發的詳細資訊,請參閱設定發行和散發

      如果在 [散發者] 頁面指定「發行者」伺服器做為自己的「散發者」(本機散發者),而不將伺服器設定為「散發者」,則「新增發行集精靈」會設定該伺服器。 您將在 [快照集資料夾] 頁面,為「散發者」指定預設快照集資料夾。 快照集資料夾只是指定為共用的目錄;讀取並寫入此資料夾的代理程式必須具有足夠的權限才能對其進行存取。 如需適當地保護資料夾的詳細資訊,請參閱保護快照集資料夾

      如果指定另一台伺服器扮演「散發者」角色,則必須在 [管理密碼] 頁面輸入密碼才能從「發行者」連接到「散發者」。 此密碼必須符合發行者於遠端散發者啟用時所指定的密碼。

      如需詳細資訊,請參閱 Configure Distribution>。

    • 選擇發行集資料庫。

    • 選取發行集類型。 如需詳細資訊,請參閱複寫類型

    • 指定要發行的資料和資料庫物件;從資料表發行項選擇性地篩選資料行,並設定發行項屬性。

    • 從資料表發行項中選擇性地篩選資料列。 如需詳細資訊,請參閱篩選發行的資料

    • 設定「快照集代理程式」的排程。

    • 指定下列複寫代理程式執行時使用的認證,並建立連接:

      - 所有發行集的快照集代理程式。

      - 所有交易式發行集的記錄讀取器代理程式。

      - 允許更新訂閱的交易式發行集之佇列讀取器代理程式。

      如需相關資訊,請參閱 Replication Agent Security Model 以及 Replication Security Best Practices

    • 選擇性地編寫發行集的指令碼。 如需詳細資訊,請參閱 Scripting Replication

    • 指定發行集的名稱。

使用 TRANSACT-SQL

在建立發行集之後,可以使用複寫預存程序來以程式設計的方式建立發行項。 要使用哪些預存程序來建立發行項,將取決於定義此發行項的發行集類型而定。 如需詳細資訊,請參閱建立發行集

為快照式或交易式發行集定義發行項

  1. 在發行集資料庫的發行者上,執行 sp_addarticle。 針對 @publication 指定發行項所屬發行集名稱、 針對 @article 指定發行項名稱、針對 @source_object 指定正在發行的資料庫物件,以及指定其他任何選擇性參數。 使用 @source_owner 來指定此物件的結構描述擁有權 (如果不是 dbo。 如果此發行項不是記錄式資料表發行項,請針對 @type 指定發行項類型;如需詳細資訊,請參閱指定發行項類型 (Transact-SQL 程式設計)

  2. 若要以水平方式篩選資料表中的資料列或是檢視發行項,請使用 sp_articlefilter 來定義篩選子句。 如需詳細資訊,請參閱 Define and Modify a Static Row Filter

  3. 若要以垂直方式篩選資料表中的資料行或是檢視發行項,請使用 sp_articlecolumn。 如需詳細資訊,請參閱 Define and Modify a Column Filter

  4. 如果發行項已經過篩選,請執行 sp_articleview

  5. 如果發行集有現有的訂閱,而且 sp_helppublicationimmediate_sync 資料行中傳回 0 的值,您就必須呼叫 sp_addsubscription ,將此發行項加入到每一個現有的訂閱中。

  6. 如果發行集有現有的提取訂閱,請在發行者上執行 sp_refreshsubscriptions ,針對只包含新發行項的現有提取訂閱建立新的快照集。

    注意

    如果是未使用快照集初始化的訂閱,您就不需要執行 sp_refreshsubscriptions ,因為這個程序是由 sp_addarticle所執行。

為合併式發行集定義發行項

  1. 在發行集資料庫的發行者上,執行 sp_addmergearticle。 針對 @publication 指定發行集的名稱、針對 @article 指定發行項的名稱,以及針對 @source_object 指定發行的物件。 若要以水平方式篩選資料表資料列,請指定 @subset_filterclause 的值。 如需相關資訊,請參閱 針對合併發行項定義及修改參數化資料列篩選 以及 定義及修改靜態資料列篩選。 如果此發行項不是資料表發行項,請針對 @type 指定發行項類型。 如需詳細資訊,請參閱指定發行項類型 (複寫 Transact-SQL 程式設計)

  2. (選擇性) 在發行集資料庫的發行者上,執行 sp_addmergefilter ,以定義兩個發行項之間的聯結篩選。 如需詳細資訊,請參閱 定義和修改合併發行項之間的聯結篩選

  3. (選擇性) 在發行集資料庫的發行者上,執行 sp_mergearticlecolumn ,以篩選資料表資料行。 如需詳細資訊,請參閱 Define and Modify a Column Filter

範例 (Transact-SQL)

此範例是根據交易式發行集的 Product 資料表來定義發行項,其中會以水平和垂直方式篩選發行項。

DECLARE @publication    AS sysname;
DECLARE @table AS sysname;
DECLARE @filterclause AS nvarchar(500);
DECLARE @filtername AS nvarchar(386);
DECLARE @schemaowner AS sysname;
SET @publication = N'AdvWorksProductTran'; 
SET @table = N'Product';
SET @filterclause = N'[DiscontinuedDate] IS NULL'; 
SET @filtername = N'filter_out_discontinued';
SET @schemaowner = N'Production';

-- Add a horizontally and vertically filtered article for the Product table.
-- Manually set @schema_option to ensure that the Production schema 
-- is generated at the Subscriber (0x8000000).
EXEC sp_addarticle 
    @publication = @publication, 
    @article = @table, 
    @source_object = @table,
    @source_owner = @schemaowner, 
    @schema_option = 0x80030F3,
    @vertical_partition = N'true', 
    @type = N'logbased',
    @filter_clause = @filterclause;

-- (Optional) Manually call the stored procedure to create the 
-- horizontal filtering stored procedure. Since the type is 
-- 'logbased', this stored procedures is executed automatically.
EXEC sp_articlefilter 
    @publication = @publication, 
    @article = @table, 
    @filter_clause = @filterclause, 
    @filter_name = @filtername;

-- Add all columns to the article.
EXEC sp_articlecolumn 
    @publication = @publication, 
    @article = @table;

-- Remove the DaysToManufacture column from the article
EXEC sp_articlecolumn 
    @publication = @publication, 
    @article = @table, 
    @column = N'DaysToManufacture', 
    @operation = N'drop';

-- (Optional) Manually call the stored procedure to create the 
-- vertical filtering view. Since the type is 'logbased', 
-- this stored procedures is executed automatically.
EXEC sp_articleview 
    @publication = @publication, 
    @article = @table,
    @filter_clause = @filterclause;
GO

此範例會定義合併式發行集的發行項,其中的 SalesOrderHeader 發行項是根據 SalesPersonID進行靜態篩選,而 SalesOrderDetail 發行項則是根據 SalesOrderHeader進行聯結篩選。

DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @table3 AS sysname;
DECLARE @salesschema AS sysname;
DECLARE @hrschema AS sysname;
DECLARE @filterclause AS nvarchar(1000);
SET @publication = N'AdvWorksSalesOrdersMerge'; 
SET @table1 = N'Employee'; 
SET @table2 = N'SalesOrderHeader'; 
SET @table3 = N'SalesOrderDetail'; 
SET @salesschema = N'Sales';
SET @hrschema = N'HumanResources';
SET @filterclause = N'Employee.LoginID = HOST_NAME()';

-- Add a filtered article for the Employee table.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_object = @table1, 
  @type = N'table', 
  @source_owner = @hrschema,
  @schema_option = 0x0004CF1,
  @description = N'article for the Employee table',
  @subset_filterclause = @filterclause;

-- Add an article for the SalesOrderHeader table that is filtered
-- based on Employee and horizontally filtered.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_object = @table2, 
  @type = N'table', 
  @source_owner = @salesschema, 
  @vertical_partition = N'true',
  @schema_option = 0x0034EF1,
  @description = N'article for the SalesOrderDetail table';

-- Add an article for the SalesOrderDetail table that is filtered
-- based on SaledOrderHeader.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table3, 
  @source_object = @table3, 
  @source_owner = @salesschema,
  @description = 'article for the SalesOrderHeader table', 
  @identityrangemanagementoption = N'auto', 
  @pub_identity_range = 100000, 
  @identity_range = 100, 
  @threshold = 80,
  @schema_option = 0x0004EF1;

-- Add all columns to the SalesOrderHeader article.
EXEC sp_mergearticlecolumn 
  @publication = @publication, 
  @article = @table2, 
  @force_invalidate_snapshot = 1, 
  @force_reinit_subscription = 1;

-- Remove the credit card Approval Code column.
EXEC sp_mergearticlecolumn 
  @publication = @publication, 
  @article = @table2, 
  @column = N'CreditCardApprovalCode', 
  @operation = N'drop', 
  @force_invalidate_snapshot = 1, 
  @force_reinit_subscription = 1;

-- Add a merge join filter between Employee and SalesOrderHeader.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table2, 
  @filtername = N'SalesOrderHeader_Employee', 
  @join_articlename = @table1, 
  @join_filterclause = N'Employee.BusinessEntityID = SalesOrderHeader.SalesPersonID', 
  @join_unique_key = 1, 
  @filter_type = 1, 
  @force_invalidate_snapshot = 1, 
  @force_reinit_subscription = 1;

-- Add a merge join filter between SalesOrderHeader and SalesOrderDetail.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table3, 
  @filtername = N'SalesOrderDetail_SalesOrderHeader', 
  @join_articlename = @table2, 
  @join_filterclause = N'SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID', 
  @join_unique_key = 1, 
  @filter_type = 1, 
  @force_invalidate_snapshot = 1, 
  @force_reinit_subscription = 1;
GO

使用 Replication Management Objects (RMO)

您可以使用 Replication Management Objects (RMO) 以程式設計的方式定義發行項。 用於定義發行項的 RMO 類別,將取決於定義發行項的發行集類型而定。

範例 (RMO)

下列範例會將具有資料列篩選和資料行篩選的發行項加入交易式發行集中。

// Define the Publisher, publication, and article names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksProductTran";
string publicationDbName = "AdventureWorks2022";
string articleName = "Product";
string schemaOwner = "Production";

TransArticle article;

// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);

// Create a filtered transactional articles in the following steps:
// 1) Create the  article with a horizontal filter clause.
// 2) Add columns to or remove columns from the article.
try
{
    // Connect to the Publisher.
    conn.Connect();

    // Define a horizontally filtered, log-based table article.
    article = new TransArticle();
    article.ConnectionContext = conn;
    article.Name = articleName;
    article.DatabaseName = publicationDbName;
    article.SourceObjectName = articleName;
    article.SourceObjectOwner = schemaOwner;
    article.PublicationName = publicationName;
    article.Type = ArticleOptions.LogBased;
    article.FilterClause = "DiscontinuedDate IS NULL";

    // Ensure that we create the schema owner at the Subscriber.
    article.SchemaOption |= CreationScriptOptions.Schema;

    if (!article.IsExistingObject)
    {
        // Create the article.
        article.Create();
    }
    else
    {
        throw new ApplicationException(String.Format(
            "The article {0} already exists in publication {1}.",
            articleName, publicationName));
    }

    // Create an array of column names to remove from the article.
    String[] columns = new String[1];
    columns[0] = "DaysToManufacture";

    // Remove the column from the article.
    article.RemoveReplicatedColumns(columns);
}
catch (Exception ex)
{
    // Implement appropriate error handling here.
    throw new ApplicationException("The article could not be created.", ex);
}
finally
{
    conn.Disconnect();
}
' Define the Publisher, publication, and article names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksProductTran"
Dim publicationDbName As String = "AdventureWorks2022"
Dim articleName As String = "Product"
Dim schemaOwner As String = "Production"

Dim article As TransArticle

' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

' Create a filtered transactional articles in the following steps:
' 1) Create the  article with a horizontal filter clause.
' 2) Add columns to or remove columns from the article.
Try
    ' Connect to the Publisher.
    conn.Connect()

    ' Define a horizontally filtered, log-based table article.
    article = New TransArticle()
    article.ConnectionContext = conn
    article.Name = articleName
    article.DatabaseName = publicationDbName
    article.SourceObjectName = articleName
    article.SourceObjectOwner = schemaOwner
    article.PublicationName = publicationName
    article.Type = ArticleOptions.LogBased
    article.FilterClause = "DiscontinuedDate IS NULL"

    ' Ensure that we create the schema owner at the Subscriber.
    article.SchemaOption = article.SchemaOption Or _
    CreationScriptOptions.Schema

    If Not article.IsExistingObject Then
        ' Create the article.
        article.Create()
    Else
        Throw New ApplicationException(String.Format( _
         "The article {0} already exists in publication {1}.", _
         articleName, publicationName))
    End If

    ' Create an array of column names to remove from the article.
    Dim columns() As String = New String(0) {}
    columns(0) = "DaysToManufacture"

    ' Remove the column from the article.
    article.RemoveReplicatedColumns(columns)
Catch ex As Exception
    ' Implement appropriate error handling here.
    Throw New ApplicationException("The article could not be created.", ex)
Finally
    conn.Disconnect()
End Try

下列範例會將三個發行項加入合併式發行集中。 這些發行項具有資料行篩選,而且會使用兩個聯結篩選將參數化資料列篩選器列傳播至其他發行項。

// Define the Publisher and publication names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksSalesOrdersMerge";
string publicationDbName = "AdventureWorks2022";

// Specify article names.
string articleName1 = "Employee";
string articleName2 = "SalesOrderHeader";
string articleName3 = "SalesOrderDetail";

// Specify join filter information.
string filterName12 = "SalesOrderHeader_Employee";
string filterClause12 = "Employee.EmployeeID = " +
    "SalesOrderHeader.SalesPersonID";
string filterName23 = "SalesOrderDetail_SalesOrderHeader";
string filterClause23 = "SalesOrderHeader.SalesOrderID = " +
    "SalesOrderDetail.SalesOrderID";

string salesSchema = "Sales";
string hrSchema = "HumanResources";

MergeArticle article1 = new MergeArticle();
MergeArticle article2 = new MergeArticle();
MergeArticle article3 = new MergeArticle();
MergeJoinFilter filter12 = new MergeJoinFilter();
MergeJoinFilter filter23 = new MergeJoinFilter();

// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);

// Create three merge articles that are horizontally partitioned
// using a parameterized row filter on Employee.EmployeeID, which is 
// extended to the two other articles using join filters. 
try
{
    // Connect to the Publisher.
    conn.Connect();

    // Create each article. 
    // For clarity, each article is defined separately. 
    // In practice, iterative structures and arrays should 
    // be used to efficiently create multiple articles.

    // Set the required properties for the Employee article.
    article1.ConnectionContext = conn;
    article1.Name = articleName1;
    article1.DatabaseName = publicationDbName;
    article1.SourceObjectName = articleName1;
    article1.SourceObjectOwner = hrSchema;
    article1.PublicationName = publicationName;
    article1.Type = ArticleOptions.TableBased;

    // Define the parameterized filter clause based on Hostname.
    article1.FilterClause = "Employee.LoginID = HOST_NAME()";

    // Set the required properties for the SalesOrderHeader article.
    article2.ConnectionContext = conn;
    article2.Name = articleName2;
    article2.DatabaseName = publicationDbName;
    article2.SourceObjectName = articleName2;
    article2.SourceObjectOwner = salesSchema;
    article2.PublicationName = publicationName;
    article2.Type = ArticleOptions.TableBased;

    // Set the required properties for the SalesOrderDetail article.
    article3.ConnectionContext = conn;
    article3.Name = articleName3;
    article3.DatabaseName = publicationDbName;
    article3.SourceObjectName = articleName3;
    article3.SourceObjectOwner = salesSchema;
    article3.PublicationName = publicationName;
    article3.Type = ArticleOptions.TableBased;

    if (!article1.IsExistingObject) article1.Create();
    if (!article2.IsExistingObject) article2.Create();
    if (!article3.IsExistingObject) article3.Create();

    // Select published columns for SalesOrderHeader.
    // Create an array of column names to vertically filter out.
    // In this example, only one column is removed.
    String[] columns = new String[1];

    columns[0] = "CreditCardApprovalCode";

    // Remove the column.
    article2.RemoveReplicatedColumns(columns);

    // Define a merge filter clauses that filter 
    // SalesOrderHeader based on Employee and 
    // SalesOrderDetail based on SalesOrderHeader. 

    // Parent article.
    filter12.JoinArticleName = articleName1;
    // Child article.
    filter12.ArticleName = articleName2;
    filter12.FilterName = filterName12;
    filter12.JoinUniqueKey = true;
    filter12.FilterTypes = FilterTypes.JoinFilter;
    filter12.JoinFilterClause = filterClause12;

    // Add the join filter to the child article.
    article2.AddMergeJoinFilter(filter12);

    // Parent article.
    filter23.JoinArticleName = articleName2;
    // Child article.
    filter23.ArticleName = articleName3;
    filter23.FilterName = filterName23;
    filter23.JoinUniqueKey = true;
    filter23.FilterTypes = FilterTypes.JoinFilter;
    filter23.JoinFilterClause = filterClause23;

    // Add the join filter to the child article.
    article3.AddMergeJoinFilter(filter23);
}
catch (Exception ex)
{
    // Do error handling here and rollback the transaction.
    throw new ApplicationException(
        "The filtered articles could not be created", ex);
}
finally
{
    conn.Disconnect();
}
' Define the Publisher and publication names.
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2022"

' Specify article names.
Dim articleName1 As String = "Employee"
Dim articleName2 As String = "SalesOrderHeader"
Dim articleName3 As String = "SalesOrderDetail"

' Specify join filter information.
Dim filterName12 As String = "SalesOrderHeader_Employee"
Dim filterClause12 As String = "Employee.EmployeeID = " + _
    "SalesOrderHeader.SalesPersonID"
Dim filterName23 As String = "SalesOrderDetail_SalesOrderHeader"
Dim filterClause23 As String = "SalesOrderHeader.SalesOrderID = " + _
    "SalesOrderDetail.SalesOrderID"

Dim salesSchema As String = "Sales"
Dim hrSchema As String = "HumanResources"

Dim article1 As MergeArticle = New MergeArticle()
Dim article2 As MergeArticle = New MergeArticle()
Dim article3 As MergeArticle = New MergeArticle()
Dim filter12 As MergeJoinFilter = New MergeJoinFilter()
Dim filter23 As MergeJoinFilter = New MergeJoinFilter()

' Create a connection to the Publisher.
Dim conn As ServerConnection = New ServerConnection(publisherName)

' Create three merge articles that are horizontally partitioned
' using a parameterized row filter on Employee.EmployeeID, which is 
' extended to the two other articles using join filters. 
Try
    ' Connect to the Publisher.
    conn.Connect()

    ' Create each article. 
    ' For clarity, each article is defined separately. 
    ' In practice, iterative structures and arrays should 
    ' be used to efficiently create multiple articles.

    ' Set the required properties for the Employee article.
    article1.ConnectionContext = conn
    article1.Name = articleName1
    article1.DatabaseName = publicationDbName
    article1.SourceObjectName = articleName1
    article1.SourceObjectOwner = hrSchema
    article1.PublicationName = publicationName
    article1.Type = ArticleOptions.TableBased

    ' Define the parameterized filter clause based on Hostname.
    article1.FilterClause = "Employee.LoginID = HOST_NAME()"

    ' Set the required properties for the SalesOrderHeader article.
    article2.ConnectionContext = conn
    article2.Name = articleName2
    article2.DatabaseName = publicationDbName
    article2.SourceObjectName = articleName2
    article2.SourceObjectOwner = salesSchema
    article2.PublicationName = publicationName
    article2.Type = ArticleOptions.TableBased

    ' Set the required properties for the SalesOrderDetail article.
    article3.ConnectionContext = conn
    article3.Name = articleName3
    article3.DatabaseName = publicationDbName
    article3.SourceObjectName = articleName3
    article3.SourceObjectOwner = salesSchema
    article3.PublicationName = publicationName
    article3.Type = ArticleOptions.TableBased

    ' Create the articles, if they do not already exist.
    If article1.IsExistingObject = False Then
        article1.Create()
    End If
    If article2.IsExistingObject = False Then
        article2.Create()
    End If
    If article3.IsExistingObject = False Then
        article3.Create()
    End If

    ' Select published columns for SalesOrderHeader.
    ' Create an array of column names to vertically filter out.
    ' In this example, only one column is removed.
    Dim columns() As String = New String(0) {}

    columns(0) = "CreditCardApprovalCode"

    ' Remove the column.
    article2.RemoveReplicatedColumns(columns)

    ' Define a merge filter clauses that filter 
    ' SalesOrderHeader based on Employee and 
    ' SalesOrderDetail based on SalesOrderHeader. 

    ' Parent article.
    filter12.JoinArticleName = articleName1
    ' Child article.
    filter12.ArticleName = articleName2
    filter12.FilterName = filterName12
    filter12.JoinUniqueKey = True
    filter12.FilterTypes = FilterTypes.JoinFilter
    filter12.JoinFilterClause = filterClause12

    ' Add the join filter to the child article.
    article2.AddMergeJoinFilter(filter12)

    ' Parent article.
    filter23.JoinArticleName = articleName2
    ' Child article.
    filter23.ArticleName = articleName3
    filter23.FilterName = filterName23
    filter23.JoinUniqueKey = True
    filter23.FilterTypes = FilterTypes.JoinFilter
    filter23.JoinFilterClause = filterClause23

    ' Add the join filter to the child article.
    article3.AddMergeJoinFilter(filter23)

Catch ex As Exception
    ' Do error handling here and rollback the transaction.
    Throw New ApplicationException( _
        "The filtered articles could not be created", ex)
Finally
    conn.Disconnect()
End Try

另請參閱

建立發行集
Replication System Stored Procedures Concepts
在現有發行集中加入和卸除發行項
篩選發行的資料
發行資料和資料庫物件
Replication System Stored Procedures Concepts