Sql Server を想定 -この記事に基づいて、DDL トリガーを作成する例を次に示します。
まず、ログを保持するテーブルを作成します...
CREATE TABLE [dbo].[ChangeLog](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[DatabaseName] [varchar](256) NOT NULL,
[EventType] [varchar](50) NOT NULL,
[ObjectName] [varchar](256) NOT NULL,
[ObjectType] [varchar](25) NOT NULL,
[SqlCommand] [varchar](max) NOT NULL,
[EventDate] [datetime] NOT NULL CONSTRAINT
[DF_EventsLog_EventDate] DEFAULT (getdate()),
[LoginName] [varchar](256) NOT NULL,
[UserName] [varchar](256) NULL,
CONSTRAINT [PK_ChangeLog] PRIMARY KEY CLUSTERED ([LogId] ASC)
)
次に、トリガーを作成します...
CREATE TRIGGER [TrgDDLChangeLog]
ON DATABASE
FOR
CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
CREATE_TABLE, ALTER_TABLE, DROP_TABLE,
CREATE_FUNCTION, ALTER_FUNCTION, DROP_FUNCTION,
CREATE_VIEW, ALTER_VIEW, DROP_VIEW,
CREATE_TRIGGER, ALTER_TRIGGER, DROP_TRIGGER,
CREATE_INDEX, ALTER_INDEX, DROP_INDEX
AS
DECLARE @Event XML
SET @Event = EVENTDATA()
INSERT INTO dbo.ChangeLog
(
DatabaseName,
EventType,
ObjectName,
ObjectType,
SQLCommand,
LoginName,
UserName
)
VALUES
(
@Event.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'VARCHAR(256)'),
@Event.value('(/EVENT_INSTANCE/EventType)[1]', 'VARCHAR(50)'),
@Event.value('(/EVENT_INSTANCE/ObjectName)[1]', 'VARCHAR(256)'),
@Event.value('(/EVENT_INSTANCE/ObjectType)[1]', 'VARCHAR(25)'),
@Event.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'VARCHAR(max)'),
@Event.value('(/EVENT_INSTANCE/LoginName)[1]', 'VARCHAR(256)'),
@Event.value('(/EVENT_INSTANCE/UserName)[1]', 'VARCHAR(256)')
)