Définir un articleDefine an Article

S’APPLIQUE À : ouiSQL Server nonAzure SQL Database nonAzure Synapse Analytics (SQL DW) nonParallel Data Warehouse APPLIES TO: yesSQL Server noAzure SQL Database noAzure Synapse Analytics (SQL DW) noParallel Data Warehouse

Cette rubrique explique comment définir un article dans SQL ServerSQL Server à l'aide de SQL Server Management StudioSQL Server Management Studio, de Transact-SQLTransact-SQL, ou des objets RMO (Replication Management Objects).This topic describes how to define an article in SQL ServerSQL Server by using SQL Server Management StudioSQL Server Management Studio, Transact-SQLTransact-SQL, or Replication Management Objects (RMO).

Dans cette rubriqueIn This Topic

Avant de commencerBefore You Begin

Limitations et restrictionsLimitations and Restrictions

  • Les noms d'article ne peuvent inclure aucun des caractères suivants : % , * , [ , ] , | , : , " , ?Article names cannot include any of the following characters: % , * , [ , ] , | , : , " , ? , ' , \ , / , < , >., ' , \ , / , < , >. Si des objets de la base de données incluent l'un de ces caractères et que vous souhaitez les répliquer, vous devez spécifier un nom d'article qui est différent du nom d'objet.If objects in the database include any of these characters and you want to replicate them, you must specify an article name that is different from the object name.

SécuritéSecurity

Lorsque c'est possible, demande aux utilisateurs de fournir les informations d'identification au moment de l'exécution.When possible, prompt users to enter security credentials at runtime. Si vous devez stocker des informations d'identification, utilisez les Services de chiffrement fournis par MicrosoftMicrosoft Windows .NET Framework.If you must store credentials, use the cryptographic services provided by the MicrosoftMicrosoft Windows .NET Framework.

Utilisation de SQL Server Management StudioUsing SQL Server Management Studio

Créez des publication et définissez des articles avec l'Assistant Nouvelle publication.Create publications and define articles with the New Publication Wizard. Après avoir créé une publication, affichez et modifiez les propriétés de publication dans la boîte de dialogue Propriétés de la publication - <Publication> .After a publication is created, view and modify publication properties in the Publication Properties - <Publication> dialog box. Pour plus d’informations sur la création d’une publication à partir d’une base de données Oracle, consultez Créer une publication à partir d’une base de données Oracle.For information about creating a publication from an Oracle database, see Create a Publication from an Oracle Database.

Pour créer une publication et définir des articlesTo create a publication and define articles

  1. Connectez-vous au serveur de publication dans MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio, puis développez le nœud du serveur.Connect to the Publisher in MicrosoftMicrosoft SQL Server Management StudioSQL Server Management Studio, and then expand the server node.

  2. Développez le dossier Réplication , puis cliquez avec le bouton droit sur le dossier Publications locales .Expand the Replication folder, and then right-click the Local Publications folder.

  3. Cliquez sur Nouvelle publication.Click New Publication.

  4. Exécutez les pages de l'Assistant Nouvelle publication pour.Follow the pages in the New Publication Wizard to:

    • Spécifier un serveur de distribution si la distribution n'a pas été configurée sur le serveur.Specify a Distributor if distribution has not been configured on the server. Pour plus d’informations sur la configuration de la distribution, consultez Configurer la publication et la distribution.For more information about configuring distribution, see Configure Publishing and Distribution.

      Si vous spécifiez dans la page Serveur de distribution que le serveur de publication se comportera comme son propre serveur de distribution (serveur de distribution local), et si ce serveur n'est pas configuré comme serveur de distribution, l'Assistant Nouvelle publication configurera ce serveur.If you specify on the Distributor page that the Publisher server will act as its own Distributor (a local Distributor), and the server is not configured as a Distributor, the New Publication Wizard will configure the server. Vous spécifierez un dossier d'instantanés par défaut pour le serveur de distribution dans la page Dossier d'instantanés .You will specify a default snapshot folder for the Distributor on the Snapshot Folder page. Le dossier d'instantanés correspond à un simple répertoire que vous définissez sous la forme d'un partage ; les agents qui lisent et écrivent dans le dossier doivent disposer des autorisations suffisantes pour pouvoir y accéder.The snapshot folder is simply a directory that you have designated as a share; agents that read from and write to this folder must have sufficient permissions to access it. Pour plus d’informations sur une sécurisation appropriée du dossier, consultez Sécuriser le dossier d’instantanés.For more information about securing the folder appropriately, see Secure the Snapshot Folder.

      Si vous spécifiez qu'un autre serveur doit jouer le rôle de serveur de distribution, vous devez entrer un mot de passe dans la page Mot de passe d'administration pour les connexions effectuées du serveur de publication sur le serveur de distribution.If you specify that another server should act as the Distributor, you must enter a password on the Administrative Password page for connections made from the Publisher to the Distributor. Ce mot de passe doit correspondre à celui qui a été spécifié lorsque le serveur de publication a été activé sur le serveur de distribution distant.This password must match the password specified when the Publisher was enabled at the remote Distributor.

      Pour plus d'informations, voir Configure Distribution.For more information, see Configure Distribution.

    • Choisissez une base de données de publication.Choose a publication database.

    • Sélectionnez un type de publication.Select a publication type. Pour plus d’informations, consultez Types de réplication.For more information, see Types of Replication.

    • Spécifiez les données et les objets de base de données à publier ; en option, filtrez les colonnes des articles des tables, et définissez des propriétés d'articles.Specify data and database objects to publish; optionally filter columns from table articles, and set article properties.

    • En option, filtrez les lignes des articles des tables.Optionally filter rows from table articles. Pour plus d’informations, consultez Filtrer des données publiées.For more information, see Filter Published Data.

    • Définissez la planification de l'Agent d'instantané.Set the Snapshot Agent schedule.

    • Spécifiez les informations de connexion sous lesquelles les Agents de réplication suivants s'exécuteront et se connecteront :Specify the credentials under which the following replication agents run and make connections:

      - Agent d’instantané pour toutes les publications.- Snapshot Agent for all publications.

      - Agent de lecture du journal pour toutes les publications transactionnelles.- Log Reader Agent for all transactional publications.

      - Agent de lecture de la file d’attente pour les publications transactionnelles acceptant les abonnements avec mise à jour.- Queue Reader Agent for transactional publications that allow updating subscriptions.

      Pour plus d'informations, consultez Replication Agent Security Model et Replication Security Best Practices.For more information, see Replication Agent Security Model and Replication Security Best Practices.

    • En option, scriptez la publication.Optionally script the publication. Pour plus d'informations, voir Scripting Replication.For more information, see Scripting Replication.

    • Spécifiez le nom de la publication.Specify a name for the publication.

Utilisation de Transact-SQLUsing Transact-SQL

Une fois une publication créée, des articles peuvent être créés par programme en utilisant des procédures stockées de réplication.After a publication has been created, articles can be created programmatically using replication stored procedures. Les procédures stockées utilisées pour créer un article dépendent du type de publication pour laquelle l'article est défini.The stored procedures used to create an article will depend on the type of publication for which the article is being defined. Pour plus d’informations, consultez créer une Publication.For more information, see Create a Publication.

Pour définir un article pour une publication transactionnelle ou d'instantanéTo define an article for a Snapshot or Transactional Publication

  1. Exécutez sp_addarticlesur la base de données de publication du serveur de publication.At the Publisher on the publication database, execute sp_addarticle. Spécifiez le nom de la publication à laquelle l’article appartient pour @publication, le nom de l’article pour @article, l’objet de base de données qui est publié pour @source_object, et tout autre paramètre optionnel.Specify the name of the publication to which the article belongs for @publication, a name for the article for @article, the database object being published for @source_object, and any other optional parameters. Utilisez @source_owner pour spécifier la propriété de schéma de l’objet, s’il ne s’agit pas de dbo.Use @source_owner to specify the schema ownership of the object, if not dbo. Si l’article n’est pas un article de table basé sur un journal, spécifiez le type d’article pour @type. Pour plus d’informations, consultez Spécifier les types d’articles (programmation Transact-SQL de la réplication).If the article is not a log-based table article, specify the article type for @type; for more information, see Specify Article Types (Replication Transact-SQL Programming).

  2. Pour filtrer horizontalement les lignes d'une table ou pour afficher un article, utilisez sp_articlefilter pour définir la clause du filtre.To horizontally filter rows in a table or view an article, use sp_articlefilter to define the filter clause. Pour plus d'informations, voir Définir et modifier un filtre de lignes statiques.For more information, see Define and Modify a Static Row Filter.

  3. Pour filtrer verticalement les colonnes d'une table ou afficher un article, utilisez sp_articlecolumn.To vertically filter columns in a table or view an article, use sp_articlecolumn. Pour plus d'informations, voir Définir et modifier un filtre de colonne.For more information, see Define and Modify a Column Filter.

  4. Exécutez sp_articleview si l'article est filtré.Execute sp_articleview if the article is filtered.

  5. Si la publication contient des abonnements existants et si sp_helppublication retourne la valeur 0 dans la colonne immediate_sync , vous devez appeler sp_addsubscription pour ajouter l'article à chaque abonnement existant.If the publication has existing subscriptions and sp_helppublication returns a value of 0 in the immediate_sync column, you must call sp_addsubscription to add the article to each existing subscription.

  6. Si la publication contient des abonnements par extraction existants, exécutez sp_refreshsubscriptions au niveau du serveur de publication de manière à créer un nouvel instantané pour les abonnements par extraction existants qui contient uniquement le nouvel article.If the publication has existing pull subscriptions, execute sp_refreshsubscriptions at the Publisher to create a new snapshot for existing pull subscriptions that contains just the new article.

    Notes

    Pour les abonnements qui ne sont pas initialisés à l'aide d'un instantané, vous n'avez pas besoin d'exécuter sp_refreshsubscriptions puisque cette procédure est exécutée par sp_addarticle.For subscriptions that are not initialized using a snapshot, you do not need to execute sp_refreshsubscriptions as this procedure is executed by sp_addarticle.

Pour définir un article pour une publication de fusionTo define an article for a Merge Publication

  1. Dans la base de données de publication sur le serveur de publication, exécutez sp_addmergearticle.At the Publisher on the publication database, execute sp_addmergearticle. Spécifiez le nom de la publication pour @publication, le nom de l’article pour @article et l’objet qui est publié pour @source_object.Specify the name of the publication for @publication, a name for the article name for @article, and the object being published for @source_object. Pour filtrer horizontalement les lignes d’une table, spécifiez une valeur pour @subset_filterclause.To horizontally filter table rows, specify a value for @subset_filterclause. Pour plus d'informations, consultez Définir et modifier un filtre de lignes paramétrable pour un article de fusion et Définir et modifier un filtre de lignes statiques.For more information, see Define and Modify a Parameterized Row Filter for a Merge Article and Define and Modify a Static Row Filter. Si l’article n’est pas un article de table, spécifiez le type d’article pour @type.If the article is not a table article, specify the article type for @type. Pour plus d’informations, consultez Spécifier les types d’articles (programmation Transact-SQL de la réplication).For more information, see Specify Article Types (Replication Transact-SQL Programming).

  2. (Facultatif) Dans la base de données de publication sur le serveur de publication, exécutez sp_addmergefilter pour définir un filtre de jointure entre deux articles.(Optional) At the Publisher on the publication database, execute sp_addmergefilter to define a join filter between two articles. Pour plus d'informations, voir Définir et modifier un filtre de jointure entre des articles de fusion.For more information, see Define and Modify a Join Filter Between Merge Articles.

  3. (Facultatif) Dans la base de données de publication sur le serveur de publication, exécutez sp_mergearticlecolumn pour filtrer les colonnes d'une table.(Optional) At the Publisher on the publication database, execute sp_mergearticlecolumn to filter table columns. Pour plus d'informations, voir Définir et modifier un filtre de colonne.For more information, see Define and Modify a Column Filter.

Exemples (Transact-SQL)Examples (Transact-SQL)

Cet exemple définit un article basé sur la table Product pour une publication transactionnelle, où l'article est filtré à la fois horizontalement et verticalement.This example defines an article based on the Product table for a transactional publication, where the article is filtered both horizontally and vertically.

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

Cet exemple définit des articles pour une publication de fusion, où l'article SalesOrderHeader est filtré statiquement sur SalesPersonIDet où l'article SalesOrderDetail est filtré avec un filtre de jointure sur SalesOrderHeader.This example defines articles for a merge publication, where the SalesOrderHeader article is statically filtered based on SalesPersonID, and the SalesOrderDetail article is join filtered based on 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

Utilisation d'objets RMO (Replication Management Objects)Using Replication Management Objects (RMO)

Vous pouvez définir des articles par programme à l'aide d'objets RMO (Replication Management Objects).You can define articles programmatically by using Replication Management Objects (RMO). Les classes RMO que vous utilisez pour définir un article dépendent du type de publication pour lequel l'article est défini.The RMO classes that you use to define an article depend on the type of publication for which the article is defined.

Exemples (RMO)Examples (RMO)

L'exemple suivant ajoute un article avec des filtres des lignes et de colonnes à une publication transactionnelle.The following example adds an article with row and column filters to a transactional publication.

// Define the Publisher, publication, and article names.
string publisherName = publisherInstance;
string publicationName = "AdvWorksProductTran";
string publicationDbName = "AdventureWorks2012";
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 = "AdventureWorks2012"
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

L'exemple suivant ajoute trois articles à une publication de fusion.The following example adds three articles to a merge publication. Ces articles ont des filtres de colonnes, et deux filtres de jointure sont utilisés pour propager un filtre de lignes paramétrable aux autres articles.The articles have column filters, and two join filters are used to propagate a parameterized row filter to the other articles.

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

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

' 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

Voir aussiSee Also

Create a Publication Create a Publication
Concepts liés aux procédures stockées système de réplication Replication System Stored Procedures Concepts
Ajouter et supprimer des articles de publications existantes Add Articles to and Drop Articles from Existing Publications
Filtrer des données publiées Filter Published Data
Publier des données et des objets de base de données Publish Data and Database Objects
Replication System Stored Procedures ConceptsReplication System Stored Procedures Concepts