SQL Server What DDL Operation are captured by CDC in SQLServer

xv8emn3q  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(101)

I m trying to capture DDL operations using CDC in SQLServer. I m able to capture DDl ops like add columns,drop columns and alter columns, but I m unable to capture below operations

  1. .add constraint or drop constraint, For example this SQL is not getting recorded, alter table t add primary key(col1) .
  2. create,drop,rename table, for example create table t(col1 int) . ( I think this is understandable because a newly created table doesnt have cdc enabled by default so we are not getting the log, right?)

I m using cdc.ddl_history table to see ddl logs.Does SQLServer doesnt support the above ddl logs. I tried searching online to find what all ddl are supported but I cant find any concrete information about this.

SQLServer version 2017 Developer Edition, OS - windows 10

Thanks

o4hqfura

o4hqfura1#

In SQL Server, the Change Data Capture (CDC) feature is primarily designed to capture data changes (DML operations) rather than DDL operations. While CDC can capture certain DDL operations, it has limitations and may not capture all DDL operations.

As @Nick mentioned, you can use DDL triggers to capture DDL events and perform custom actions in response to those events.

CREATE TABLE DDL_Log (
    EventDate DATETIME,
    EventType NVARCHAR(100),
    ObjectName NVARCHAR(100),
    SQLCommand NVARCHAR(MAX)
);

CREATE TRIGGER CaptureDDL
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
    DECLARE @EventData XML;
    SET @EventData = EVENTDATA();

    DECLARE @EventDate DATETIME = GETDATE();
    DECLARE @EventType NVARCHAR(100) = @EventData.value('(/EVENT_INSTANCE/EventType)[1]', 'NVARCHAR(100)');
    DECLARE @ObjectName NVARCHAR(100) = @EventData.value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(100)');
    DECLARE @SQLCommand NVARCHAR(MAX) = @EventData.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'NVARCHAR(MAX)');

    
    INSERT INTO DDL_Log (EventDate, EventType, ObjectName, SQLCommand)
    VALUES (@EventDate, @EventType, @ObjectName, @SQLCommand);
END;

相关问题