--
建跟踪触发器
ALTER
trigger tr_sto
on sto after
update,
insert,
delete
as
begin
declare
@di
table(et
NVARCHAR(
max),pt
NVARCHAR(
max),ei
NVARCHAR(
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
=
'
Update
'
--
IF UPDATE(de) --关键字段发生表更记录。
--
BEGIN
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
WHERE
ISNULL(o.de,
'')
<>
ISNULL(n.de,
'')
--
只记录修改字段old值和new值不一样的情况。
--
WHERE CHECKSUM(o.de)<>CHECKSUM(n.de)
END
--
end
ELSE
if
@op
=
'
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