Scenario:
U werkt als SQL Server DBA of ontwikkelaar, u moet een script schrijven dat u kunt gebruiken om Change Data Capture (CDC) op alle tabellen in een database in te schakelen of op bepaalde specifieke tabellen in te schakelen.Het onderstaande script kan worden gebruikt om Change Data Capture in te schakelen voor alle tabellen in een database met geselecteerde tabellen. U kunt de query wijzigen om de gewenste tabellen op te nemen of uit te sluiten.
/*------------------------------------------------ Enable CDC on Set of Tables ( To Enable CDC on Table , CDC Should be enabled on Database level) --------------------------------------------------*/ USE [DatabaseName] GODECLARE @TableName VARCHAR(100)DECLARE @TableSchema VARCHAR(100)DECLARE CDC_Cursor CURSOR FOR SELECT * FROM ( SELECT 'T' AS TableName,'dbo' AS TableSchema UNION ALL SELECT 'T2' AS TableName,'dbo' AS TableSchema --IF want to Enable CDC on All Table, then use --SELECT Name,SCHEMA_NAME(schema_id) AS TableSchema --FROM sys.objects --WHERE type = 'u' -- AND is_ms_shipped <> 1 ) CDCOPEN CDC_CursorFETCH NEXT FROM CDC_Cursor INTO @TableName,@TableSchemaWHILE @@FETCH_STATUS = 0 BEGIN DECLARE @SQL NVARCHAR(1000) DECLARE @CDC_Status TINYINT SET @CDC_Status=(SELECT COUNT(*) FROM cdc.change_tables WHERE Source_object_id = OBJECT_ID(@TableSchema+'.'+@TableName)) --IF CDC Already Enabled on Table , Print Message IF @CDC_Status = 1 PRINT 'CDC is already enabled on ' +@TableSchema+'.'+@TableName + ' Table' --IF CDC is not enabled on Table, Enable CDC and Print Message IF @CDC_Status <> 1 BEGIN SET @SQL='EXEC sys.sp_cdc_enable_table @source_schema = '''+@TableSchema+''', @source_name = ''' + @TableName + ''', @role_name = null;' EXEC sp_executesql @SQL PRINT 'CDC enabled on ' +@TableSchema+'.'+ @TableName + ' Table successfully' END FETCH NEXT FROM CDC_Cursor INTO @TableName,@TableSchema END CLOSE CDC_CursorDEALLOCATE CDC_Cursor