Change Data Capture(CDC) in SQL Server

USE CDC
GO
CREATE TABLE Customer (
CustomerId INT  PRIMARY KEY
,FirstName VARCHAR(30)
,LastName VARCHAR(30)
,Amount_purchased DECIMAL
)
GO
INSERT INTO dbo.Customer
( CustomerId, FirstName,    LastName,    Amount_Purchased)
VALUES
(1, 'Frank', 'Sinatra',20000.00),
( 2,'Shawn', 'McGuire',30000.00),
( 3,'Amy', 'Carlson',40000.00)
GO
 
SELECT * FROM dbo.Customer
 
-- Now enable CDC at the Database Level
EXEC sys.sp_cdc_enable_db  
GO 
-- Enable on the table level
EXEC sys.sp_cdc_enable_table   
   @source_schema = N'dbo',
   @source_name   = N'Customer',
  /*
    Main parameter to remember @capture_instance.
	If you dont mention this parameter jobs will not create other 
	functions will also get affect
  */
   @capture_instance=N'Customer',
   @role_name     = NULL,
   @filegroup_name = N'Primary',
   @supports_net_changes = 0
GO
INSERT INTO Customer (Customerid, FirstName, LastName, Amount_purchased)
VALUES (4, 'Ameena', 'Lalani', 50000)
GO
UPDATE Customer
SET FirstName='Keka'
WHERE Customerid=4
go
-- Let us query to see what it reports now
SELECT * FROM dbo.Customer
/*
2-->Insert
1-->Delete
4-->Update
*/
Declare @begin_lsn binary (10), @end_lsn binary (10)
-- get the first LSN for customer changes
Select @begin_lsn = sys.fn_cdc_get_min_lsn('customer')
-- get the last LSN for customer changes
Select @end_lsn = sys.fn_cdc_get_max_lsn()
/*
 get individual changes in the range and provide the same value
that you have given for @capture_instance value here in
cdc.fn_cdc_get_all_changes_@capture_instance value here
*/
Select * from cdc.fn_cdc_get_all_changes_customer(@begin_lsn, @end_lsn, 'all');




Returns one row for each log scan session in the current database. The last row returned represents the current session. You can use this view to return status information about the current log scan session, or aggregated information about all sessions since the instance of SQL Server was last started.
This DMV  will provide information of latency of tables on which Change Data Captured enabled.


USE DatabaseName; 
GO 
SELECT latency as 'InSeconds',session_id, start_time, end_time, duration, scan_phase, error_count, start_lsn, current_lsn, end_lsn, tran_count 
    last_commit_lsn, last_commit_time, log_record_count, schema_change_count 
    command_count, first_begin_cdc_lsn, last_commit_cdc_lsn,  
    last_commit_cdc_time, empty_scan_count, failed_sessions_count 
FROM sys.dm_cdc_log_scan_sessions 
WHERE session_id = (SELECT MAX(b.session_id) 
FROM sys.dm_cdc_log_scan_sessions AS b); 
GO  

Comments

Popular posts from this blog

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Pre login Handshake or Connection Timeout Period

Transparent Data Encryption(TDE) with Master Key and Certificate in SQL Server