Sql Server触发器:记录表增删改记录


drop TABLE log_history
create table log_history
(logid int not null identity(1,1),  -- 日志序号(日志主键)
 operate varchar(10),               -- 操作类型:Insert,Update,Delete
 pznm varchar(100),                            -- 记录的表字段pznm(主键) 
 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)
)



drop trigger tr_history
create trigger tr_history
on cw_zcmx 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_history
     (operate,pznm,spid,login_name,prog_name,hostname,ipaddress,runsql,UDate)
     select @op,n.pznm,@@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.pznm=n.pznm
   end
   else
   begin
     insert into log_history
       (operate,pznm,spid,login_name,prog_name,hostname,ipaddress,runsql,UDate)
       select @op,o.pznm,@@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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM