判断调用DDL触发器的操作类型

Determine the type of operation that called DDL trigger

我有以下 table:

CREATE TABLE dbchanges 
(
    ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
    operationType VARCHAR(16),
    [Date] DATE NOT NULL,
    PRIMARY KEY (ID)
)

我需要我的 DDL 触发器来注册数据库中发生的所有更改 table。是否可以确定调用触发器的操作类型(CREATE、DROP 等)?

我正在使用 Transact-SQL。

是的,可以使用 EVENTDATA() 内置函数。此函数 returns 一个 XML 值,其中包含有关触发 DDL 触发器的事件的信息,例如事件时间、事件类型等。

您可以像这样在 DDL 触发器中使用此函数:

CREATE TRIGGER dbchanges_ddl
ON <database name here>
FOR DDL_TABLE_EVENTS -- alter, create and drop table
AS 

DECLARE @data XML,
        @EventType nvarchar(100);
SET @data = EVENTDATA();

SET @EventType = @data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)');

/* 
    Currently, we can examin the content of @EventType to know if 
    the statement that fired the trigger is an alter, create or a drop statement,
    However we have no information about what TABLE is mensioned in that statement.

    To get that information, we need to parse the actual SQL statement.
    We get the statement using TSQLCommand:
*/

DECLARE @Statement nvarchar(4000);
SET @Statement = @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(4000)');

-- Now you can check if the command refers to the table you want to monitor or not,
-- by looking for the name of the table inside the statement.


IF @statement LIKE '%dbchanges%' 
BEGIN
    -- Do whatever you want here...
END

GO