Technical Article

Enables Change Data Capture (CDC) on all user databases

,

Here’s a step-by-step guide and a ready-to-use SQL Agent Job script.

  1. Create the script
  2. Save this script as a SQL Agent Job step
    1. Open SQL Server Management Studio (SSMS).
    2. Connect to your instance.
    3. Go to SQL Server Agent → Jobs → New Job.
    4. General Tab:
      1. Name: Enable CDC on All User DBs
      2. Description: Enables CDC on all user DBs except excluded ones every Sunday at 11 PM.
    5. Steps Tab:
        • New Step
          • Name: Enable CDC
          • Type: Transact-SQL script (T-SQL)
          • Database: master
          • Paste the script above.
    6. Schedules Tab:
        • New Schedule
          • Name: Weekly - Sunday 11 PM
            • Frequency: Weekly
            • Recurs every: 1 week on Sunday
            • Daily Frequency: Occurs once at 11:00 PM.
    7. Save the Job.

3. Start SQL Server Agent - Make sure the SQL Server Agent is running, otherwise the job won’t execute.

Notes

  • The job will skip master, msdb, tempdb, model by default — adjust @ExcludeList to add more.
  • Make sure your SQL Server Agent account has permission to run sp_cdc_enable_db.
  • You must be a member of the sysadmin server role to enable CDC.
-- Replace with the databases you want to exclude
DECLARE @ExcludeList TABLE (DatabaseName SYSNAME);
INSERT INTO @ExcludeList (DatabaseName)
VALUES ('master'), ('tempdb'), ('model'), ('msdb'), ('YourDB1'), ('YourDB2'); -- Add your exclusions here

DECLARE @DatabaseName SYSNAME;
DECLARE @SQL NVARCHAR(MAX);

DECLARE db_cursor CURSOR FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE'
AND database_id > 4 -- skip system DBs
AND name NOT IN (SELECT DatabaseName FROM @ExcludeList);

OPEN db_cursor;

FETCH NEXT FROM db_cursor INTO @DatabaseName;

WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = '
USE [' + @DatabaseName + '];
IF NOT EXISTS (SELECT 1 FROM sys.change_tracking_databases WHERE database_id = DB_ID())
BEGIN
IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = ''' + @DatabaseName + ''' AND is_cdc_enabled = 1)
BEGIN
EXEC sys.sp_cdc_enable_db;
PRINT ''CDC enabled for database: ' + @DatabaseName + ''';
END
ELSE
BEGIN
PRINT ''CDC already enabled for database: ' + @DatabaseName + ''';
END
END
ELSE
BEGIN
PRINT ''CDC already enabled for database: ' + @DatabaseName + ''';
END';

EXEC sp_executesql @SQL;

FETCH NEXT FROM db_cursor INTO @DatabaseName;
END;

CLOSE db_cursor;
DEALLOCATE db_cursor;

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating