Use the CDC function of SQL Server to realize data change capture

--Enable the CDC function of a certain database
exec sys.sp_cdc_enable_db
 
--is_cdc_enabled field is 1 means the CDC function is enabled
SELECT is_cdc_enabled,CASE WHEN is_cdc_enabled=0 
THEN 'CDC function disabled' ELSE 'CDC function enabled'END Description
FROM sys. databases
WHERE NAME = 't'
 
--Enable the CDC function of a single table
EXEC sys.sp_cdc_enable_table @source_schema='dbo',
    @source_name = 'so',@role_name = NULL
 
--Close the CDC function of a single table
EXEC sys. sp_cdc_disable_table @source_schema='dbo',
    @source_name = 'so',@capture_instance = 'dbo_so'
  
 __$operation" is "1" for delete, "2" for insert, "3" for the value before the update operation, "4 ” The value after performing the update operation.


SELECT * FROM [cdc].[dbo_so_CT]
 
--(DDL) change history
SELECT * FROM [cdc].[ddl_history]

1. The version of SQL Server must be 2008 or above;
2. Memory-optimized tables (a function only available in SQL Server 2014 or above) cannot be used at the same time. Otherwise, the following error will occur:
3. Both @@SERVERNAME and serverproperty('servername') (the local server name and the attribute of the server instance must be consistent) must be consistent. The following script can adjust the two to be consistent. If the two are still inconsistent after execution, you need to restart the SQL Server service.


if serverproperty('servername') <> @@servername 
begin
    declare @server sysname 
    set @server = @@servername 
    exec sp_dropserver@server =@server 
    set @server = cast(serverproperty('servername') as sysname) 
    exec sp_addserver@server = @server , @local = 'LOCAL'
    PRINT 'ok'
end


select @@SERVERNAME,serverproperty('servername') 
4. The SQL Sever proxy service must be enabled. The CDC function must be implemented through jobs.
 
5. The table with the CDC function enabled cannot use TRUNCATE TABLE. You can disable it first, and then enable cdc after executing truncate.
 
6. If the table structure changes, capture the instance table: the new column cannot be captured, the deleted column remains NULL, and the modified column type will be cast. To be on the safe side, capture instances should be disabled and then enabled again.
 
7. When querying CDC related tables, it is recommended to add With (NOLOCK), otherwise blocking or deadlock will easily occur.
 
8. A table can only have a maximum of two capture instances.


 

Guess you like

Origin blog.csdn.net/weixin_51981189/article/details/130619018