ms_sql 觸發器記錄表字段數據變化的日誌 -針對一張表操做

create table stosql

(id int not null, -- 主鍵字段
de datetime -- 被跟蹤的字段
constraint pk_sto primary key(id)
)
session


select * from stoide

-- 建日誌表
create table log_sto
(logid int not null identity(1,1), -- 日誌序號(日誌主鍵)
operate varchar(10), -- 操做類型 如Insert,Update,Delete.
id int, -- 原表ID(主鍵)
old_de datetime, -- de字段舊值
new_de datetime, -- de字段新值
spid int not null, -- spid
login_name varchar(100), -- 登陸名
prog_name varchar(100), -- 程序名
hostname varchar(100), -- 主機名
ipaddress varchar(100), -- IP地址
runsql varchar(4000), -- 執行的TSQL代碼
UDate datetime -- 操做日期時間
constraint pk_logsto primary key(logid)
)
------------建跟蹤觸發器
create trigger tr_sto
on sto after update,insert,delete
as
begin
declare @di table(et varchar(200),pt varchar(200),ei varchar(max))
insert into @di exec('dbcc inputbuffer(@@spid)')

declare @op varchar(10)
select @op=case when exists(select 1 from inserted) and exists(select 1 from deleted)
then 'Update'
when exists(select 1 from inserted) and not exists(select 1 from deleted)
then 'Insert'
when not exists(select 1 from inserted) and exists(select 1 from deleted)
then 'Delete' end

if @op in('Update','Insert')
begin
insert into log_sto
(operate,id,old_de,new_de,spid,login_name,prog_name,hostname,ipaddress,runsql,UDate)
select @op,n.id,o.de,n.de,@@spid,
(select login_name from sys.dm_exec_sessions where session_id=@@spid),
(select program_name from sys.dm_exec_sessions where session_id=@@spid),
(select hostname from sys.sysprocesses where spid=@@spid),
(select client_net_address from sys.dm_exec_connections where session_id=@@spid),
(select top 1 isnull(ei,'') from @di),
getdate()
from inserted n
left join deleted o on o.id=n.id
end
else
begin
insert into log_sto
(operate,id,old_de,new_de,spid,login_name,prog_name,hostname,ipaddress,runsql,UDate)
select @op,o.id,o.de,null,@@spid,
(select login_name from sys.dm_exec_sessions where session_id=@@spid),
(select program_name from sys.dm_exec_sessions where session_id=@@spid),
(select hostname from sys.sysprocesses where spid=@@spid),
(select client_net_address from sys.dm_exec_connections where session_id=@@spid),
(select top 1 isnull(ei,'') from @di),
getdate()
from deleted o
end
end
go日誌

insert into sto(id,de,name) values (6,GETDATE(),'xx')ip

-- 操做2
insert into sto(id,de) values(2,'2012-01-01 06:06:07')
go

-- 操做3
update sto set de=getdate() where id=2
go

-- 操做4
update sto set de=getdate() where id=1
go

-- 操做5
insert into sto(id,de) values(3,'2012-01-01 15:26:37')
go

-- 操做6
delete sto where id=2
select * from sto
select * from log_stoget

相關文章
相關標籤/搜索