Change Data Capture (CDC) isan auditing feature provided by SQL Server 2008 and above and used to audit/track all changes done on a table such as inserts, updates, and deletes. We can enable CDC on the database using exec sys.sp_cdc_enable_db then we need to enable the same on each table manually using sys.sp_cdc_enable_table with table name as parameter. Instead of that, we can use the following SP to enable/disable CDC at the table level for all tables in a database:
  1. create procedure sp_enable_disable_cdc_all_tables(@dbname varchar(100), @enable bit)
  2. as
  3. BEGIN TRY
  4. DECLARE @source_name varchar(400);
  5. declare @sql varchar(1000)
  6. DECLARE the_cursor CURSOR FAST_FORWARD FOR
  7. SELECT table_name
  8. FROM INFORMATION_SCHEMA.TABLES where TABLE_CATALOG=@dbname and table_schema='dbo' and table_name != 'systranschemas'
  9. OPEN the_cursor
  10. FETCH NEXT FROM the_cursor INTO @source_name
  11. WHILE @@FETCH_STATUS = 0
  12. BEGIN
  13. if @enable = 1
  14. set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_enable_table
  15. @source_schema = N''dbo'',@source_name = '+@source_name+'
  16. , @role_name = N'''+'dbo'+''''
  17. else
  18. set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_disable_table
  19. @source_schema = N''dbo'',@source_name = '+@source_name+', @capture_instance =''all'''
  20. exec(@sql)
  21. FETCH NEXT FROM the_cursor INTO @source_name
  22. END
  23. CLOSE the_cursor
  24. DEALLOCATE the_cursor
  25. SELECT 'Successful'
  26. END TRY
  27. BEGIN CATCH
  28. CLOSE the_cursor
  29. DEALLOCATE the_cursor
  30. SELECT
  31. ERROR_NUMBER() AS ErrorNumber
  32. ,ERROR_MESSAGE() AS ErrorMessage;
  33. END CATCH
This SP takes db name and flags enable/disable as inputs and loops through each table name from INFORMATION_SCHEMA.TABLES using the cursor and calling dynamic SQL with command sys.sp_cdc_enable_table in it.
We can re-usethe same SP for doing any operation on every table in a database.