SqlServer2008实例16捕获和跟踪数据修改的改变之四从CDC表查询所有变更

--使表产生变更
use TSQLRecipe_CDC_DEMO
go

INSERT dbo.Equipment
	(EquipmentDESC,LocationID)
VALUES 
	('Projector A','22')
	
INSERT dbo.Equipment
	(EquipmentDESC,LocationID)
VALUES 
	('HR File Cabinet','3')

UPDATE dbo.Equipment
SET EquipmentDESC='HR File Cabinet 1'	
WHERE EquipmentID=2

DELETE dbo.Equipment
WHERE EquipmentID=1

    在生成变更之后,就可以使用CDC函数查看变更历史了。在曰志序列号(Log sequence number,LSN)级别跟踪数据变更。LSN是在事务日志中唯一标识活动的一个记录。
    现在要获取希望生成变更的时问范围的最小和最大的LSN值。这里使用sys.fn_cdc_map_time_to_lsn函数来确定LSN,这个函数有两个输入参数:关系运算符和跟踪时间.关系运算符如下:

  • srnallest greater也an;
  • smallest greater than or equal:
  • largest less than;
  • largest less than or equal
--设置侦测发生在希望的时间范围内的变更的LSN边界
SELECT sys.fn_cdc_map_time_to_lsn
('smallest greater than or equal','2020-07-05 00:00:00') as BenigLSN

SELECT sys.fn_cdc_map_time_to_lsn
('largest less than or equal','2020-07-05 23:30:00') as EndLSN
use TSQLRecipe_CDC_DEMO
go
--显示所有变更
DECLARE @FromLSN varbinary(10),@ToLSN varbinary(10);
SET @FromLSN=sys.fn_cdc_map_time_to_lsn
('smallest greater than or equal','2020-07-05 00:00:00');
SET @ToLSN=sys.fn_cdc_map_time_to_lsn
('largest less than or equal','2020-07-06 10:30:00');

SELECT 
	__$operation,
	__$update_mask,
	EquipmentID,
	EquipmentDESC,
	LocationID
FROM cdc.fn_cdc_get_all_changes_dbo_Equipment
     (@FromLSN,@ToLSN,N'all');

  SqlServer2008实例16捕获和跟踪数据修改的改变之四从CDC表查询所有变更_第1张图片

__$operation值的解释如下:
1为删除;
2为插入:
3为更新的行“之前”的版本(使用all update old选项来查看):
4为更新的行“之后”的版本。
 

use TSQLRecipe_CDC_DEMO
go
--显示所有变更
DECLARE @FromLSN varbinary(10),@ToLSN varbinary(10);
SET @FromLSN=sys.fn_cdc_map_time_to_lsn
('smallest greater than or equal','2020-07-05 00:00:00');
SET @ToLSN=sys.fn_cdc_map_time_to_lsn
('largest less than or equal','2020-07-06 10:30:00');

SELECT 
	case __$operation
		WHEN 1 THEN 'DELETE'
		WHEN 2 THEN 'INSERT'
		WHEN 3 THEN 'Before UPDATE'
		WHEN 4 THEN 'After UPDATE'
	END Operation,
	__$update_mask,
	EquipmentID,
	EquipmentDESC,
	LocationID
FROM cdc.fn_cdc_get_all_changes_dbo_Equipment
     (@FromLSN,@ToLSN,N'all update old');

SqlServer2008实例16捕获和跟踪数据修改的改变之四从CDC表查询所有变更_第2张图片

 

你可能感兴趣的:(#,SqlServer2008实例)