记录数据库操作记录的DDL触发器


 我们在项目中经常会对数据做一些操作,比如增加一个字段,修改一个存储过程,删除表等等操作,很有必要记录这些操作,以便以后出了问题,方便找到元凶。接下来介绍一个DDL触发器在实际环境中的使用,这个DDL触发器主要功能是:把数据库结构变化的操作事件,操作类型,登陆名,操作人电脑名称,架构名称,对象名称,目标对象,事件内容,插入到日志表中。

首先在数据库创建一张日志表,存储操作记录

CREATE TABLE [dbo].[AuditDDLEvents](
	[Lsn] [int] IDENTITY(1,1) NOT NULL,
	[PostTime] [datetime] NOT NULL,
	[EventType] [sysname] NOT NULL,
	[LoginName] [sysname] NOT NULL,
	[HostName] [nvarchar](100) NOT NULL,
	[SchemaName] [sysname] NOT NULL,
	[ObjectName] [sysname] NOT NULL,
	[TargetObjectName] [sysname] NOT NULL,
	[Eventdata] [xml] NOT NULL,
 CONSTRAINT [PK_AuditDDLEvents_Lsn] PRIMARY KEY CLUSTERED 
(
	[Lsn] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

接下是重点创建一个触发器,每操作一次,系统自动把数据插入表中

INSERT INTO dbo.AuditDDLEvents(posttime,eventtype,loginname,schemaname,
		objectname,targetobjectname,eventdata,HostName)
VALUES(
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/PostTime)[1]',		'varchar(23)'),''),
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/EventType)[1]',		'sysname'),''),
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/LoginName)[1]',		'sysname'),''),
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/SchemaName)[1]',		'sysname'),''),
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/ObjectName)[1]',		'sysname'),''),
	ISNULL(@Eventdata.value('(/EVENT_INSTANCE/TargetObjectName)[1]',		'sysname'),''),
	@Eventdata,Host_Name());

GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

ENABLE TRIGGER [trg_audit_ddl_events] ON DATABASE
GO

最后就亲自试一试。
Alt text

posted @ 2017-07-10 19:43  山中自有人  阅读(616)  评论(1编辑  收藏  举报