为包含参数化筛选器的合并发布创建快照

本主题说明如何使用 SQL Server Management Studio、Transact-SQL 或复制管理对象 (RMO) 在 SQL Server 2012 中通过参数化筛选器为合并发布创建快照。

本主题内容

  • 开始之前:

    建议

  • 通过参数化筛选器为合并发布创建快照,使用:

    SQL Server Management Studio

    Transact-SQL

    复制管理对象 (RMO)

开始之前

建议

  • 在使用参数化筛选器为合并发布生成快照时,必须先生成一个包含所有已发布数据和订阅的订阅服务器元数据的标准(架构)快照。 有关详细信息,请参阅创建并应用初始快照。 创建完架构快照后,便可生成包含特定于订阅服务器的已发布数据分区的快照。

  • 如果发布中对一个或多个项目的筛选生成了对每个订阅具有唯一性的非重叠分区,则每当运行合并代理时都会清除元数据。 这意味着分区快照会过期得更快。 使用此选项时,应考虑允许订阅服务器启动快照的生成和传送。 有关筛选选项的详细信息,请参阅带有参数化筛选器的合并发布的快照中的“设置‘分区选项’”部分。

用于“返回首页”链接的箭头图标[Top]

使用 SQL Server Management Studio

可以在**“发布属性 - <发布>”对话框的“数据分区”**页上生成分区的快照。 有关访问此对话框的详细信息,请参阅查看和修改发布属性。 可以允许订阅服务器启动快照生成及传送和/或生成快照。

生成一个或多个分区的快照之前,必须:

  1. 使用新建发布向导创建合并发布,并在该向导的**“添加筛选器”**页上指定一个或多个参数化行筛选器。 有关详细信息,请参阅定义和修改合并项目的参数化行筛选器

  2. 生成发布的架构快照。 默认情况下,架构快照在完成新建发布向导时生成;您也可以从 SQL Server Management Studio 中生成架构快照。

生成架构快照

  1. 在 Management Studio 中,连接到发布服务器,然后展开服务器节点。

  2. 展开**“复制”文件夹,再展开“发布”**文件夹。

  3. 右键单击要为其创建快照的发布,然后单击**“查看快照代理状态”**。

  4. 在**“查看快照代理状态 - <发布>”对话框中,单击“启动”**。

    快照代理生成快照后,将显示一条消息,例如“[100%] 已生成 17 个项目的快照”。

允许订阅服务器启动快照生成和传送

  1. 在**“发布属性 - <发布>”对话框的“数据分区”页上,选择“在新订阅服务器尝试同步时,根据需要自动定义分区并生成快照”**。

  2. 单击“确定”。

生成和刷新快照

  1. 在**“发布属性 - <发布>”对话框的“数据分区”页上,单击“添加”**。

  2. 为与要为其创建快照的分区关联的 HOST_NAME() 和/或 SUSER_SNAME() 输入一个值。

  3. 还可以指定快照刷新计划:

    1. 选择**“安排此分区的快照代理在以下时间运行”**

    2. 接受默认的快照刷新计划,或者单击**“更改”**指定其他计划。

  4. 单击**“确定”,返回到“发布属性 - <发布>”**对话框。

  5. 在属性网格中选择分区,然后单击**“立即生成所选快照”**。

  6. 单击“确定”。

用于“返回首页”链接的箭头图标[Top]

使用 Transact-SQL

使用存储过程和快照代理,您可以执行以下操作:

  • 允许订阅服务器在第一次同步时请求快照生成和应用。

  • 为每个分区预生成快照。

  • 手动为每个订阅服务器生成快照。

    安全说明安全说明

    如果可能,请在运行时提示用户输入安全凭据。 如果必须在脚本文件中存储凭据,则必须保护文件以防止未经授权的访问。

创建允许订阅服务器启动快照生成和传递的发布

  1. 在发布服务器上,对发布数据库执行 sp_addmergepublication (Transact-SQL)。 指定下列参数:

    • @publication 指定为发布的名称。

    • 将 true 值指定为 @allow_subscriber_initiated_snapshot,这样可使订阅服务器启动快照进程。

    • (可选)将 @max_concurrent_dynamic_snapshots 指定为可并发运行的动态快照进程数。 如果正在运行的进程数达到了最大值,并且订阅服务器尝试生成快照,则该进程将被置于队列中。 默认情况下,并发进程的数量不受限制。

  2. 在发布服务器中,执行 sp_addpublication_snapshot (Transact-SQL)。 将 @publication 指定为在步骤 1 中使用的发布名称,并将 @job_login@password 指定为用于运行复制快照代理的 Microsoft Windows 凭据。 如果代理在连接到发布服务器时将使用 SQL Server 身份验证,则还必须将 @publisher_security_mode 的值指定为 0,并为 @publisher_login@publisher_password 指定 Microsoft SQL Server 登录信息。 此操作将为发布创建一个快照代理作业。 有关生成初始快照以及为快照代理定义自定义计划的详细信息,请参阅创建并应用初始快照

    安全说明安全说明

    使用远程分发服务器配置发布服务器时,为所有参数提供的值(包括 job_login 和 job_password)都会以纯文本方式发送到该分发服务器。 在执行此存储过程之前,应该对发布服务器及其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅启用数据库引擎的加密连接(SQL Server 配置管理器)

  3. 执行 sp_addmergearticle (Transact-SQL) 以向发布添加项目。 必须对发布中的每个项目执行一次此存储过程。 使用参数化筛选器时,必须使用 @subset_filterclause 参数为一个或多个项目指定参数化行筛选器。 有关详细信息,请参阅定义和修改合并项目的参数化行筛选器

  4. 如果将基于该参数化行筛选器筛选其他项目,请执行 sp_addmergefilter (Transact-SQL) 以定义项目间的联接或逻辑记录关系。 必须对要定义的每个关系执行一次此存储过程。 有关详细信息,请参阅定义和修改合并项目间的联接筛选器

  5. 当合并代理请求快照初始化订阅服务器时,将自动生成请求订阅的分区的快照。

创建发布并预生成或自动刷新快照

  1. 执行 sp_addmergepublication (Transact-SQL) 以创建发布。 有关详细信息,请参阅创建发布

  2. 在发布服务器中,执行 sp_addpublication_snapshot (Transact-SQL)。 指定在步骤 1 中对 @publication 使用的发布名称以及快照代理针对 @job_login@password 运行的 Windows 凭据。 如果代理在连接到发布服务器时将使用 SQL Server 身份验证,则还必须将 @publisher_security_mode 的值指定为 0,并为 @publisher_login@publisher_password 指定 SQL Server 登录信息。 此操作将为发布创建一个快照代理作业。 有关生成初始快照以及为快照代理定义自定义计划的详细信息,请参阅创建并应用初始快照

    安全说明安全说明

    使用远程分发服务器配置发布服务器时,为所有参数提供的值(包括 job_login 和 job_password)都会以纯文本方式发送到该分发服务器。 在执行此存储过程之前,应该对发布服务器及其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅启用数据库引擎的加密连接(SQL Server 配置管理器)

  3. 执行 sp_addmergearticle (Transact-SQL) 以向发布添加项目。 必须对发布中的每个项目执行一次此存储过程。 使用参数化筛选器时,必须使用 @subset_filterclause 参数为一个项目指定参数化行筛选器。 有关详细信息,请参阅定义和修改合并项目的参数化行筛选器

  4. 如果将基于该参数化行筛选器筛选其他项目,请执行 sp_addmergefilter (Transact-SQL) 以定义项目间的联接或逻辑记录关系。 必须对要定义的每个关系执行一次此存储过程。 有关详细信息,请参阅定义和修改合并项目间的联接筛选器

  5. 在发布服务器上的发布数据库中执行 sp_helpmergepublication (Transact-SQL),并指定步骤 1 中的 @publication 的值。 请注意结果集中的 snapshot_jobid 值。

  6. 将步骤 5 中得到的 snapshot_jobid 的值转换为 uniqueidentifier

  7. msdb 数据库的发布服务器上,执行 sp_start_job (Transact-SQL),将 @job_id 指定为在步骤 6 中得到的转换后的值。

  8. 在发布服务器的发布数据库中,执行 sp_addmergepartition (Transact-SQL)。 将 @publication 指定为来自步骤 1 的发布名称,并将 @suser_sname(如果在筛选子句中使用 SUSER_SNAME (Transact-SQL))或 @host_name(如果在筛选子句中使用 HOST_NAME (Transact-SQL))指定为用于定义分区的值。

  9. 在发布数据库的发布服务器上,执行 sp_adddynamicsnapshot_job (Transact-SQL)。 将 @publication 指定为来自步骤 1 的发布名称,并将 @suser_sname@host_name 指定为来自步骤 8 的值,同时为作业指定一个计划。 此操作将创建为指定分区生成参数化快照的作业。 有关详细信息,请参阅指定同步计划

    注意注意

    使用在步骤 2 中定义的初始快照作业的 Windows 帐户运行此作业。 若要删除参数化快照作业及其相关的数据分区,请执行 sp_dropdynamicsnapshot_job (Transact-SQL)

  10. 在发布服务器上的发布数据库中执行 sp_helpmergepartition (Transact-SQL),从步骤 1 指定 @publication 的值并从步骤 8 指定 @suser_sname@host_name 的值。 请注意结果集中的 dynamic_snapshot_jobid 值。

  11. msdb 数据库的分发服务器上,执行 sp_start_job (Transact-SQL),将 @job_id 指定为在步骤 9 中获得的值。 此操作将启动分区的参数化快照作业。

  12. 重复步骤 8-11,分别为每个订阅生成一个分区快照。

创建发布并为每个分区手动创建快照

  1. 执行 sp_addmergepublication (Transact-SQL) 以创建发布。 有关详细信息,请参阅创建发布

  2. 在发布服务器中,执行 sp_addpublication_snapshot (Transact-SQL)。 指定在步骤 1 中对 @publication 使用的发布名称以及快照代理针对 @job_login@password 运行的 Windows 凭据。 如果代理在连接到发布服务器时将使用 SQL Server 身份验证,则还必须将 @publisher_security_mode 的值指定为 0,并为 @publisher_login@publisher_password 指定 SQL Server 登录信息。 此操作将为发布创建一个快照代理作业。 有关生成初始快照以及为快照代理定义自定义计划的详细信息,请参阅创建并应用初始快照

    安全说明安全说明

    使用远程分发服务器配置发布服务器时,为所有参数提供的值(包括 job_login 和 job_password)都会以纯文本方式发送到该分发服务器。 在执行此存储过程之前,应该对发布服务器及其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅启用数据库引擎的加密连接(SQL Server 配置管理器)

  3. 执行 sp_addmergearticle (Transact-SQL) 以向发布添加项目。 必须对发布中的每个项目执行一次此存储过程。 使用参数化筛选器时,必须使用 @subset_filterclause 参数为至少一个项目指定参数化行筛选器。 有关详细信息,请参阅定义和修改合并项目的参数化行筛选器

  4. 如果将基于该参数化行筛选器筛选其他项目,请执行 sp_addmergefilter (Transact-SQL) 以定义项目间的联接或逻辑记录关系。 必须对要定义的每个关系执行一次此存储过程。 有关详细信息,请参阅定义和修改合并项目间的联接筛选器

  5. 启动快照作业或从命令提示符下运行复制快照代理,以生成标准快照架构及其他文件。 有关详细信息,请参阅创建并应用初始快照

  6. 再次从命令提示符下运行复制快照代理以生成大容量复制 (.bcp) 文件,为 -DynamicSnapshotLocation 指定分区快照的位置,同时指定用于定义分区的以下一个或两个属性:

  7. 重复步骤 6,分别为每个订阅生成一个分区快照。

  8. 对每个订阅运行合并代理以在订阅服务器上应用初始分区快照,并指定以下属性:

    • -Hostname - 在 HOST_NAME 的实际值被覆盖时用于定义分区的值。

    • -DynamicSnapshotLocation - 此分区的动态快照的位置。

注意注意

有关复制代理编程的详细信息,请参阅复制代理可执行文件概念

示例 (Transact-SQL)

此示例使用参数化筛选器创建合并发布,其中由订阅服务器启动快照生成过程。 @job_login@job_password 的值通过脚本变量进行传递。

-- 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".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication with Subscriber requested snapshot
-- and using the default agent schedule. 
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'true',
  @publication_compatibility_level = N'90RTM';

-- Create a new snapshot job for the publication, using the default schedule.
-- Pass credentials at runtime using sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(login), 
  @job_password = $(password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains salesperson information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO

-- Start the agent job to generate the full snapshot for the publication.
-- The filtered data snapshot is generated automatically the first time 
-- the subscription is synchronized. 
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot 
  @publication = @publication;
GO

此示例使用参数筛选器创建发布,通过传递分区信息,其中的每个订阅服务器均有自己的分区(通过执行 sp_addmergepartition 进行定义)和经过筛选的快照作业(通过执行 sp_adddynamicsnapshot_job 来创建)。 @job_login@job_password 的值通过脚本变量进行传递。

-- 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".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication.  
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the 
-- default schedule. Pass credentials at runtime using 
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(Login), 
  @job_password = $(password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains customer information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO

-- Start the snapshot agent job.
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot 
  @publication = @publication;
GO

PRINT '*** Waiting for the initial snapshot.';
GO

-- Create a temporary table to store the filtered data snapshot 
-- job information.
CREATE TABLE #temp (id int,
    job_name sysname,
    job_id uniqueidentifier,
    dynamic_filter_login sysname NULL,
    dynamic_filter_hostname sysname NULL,
    dynamic_snapshot_location nvarchar(255),
    frequency_type int, 
    frequency_interval int, 
    frequency_subday_type int,
    frequency_subday_interval int, 
    frequency_relative_interval int, 
    frequency_recurrence_factor int, 
    active_start_date int, 
    active_end_date int, 
    active_start_time int, 
    active_end_time int
)

-- Create each snapshot for a partition 
-- The initial snapshot must already be generated.
DECLARE @publication AS sysname;
DECLARE @jobname AS sysname
DECLARE @hostname AS sysname
SET @publication = N'AdvWorksSalesPersonMerge';
SET @hostname = N'adventure-works\Fernando';

WHILE NOT EXISTS(SELECT * FROM sysmergepublications 
    WHERE [name] = @publication 
    AND snapshot_ready = 1)
BEGIN
    WAITFOR DELAY '00:00:05'
END

-- Create a data partition by overriding HOST_NAME().
EXEC sp_addmergepartition 
  @publication = @publication,
  @host_name = @hostname;

-- Create the filtered data snapshot job, and use the returned 
-- information to start the job.
EXEC sp_adddynamicsnapshot_job 
  @publication = @publication,
  @host_name = @hostname;

INSERT INTO #temp (id, job_name, job_id, dynamic_filter_login,
    dynamic_filter_hostname, dynamic_snapshot_location,
    frequency_type, frequency_interval, frequency_subday_type,
    frequency_subday_interval, frequency_relative_interval, 
    frequency_recurrence_factor, active_start_date, active_end_date, 
    active_start_time,active_end_time)
EXEC sp_helpdynamicsnapshot_job;

SELECT @jobname = (SELECT DISTINCT job_name FROM #temp WHERE dynamic_filter_hostname = @hostname);

EXEC msdb..sp_start_job @job_name = @jobname;
DROP TABLE #temp;
GO

此示例使用参数化筛选器创建发布,其中每个订阅服务器都必须通过提供分区信息来创建它自己的数据分区和已筛选的快照作业。 手动运行复制代理时,订阅服务器使用命令行参数提供分区信息。 此示例假设还对发布创建了订阅。

-- 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".

--Add a new merge publication.
DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.
EXEC sp_replicationdboption
  @dbname = @publicationdb,
  @optname = N'merge publish',
  @value = N'true';  

-- Create new merge publication.  
EXEC sp_addmergepublication 
  @publication = @publication, 
  @description = N'Merge publication of AdventureWorks2012.', 
  @allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the 
-- default schedule. Pass credentials at runtime using 
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot 
  @publication = @publication, 
  @job_login = $(Login), 
  @job_password = $(Password);

-- Add an article for the Employee table, 
-- which is horizontally partitioned using 
-- a parameterized row filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table1, 
  @source_owner = @schema_hr, 
  @source_object = @table1, 
  @type = N'table', 
  @description = 'contains employee information', 
  @subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table, 
-- which is partitioned based on a join filter.
EXEC sp_addmergearticle 
  @publication = @publication, 
  @article = @table2, 
  @source_owner = @schema_sales, 
  @source_object = @table2, 
  @type = N'table', 
  @description = 'contains customer information';

-- Add a join filter between the two articles.
EXEC sp_addmergefilter 
  @publication = @publication, 
  @article = @table1, 
  @filtername = @filter, 
  @join_articlename = @table2, 
  @join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]', 
  @join_unique_key = 1, 
  @filter_type = 1;
GO

REM Line breaks are added to improve readability. 
REM In a batch file, commands must be made in a single line.
REM Run the Snapshot agent from the command line to generate the standard snapshot 
REM schema and other files. 
SET DistPub=%computername%
SET PubDB=AdventureWorks2012 
SET PubName=AdvWorksSalesPersonMerge

"C:\Program Files\Microsoft SQL Server\110\COM\SNAPSHOT.EXE" -Publication %PubName%  
-Publisher %DistPub% -Distributor  %DistPub%  -PublisherDB %PubDB%  -ReplicationType 2  
-OutputVerboseLevel 1  -DistributorSecurityMode 1

PAUSE

REM Run the Snapshot agent from the command line, this time to generate 
REM the bulk copy (.bcp) data for each Subscriber partition.  
SET DistPub=%computername%
SET PubDB=AdventureWorks2012 
SET PubName=AdvWorksSalesPersonMerge
SET SnapshotDir=\\%DistPub%\repldata\unc\fernando

MD %SnapshotDir%

"C:\Program Files\Microsoft SQL Server\110\COM\SNAPSHOT.EXE" -Publication %PubName%  
-Publisher %DistPub%  -Distributor  %DistPub%  -PublisherDB %PubDB%  -ReplicationType 2  
-OutputVerboseLevel 1  -DistributorSecurityMode 1  -DynamicFilterHostName "adventure-works\Fernando"  
-DynamicSnapshotLocation %SnapshotDir%

PAUSE

REM Run the Merge Agent for each subscription to apply the partitioned 
REM snapshot for each Subscriber.  
SET Publisher = %computername%
SET Subscriber = %computername%
SET PubDB = AdventureWorks2012 
SET SubDB = AdventureWorks2012Replica 
SET PubName = AdvWorksSalesPersonMerge 
SET SnapshotDir=\\%DistPub%\repldata\unc\fernando

"C:\Program Files\Microsoft SQL Server\110\COM\REPLMERG.EXE" -Publisher  %Publisher%  
-Subscriber  %Subscriber%  -Distributor %Publisher%  -PublisherDB %PubDB%  
-SubscriberDB %SubDB% -Publication %PubName%  -PublisherSecurityMode 1  -OutputVerboseLevel 3  
-Output -SubscriberSecurityMode 1  -SubscriptionType 3 -DistributorSecurityMode 1  
-Hostname "adventure-works\Fernando"  -DynamicSnapshotLocation %SnapshotDir%

PAUSE

用于“返回首页”链接的箭头图标[Top]

使用复制管理对象 (RMO)

可以使用复制管理对象 (RMO) 通过以下方法以编程的方式生成分区快照:

  • 允许订阅服务器在第一次同步时请求快照生成和应用。

  • 为每个分区预生成快照。

  • 通过运行快照代理为每台订阅服务器手动生成一个快照。

注意注意

如果对项目进行筛选后,生成对于每个订阅都唯一的非重叠分区(通过在创建合并项目时将 PartitionOption 的值指定为 NonOverlappingSingleSubscription),则只要合并代理运行,就会清除元数据。 这意味着分区快照会过期得更快。 使用此选项时,应考虑允许订阅服务器请求快照生成。 有关详细信息,请参阅主题参数化行筛选器中的“使用适当的筛选选项”部分。

安全说明安全说明

如果可能,请在运行时提示用户输入安全凭据。 如果必须存储凭据,请使用 Microsoft Windows .NET Framework 提供的 Cryptographic Services(加密服务)。

创建允许订阅服务器启动快照生成和传递的发布

  1. 使用 ServerConnection 类创建与发布服务器的连接。

  2. 为发布数据库创建 ReplicationDatabase 类的实例,将 ConnectionContext 属性设置为步骤 1 中的 ServerConnection 实例,然后调用 LoadProperties 方法。 如果 LoadProperties 返回 false,请确认该数据库是否存在。

  3. 如果 EnabledMergePublishing 属性为 false,则将其设置为 true,然后调用 CommitPropertyChanges

  4. 创建 MergePublication 类的实例,然后为此对象设置下列属性:

  5. 调用 Create 方法创建发布。

    安全说明安全说明

    使用远程分发服务器配置发布服务器时,为所有属性(包括 SnapshotGenerationAgentProcessSecurity)提供的值都将以纯文本格式发送到分发服务器。 在调用 Create 方法之前,应该对发布服务器与其远程分发服务器之间的连接进行加密。 有关详细信息,请参阅启用数据库引擎的加密连接(SQL Server 配置管理器)

  6. 使用 MergeArticle 属性将项目添加到发布。 至少为一个项目指定 FilterClause 属性以定义参数化筛选器。 (可选)创建 MergeJoinFilter 对象以定义项目之间的联接筛选器。 有关详细信息,请参阅定义项目

  7. 如果 SnapshotAgentExists 的值为 false,请调用 CreateSnapshotAgent 为此发布创建初始快照代理作业。

  8. 调用在步骤 4 中创建的 MergePublication 对象的 StartSnapshotGenerationAgentJob 方法。 这将启动生成初始快照的代理作业。 有关生成初始快照和为快照代理定义自定义计划的详细信息,请参阅创建并应用初始快照

  9. (可选)检查 SnapshotAvailable 属性的值是否为 true,以确定初始快照何时可以使用。

  10. 如果订阅服务器的合并代理是第一次连接,则会自动生成一个分区快照。

创建发布并预生成快照或自动刷新快照

  1. 使用 MergePublication 类的实例定义一个合并发布。 有关详细信息,请参阅创建发布

  2. 使用 MergeArticle 属性将项目添加到发布。 至少为一个项目指定 FilterClause 属性以定义参数化筛选器,然后创建任何 MergeJoinFilter 对象以定义项目之间的联接筛选器。 有关详细信息,请参阅定义项目

  3. 如果 SnapshotAgentExists 的值为 false,请调用 CreateSnapshotAgent 为此发布创建快照代理作业。

  4. 调用在步骤 1 中创建的 MergePublication 对象的 StartSnapshotGenerationAgentJob 方法。 此方法启动生成初始快照的代理作业。 有关生成初始快照和为快照代理定义自定义计划的详细信息,请参阅创建并应用初始快照

  5. 检查 SnapshotAvailable 的值是否为 true,以确定初始快照何时可以使用。

  6. 创建 MergePartition 类的实例,然后使用下列属性的一个或两个设置订阅服务器的参数化筛选条件:

  7. 创建 MergeDynamicSnapshotJob 类的实例,然后设置与步骤 6 相同的属性。

  8. 使用 ReplicationAgentSchedule 类定义用于生成订阅服务器分区的筛选快照的计划。

  9. 使用步骤 1 中的 MergePublication 实例,调用 AddMergePartition。 传递步骤 6 中的 MergePartition 对象。

  10. 使用步骤 1 中的 MergePublication 实例,调用 AddMergeDynamicSnapshotJob 方法。 传递步骤 7 中的 MergeDynamicSnapshotJob 对象和步骤 8 中的 ReplicationAgentSchedule 对象。

  11. 调用 EnumMergeDynamicSnapshotJobs,然后在返回的数组中为新添加的分区快照作业找到 MergeDynamicSnapshotJob 对象。

  12. 为此作业获取 Name 属性。

  13. 使用 ServerConnection 类创建与分发服务器的连接。

  14. 创建 SQL Server 管理对象 (SMO) Server 类的实例,并传递步骤 13 中的 ServerConnection 对象。

  15. 创建 Job 类的实例,并传递步骤 14 中的 Server 对象的 JobServer 属性和步骤 12 中的作业名称。

  16. 调用 Start 方法以启动分区快照作业。

  17. 为每个订阅服务器重复步骤 6-16。

创建发布并为每个分区手动创建快照

  1. 使用 MergePublication 类的实例定义一个合并发布。 有关详细信息,请参阅创建发布

  2. 使用 MergeArticle 属性将项目添加到发布。为至少一个项目指定 FilterClause 属性以定义参数化筛选器,然后创建任何 MergeJoinFilter 对象以定义项目之间的联接筛选器。 有关详细信息,请参阅定义项目

  3. 生成初始快照。 有关详细信息,请参阅创建并应用初始快照

  4. 创建 SnapshotGenerationAgent 类的实例,并设置下列所需属性:

  5. ReplicationType 的值设置为 Merge

  6. 设置一个或多个下列属性以定义分区参数:

  7. 调用 GenerateSnapshot 方法。

  8. 为每个订阅服务器重复步骤 4-7。

示例 (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

此示例为带有参数化行筛选器的合并发布手动创建订阅服务器分区和筛选快照。

         // Define the server, database, and publication names
            string publisherName = publisherInstance;
            string publicationName = "AdvWorksSalesOrdersMerge";
            string publicationDbName = "AdventureWorks2012";
            string distributorName = publisherInstance;

            MergePublication publication;
            MergePartition partition;
            MergeDynamicSnapshotJob snapshotAgentJob;
            ReplicationAgentSchedule schedule;
            
            // Create a connection to the Publisher.
            ServerConnection publisherConn = new ServerConnection(publisherName);

            // Create a connection to the Distributor to start the Snapshot Agent.
            ServerConnection distributorConn = new ServerConnection(distributorName);

            try
            {
                // Connect to the Publisher.
                publisherConn.Connect();

                // Set the required properties for the publication.
                publication = new MergePublication();
                publication.ConnectionContext = publisherConn;
                publication.Name = publicationName;
                publication.DatabaseName = publicationDbName;


                // If we can't get the properties for this merge publication, 
                // then throw an application exception.
                if (publication.LoadProperties() || publication.SnapshotAvailable)
                {
                    // Set a weekly schedule for the filtered data snapshot.
                    schedule = new ReplicationAgentSchedule();
                    schedule.FrequencyType = ScheduleFrequencyType.Weekly;
                    schedule.FrequencyRecurrenceFactor = 1;
                    schedule.FrequencyInterval = Convert.ToInt32(0x001);

                    // Set the value of Hostname that defines the data partition. 
                    partition = new MergePartition();
                    partition.DynamicFilterHostName = hostname;
                    snapshotAgentJob = new MergeDynamicSnapshotJob();
                    snapshotAgentJob.DynamicFilterHostName = hostname;

                    // Create the partition for the publication with the defined schedule.
                    publication.AddMergePartition(partition);
                    publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule);
                }
                else
                {
                    throw new ApplicationException(String.Format(
                        "Settings could not be retrieved for the publication, " +
                        " or the initial snapshot has not been generated. " +
                        "Ensure that the publication {0} exists on {1} and " +
                        "that the Snapshot Agent has run successfully.",
                        publicationName, publisherName));
                }
            }
            catch (Exception ex)
            {
                // Do error handling here.
                throw new ApplicationException(string.Format(
                    "The partition for '{0}' in the {1} publication could not be created.",
                    hostname, publicationName), ex);
            }
            finally
            {
                publisherConn.Disconnect();
                if (distributorConn.IsOpen) distributorConn.Disconnect();
            }
' Define the server, database, and publication names
Dim publisherName As String = publisherInstance
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2012"
Dim distributorName As String = publisherInstance

Dim publication As MergePublication
Dim partition As MergePartition
Dim snapshotAgentJob As MergeDynamicSnapshotJob
Dim schedule As ReplicationAgentSchedule

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

' Create a connection to the Distributor to start the Snapshot Agent.
Dim distributorConn As ServerConnection = New ServerConnection(distributorName)

Try
    ' Connect to the Publisher.
    publisherConn.Connect()

    ' Set the required properties for the publication.
    publication = New MergePublication()
    publication.ConnectionContext = publisherConn
    publication.Name = publicationName
    publication.DatabaseName = publicationDbName


    ' If we can't get the properties for this merge publication, 
    ' then throw an application exception.
    If (publication.LoadProperties() Or publication.SnapshotAvailable) Then
        ' Set a weekly schedule for the filtered data snapshot.
        schedule = New ReplicationAgentSchedule()
        schedule.FrequencyType = ScheduleFrequencyType.Weekly
        schedule.FrequencyRecurrenceFactor = 1
        schedule.FrequencyInterval = Convert.ToInt32("0x001", 16)

        ' Set the value of Hostname that defines the data partition. 
        partition = New MergePartition()
        partition.DynamicFilterHostName = hostname
        snapshotAgentJob = New MergeDynamicSnapshotJob()
        snapshotAgentJob.DynamicFilterHostName = hostname

        ' Create the partition for the publication with the defined schedule.
        publication.AddMergePartition(partition)
        publication.AddMergeDynamicSnapshotJob(snapshotAgentJob, schedule)
    Else
        Throw New ApplicationException(String.Format( _
         "Settings could not be retrieved for the publication, " + _
         " or the initial snapshot has not been generated. " + _
         "Ensure that the publication {0} exists on {1} and " + _
         "that the Snapshot Agent has run successfully.", _
         publicationName, publisherName))
    End If
Catch ex As Exception
    ' Do error handling here.
    Throw New ApplicationException(String.Format( _
     "The partition for '{0}' in the {1} publication could not be created.", _
     hostname, publicationName), ex)
Finally
    publisherConn.Disconnect()
    If distributorConn.IsOpen Then
        distributorConn.Disconnect()
    End If
End Try

此示例手动启动快照代理,为带有参数化行筛选器的合并发布的订阅服务器生成筛选数据快照。

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

            SnapshotGenerationAgent agent;

            try
            {
                // Set the required properties for Snapshot Agent.
                agent = new SnapshotGenerationAgent();
                agent.Distributor = distributorName;
                agent.DistributorSecurityMode = SecurityMode.Integrated;
                agent.Publisher = publisherName;
                agent.PublisherSecurityMode = SecurityMode.Integrated;
                agent.Publication = publicationName;
                agent.PublisherDatabase = publicationDbName;
                agent.ReplicationType = ReplicationType.Merge;

                // Specify the partition information to generate a 
                // filtered snapshot based on Hostname.
                agent.DynamicFilterHostName = hostname;

                // Start the agent synchronously.
                agent.GenerateSnapshot();
            }
            catch (Exception ex)
            {
                // Implement custom application error handling here.
                throw new ApplicationException(String.Format(
                    "A snapshot could not be generated for the {0} publication."
                    , publicationName), ex);
            }
' Set the Publisher, publication database, and publication names.
Dim publicationName As String = "AdvWorksSalesOrdersMerge"
Dim publicationDbName As String = "AdventureWorks2012"
Dim publisherName As String = publisherInstance
Dim distributorName As String = publisherInstance

Dim agent As SnapshotGenerationAgent

Try
    ' Set the required properties for Snapshot Agent.
    agent = New SnapshotGenerationAgent()
    agent.Distributor = distributorName
    agent.DistributorSecurityMode = SecurityMode.Integrated
    agent.Publisher = publisherName
    agent.PublisherSecurityMode = SecurityMode.Integrated
    agent.Publication = publicationName
    agent.PublisherDatabase = publicationDbName
    agent.ReplicationType = ReplicationType.Merge

    ' Specify the partition information to generate a 
    ' filtered snapshot based on Hostname.
    agent.DynamicFilterHostName = hostname

    ' Start the agent synchronously.
    agent.GenerateSnapshot()
Catch ex As Exception
    ' Implement custom application error handling here.
    Throw New ApplicationException(String.Format( _
     "A snapshot could not be generated for the {0} publication." _
     , publicationName), ex)
End Try

用于“返回首页”链接的箭头图标[Top]

请参阅

概念

参数化行筛选器

复制系统存储过程概念

带有参数化筛选器的合并发布的快照

复制安全最佳实践