Enable Change Data Capture with sys.sp_cdc_enable_table

An audit trail or a warehouse feed needs every insert, update and delete on a table, without triggers on the write path. Change data capture (CDC) reads those changes from the transaction log, and sys.sp_cdc_enable_table switches it on for one table. One call creates the change table and its query functions. On the first table in the database, it also creates the cleanup job, and the capture job too when the database has no transactional publications.

Purpose and Overview

Change data capture uses no triggers. A capture process reads the transaction log and writes each change to a change table, and you query that table through generated functions instead of reading it directly.

CDC is turned on in two steps. First the database is enabled with sys.sp_cdc_enable_db, which needs sysadmin on SQL Server and Azure SQL Managed Instance. You can confirm that step by reading the is_cdc_enabled column in sys.databases. Then sys.sp_cdc_enable_table runs once per table. It needs membership in the db_owner fixed database role and returns 0 on success or 1 on failure. A database that already has a schema or a user named cdc cannot be enabled until that schema or user is dropped or renamed.

The minimum version depends on the edition. CDC arrived in SQL Server 2008, but Standard edition first got it in SQL Server 2016 SP1. On Standard, the script needs SQL Server 2016 SP1 or later.

Code Breakdown

This script enables CDC for the AdventureWorks2022 database, then for HumanResources.Department. Microsoft notes that before you can enable a table for change data capture, the database must be enabled, so sys.sp_cdc_enable_db runs first. Run it as a member of sysadmin, which the database step needs. The table call passes every optional parameter except @allow_partition_switch and the unsupported @enable_extended_ddl_handling.

 1USE AdventureWorks2022;
 2GO
 3
 4EXECUTE sys.sp_cdc_enable_db;
 5GO
 6
 7EXECUTE sys.sp_cdc_enable_table
 8    @source_schema = N'HumanResources',
 9    @source_name = N'Department',
10    @role_name = N'cdc_admin',
11    @capture_instance = N'HR_Department',
12    @supports_net_changes = 1,
13    @index_name = N'AK_Department_Name',
14    @captured_column_list = N'DepartmentID, Name, GroupName',
15    @filegroup_name = N'PRIMARY';
16GO

Source table and capture instance

@source_schema and @source_name name the table to track. Tables in the cdc schema can't be enabled.

@capture_instance names this capture setup. Leave it out and SQL Server builds the name as <schemaname>_<sourcename>, so this table would get HumanResources_Department. The script shortens it to HR_Department. The name can be at most 100 characters and must be unique in the database.

The capture instance name also names the query functions. Here they are cdc.fn_cdc_get_all_changes_HR_Department and cdc.fn_cdc_get_net_changes_HR_Department. A source table can have at most two capture instances, so a third call against the same table fails until one instance is removed.

The gating role

@role_name is required. It names the database role that controls who can read the change data. Here it is cdc_admin. If that role doesn't exist, the procedure tries to create it. If the caller isn't allowed to create a role in the database, the whole call fails.

Reading change data takes two things. The user needs SELECT permission on all the captured columns of the source table. A user who is not in sysadmin or db_owner must also be a member of the gating role.

Passing @role_name = NULL explicitly turns gating off, and then SELECT on the captured columns is the only check. If you later disable CDC for the database, any gating role it created stays behind and has to be dropped by hand.

Net changes and @index_name

@supports_net_changes = 1 generates the net-changes function as well as the all-changes function. It also adds a nonclustered index to the change table. The net-changes function returns only one change for each distinct row changed in the interval you ask for. That suits a load that only needs the final state of each row.

The default for this parameter is 1 when the table has a primary key, or a unique index named in @index_name. Otherwise it defaults to 0, and only the all-changes functions are generated. The extra index has to be maintained as capture writes each change, and Microsoft says enabling net changes can have a negative effect on CDC performance.

@index_name must name a valid unique index on the source table. Its columns take precedence over any primary key as the row identifier. The script passes AK_Department_Name. When @index_name is left out and the table has a primary key, CDC uses the key. After that, you can't change the primary key without first disabling CDC on the table. If the table has no primary key when CDC is enabled, CDC ignores a key added later.

Column list and filegroup

@captured_column_list limits which columns go into the change table. With NULL, every column is captured. The script captures three: DepartmentID, Name and GroupName. The list must include the primary key columns, or the columns of the index named in @index_name. A column name with an embedded comma must be quoted inside the list.

@filegroup_name sets where the change table is stored. With NULL, it goes on the default filegroup. The script puts it on PRIMARY to match Microsoft's example, though Microsoft recommends creating a separate filegroup for change data capture change tables. Whichever filegroup you name must already exist. If that filegroup runs out of space, CDC stops capturing changes until space is available, and the capture job fails with error 1105.

What the call creates

On success, the procedure sets is_tracked_by_cdc to 1 for the table in sys.tables. The change table starts with five metadata columns, followed by the captured columns.

If this is the first table in the database enabled for CDC, the call also creates the CDC jobs. The cleanup job is always created. The capture job is created only when the database has no transactional publications; when replication is present, the transactional log reader does the capture work instead. The capture process doesn't read the log or write to the change table unless SQL Server Agent is running.

@allow_partition_switch defaults to 1, and the script leaves it there. On a nonpartitioned table the setting is always 1 and whatever you pass is ignored. On a partitioned table, CDC doesn't track changes that come from a partition switch. A switch can therefore move rows in or out of the table without any row appearing in the change table.

Key Benefits and Use Cases

  • Before and after values for each update — an update writes two change rows, __$operation 3 (before image) and 4 (after image), so an audit can show the old value next to the new one.
  • Two column shapes during a schema change — after a DDL change, a second capture instance with the new columns can feed a development environment while the first keeps feeding current programs.
  • Commit-time windows — cdc.lsn_time_mapping records the commit LSN and commit time of every transaction with captured changes, so a load can ask for the changes between two clock times.
  • Privacy-limited history — when a privacy rule allows only some columns to be tracked, the rest of the row never reaches the change table.

Performance Considerations

  • Log truncation: the log truncation point doesn't move until the capture process has collected all marked changes, even in the simple recovery model. If capture is stopped, running CHECKPOINT won't truncate the log.
  • Net-changes cost: @supports_net_changes = 1 adds a nonclustered index that capture maintains on every change it writes. Leave it off for tables nobody reads with the net-changes function. Because the default is 1 whenever the table has a primary key, leaving it off on such a table takes an explicit @supports_net_changes = 0.
  • Filegroup space: a full CDC filegroup stops capture until space is freed, and the capture job fails with error 1105.
  • Capture throughput and latency: by default the capture job runs continuously, reading at most 1,000 transactions per scan cycle with a 5-second wait between cycles. There is always some delay between a commit on the source table and the row showing up in the change table.
  • Edition limits: Standard edition has CDC only from SQL Server 2016 SP1, so this call can't run on an older Standard instance.

Practical Tips

  • Check both flags — read is_cdc_enabled in sys.databases before the call and is_tracked_by_cdc in sys.tables after it.
  • Watch the Agent service account — capture needs SQL Server Agent running, and CDC can't work properly when the Database Engine or Agent service runs as NETWORK SERVICE. That setup can result in error 22832.
  • Size retention on purpose — the cleanup job runs daily at 2 A.M., keeps 4,320 minutes (3 days) of changes and deletes at most 5,000 entries per statement. A change made with sys.sp_cdc_change_job takes effect only after the job is stopped and restarted.
  • Plan the role's lifecycle — grant SELECT on the captured columns to the readers, and drop the gating role yourself after sys.sp_cdc_disable_db, which leaves it in place.
  • Create the CDC filegroup first — add a dedicated filegroup before the call and pass it in @filegroup_name. Then a growing change table can't fill PRIMARY.

Conclusion

sys.sp_cdc_enable_table is the table-level step that follows sys.sp_cdc_enable_db. It is the point where the row identifier, the captured columns, net-changes support and the change table's filegroup are set. Decide those before the call, because changing the key or the column list later means disabling capture first or adding a second capture instance.

References

Posts in this series