-- Set the database and the retention period
USE YourDatabaseName;
GO
DECLARE @retentionDays INT = 7; -- Set the retention period in days
-- Convert retention days to a cutoff LSN
DECLARE @retentionDateTime DATETIME = DATEADD(DAY, -@retentionDays, GETDATE());
DECLARE @cutoffLSN BINARY(10);
-- Retrieve the minimum LSN based on the retention date
SELECT @cutoffLSN = sys.fn_cdc_map_time_to_lsn('smallest greater than or equal', @retentionDateTime);
-- Check if the cutoff LSN is valid
IF @cutoffLSN IS NOT NULL
BEGIN
DECLARE @capture_instance NVARCHAR(200);
DECLARE @sql NVARCHAR(MAX);
-- Cursor to go through each capture instance
DECLARE instance_cursor CURSOR FOR
SELECT capture_instance
FROM cdc.change_tables;
OPEN instance_cursor;
FETCH NEXT FROM instance_cursor INTO @capture_instance;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Generate the cleanup command for each capture instance
SET @sql = N'EXEC sys.sp_cdc_cleanup_change_table @capture_instance = ''' + @capture_instance + ''', @low_water_mark = ''' + CONVERT(NVARCHAR(100), @cutoffLSN, 1) + ''';';
-- Execute the cleanup command
EXEC sp_executesql @sql;
FETCH NEXT FROM instance_cursor INTO @capture_instance;
END;
CLOSE instance_cursor;
DEALLOCATE instance_cursor;
PRINT 'CDC logs purged successfully up to ' + CONVERT(NVARCHAR(30), @retentionDateTime, 121);
END
ELSE
BEGIN
PRINT 'No valid LSN found for the specified retention period.';
END
GO