作为一名数据库管理员,你尽力以各部门熟知的不同格式,向各部门提供它们所需要的数据。你通常将MS Excel格式的数据递交到会计部门,或将数据以HTML报表的形式呈现给普通用户。你们的系统安全管理员们则习惯于用文本阅读器或者事件查看器来查看日志。本文将介绍如何使用触发器,把DML(数据操作语言)对数据库中的特定数据表的改动记录下来。注:下列例子为Insert型触发器,不过改成Delete/Update型的触发器也很容易。
操作步骤首先让我们在Northwind数据库内创建一个简单表。
create table tablefortrigger ( track int identity(1,1) primary key, Lastname varchar(25), Firstname varchar(25) ) |
sp_addmessage 50005, 10, '%s', @with_log = true |
Create trigger TestTrigger on tablefortrigger for insert as --声明储存消息的变量 Declare @Msg varchar(8000) --将"操作/表名/日期时间/插入字段"赋与消息 set @Msg = 'Inserted | tablefortrigger | ' + convert(varchar(20), getdate()) + ' | ' +(select convert(varchar(5), track) + ', ' + lastname + ', ' + firstname from inserted) --产生错误发送给事件查看器。 raiserror( 50005, 10, 1, @Msg) |
Insert into tablefortrigger(lastname, firstname) Values('Doe', 'John') |
(图1) |
Alter trigger TestTrigger on tablefortrigger for insert as Declare @Msg varchar(1000) --储存将由xp_cmdshell执行的命令 Declare @CmdString varchar (2000) set @_msg = ' insert | tablefortrigger | ' + convert ( varchar ( 20 ) , getdate ( ) ) + ' | ' + ( select convert ( varchar ( 5 ) , track ) + ' , ' + lastname + ' , ' + firstname from insert ) - [99%]set @Msg = 'Inserted | tablefortrigger | ' + convert(varchar(20), getdate()) + ' | ' +(select convert(varchar(5), track) + ', ' + lastname + ', ' + firstname from inserted) --产生错误发送给事件查看器。 raiserror( 50005, 10, 1, @Msg) set @CmdString = 'echo ' + @Msg + ' >> C:\logtest.log' --写到文本文件 exec master.dbo.xp_cmdshell @CmdString |
Insert into tablefortrigger(lastname, firstname) Values('Doe', 'John') |
ALTER trigger TestTrigger on tablefortrigger for insert as Declare @Msg varchar(1000) Declare @CmdString varchar (1000) Declare GetinsertedCursor cursor for Select 'Inserted | tablefortrigger | ' + convert(varchar(20), getdate()) + ' | ' + convert(varchar(5), track) + ', ' + lastname + ', ' + firstname from inserted open GetinsertedCursor Fetch Next from GetinsertedCursor into @Msg while @@fetch_status = 0 Begin raiserror( 50005, 10, 1, @Msg) Fetch Next from GetinsertedCursor into @Msg set @CmdString = 'echo ' + @Msg + ' >> C:\logtest.log' exec master.dbo.xp_cmdshell @CmdString End close Getinsertedcursor deallocate GetInsertedCursor |
Insert into tablefortrigger(lastname, firstname) Select lastname, firstname from employees |