更改几个表的数据捕获

时间:2012-01-13 13:53:02

标签: sql-server-2008 change-tracking change-data-capture

SQL Server 2008。 是否可以创建更改数据捕获(或更改跟踪) 对于db中的几个相关表? 例如,多对多关系。

它会是什么样子?

1 个答案:

答案 0 :(得分:0)

从未使用它,但是从MSDN doc我会说:是的!

首先准备数据库:

ALTER DATABASE [yourdb] SET ALLOW_SNAPSHOT_ISOLATION ON

ALTER DATABASE [yourdb]
SET CHANGE_TRACKING = ON
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON)

现在在所需的表上启用更改跟踪:

ALTER TABLE [yourdb].[yourschema].[yourtable]
ENABLE CHANGE_TRACKING

查询更改:

IF @sync_initialized = 0
  SELECT * 
  FROM [yourschema].[yourtable] LEFT OUTER JOIN 
  CHANGETABLE(CHANGES [yourschema].[yourtable], @sync_last_received_anchor) CT
  ON CT.[yourkey] = [yourschema].[yourtable].[yourkey]
ELSE
BEGIN
  SELECT *
  FROM Sales.Customer 
  JOIN CHANGETABLE(CHANGES [yourschema].[yourtable], @sync_last_received_anchor) CT
  ON CT.[yourkey] = [yourschema].[yourtable].[yourkey]
  WHERE (CT.SYS_CHANGE_OPERATION = 'I' 
  AND CT.SYS_CHANGE_CREATION_VERSION 
  <= @sync_new_received_anchor)
END