确定调用DDL触发器的操作类型

时间:2018-09-30 11:34:45

标签: sql-server tsql triggers ddl

我有下表:

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

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

我正在使用Transact-SQL。

1 个答案:

答案 0 :(得分:1)

是的,可以使用内置的EVENTDATA()函数。此函数返回一个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