先说一下什么是cdc ,cdc 变更数据捕获(Change Data Capture ,简称 CDC)记录 SQL Server 表的插入、更新和删除活动。SQLServer的操作会写日志,这也是CDC捕获数据的来源。
1.开启cdc
if exists(select 1 from sys.databases where name='db_name' and is_cdc_enabled=0)
begin
exec sys.sp_cdc_enable_db end
2.开启表CDC(*注意:表中必须有主键或者唯一索引)
EXEC OverseaECommerceManagement.sys.sp_cdc_enable_table
@source_schema= 'dbo',
@source_name = 'Table_Name(这里是你的表的名字)',
@role_name = N'cdc_Admin',
@capture_instance = DEFAULT,
@supports_net_changes = 1,
@index_name = NULL,
@captured_column_list = N'[SysNo],[CouponSysNo],[PublishType],[CouponCodeNum],[CustomerMaxFrequency],[CouponActivityCode],[SubmitType],[PreferChannel],[CustomLink],[CouponDetailDesc],[CouponImage]', (如果
captured_column_list = NULL,代表表的每个字段都监控
)
@filegroup_name = DEFAULT
3.修改cdc中保留数据的时间
EXECUTE OverseaECommerceManagement.sys.sp_cdc_change_job
@job_type = N'cleanup',
@retention=180
4.查询某一段时间内的cdc数据
DECLARE @from_lsn binary(10), @to_lsn binary(10);
DECLARE @begin_time varchar(255);
DECLARE @end_time varchar(255);
SET @begin_time='2019/04/01';
SET @end_time='2019/05/01';
SELECT @from_lsn =OverseaECommerceManagement.sys.fn_cdc_map_time_to_lsn('smallest greater than or equal', @begin_time);
SELECT @to_lsn = OverseaECommerceManagement.sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);
SELECT TOP 1 coupon.__$operation
OperateType FROM [OverseaECommerceManagement].cdc.dbo_Coupon_CT coupon
with(nolock) WHERE __$start_lsn BETWEEN @from_lsn AND @to_lsn
数据跟踪技术使用范围其实很广泛,特别适用于数据变更之后异步的去通知或者去处理其他操作。