我需要找出谁正在删除/更新表THETABLE上的数据,时间,使用什么程序,以及发送到导致修改的数据库的命令。
从谷歌搜索并询问一些同事,推荐的方法是删除触发器。我知道如何创建触发器,例如:
create trigger whodunit
on THETABLE
for delete
as begin
insert into MyAuditTbl(moddate, ...
end
但是如何获取发送到DB(查询/存储过程)的命令,应用程序名称,IP地址等?
答案 0 :(得分:0)
我找到some script并根据我的需要对其进行了自定义:
create trigger AuditTHETABLE
on THETABLE
for delete, update
as begin
set nocount on
declare @shouldlog bit, @insertcount bigint, @deletecount bigint
select
@shouldlog = 1,
@insertcount = (select count(*) from inserted),
@deletecount = (select count(*) from deleted)
-- if no rows are changed, do not log
if @insertcount < 1 and @deletecount < 1 begin
select @shouldlog = 0
end
-- ... other checks whether to log or not
if @shouldlog = 1 begin
-- prepare variable to capture last command
declare @buffer table (
eventtype nvarchar(30),
parameters int,
eventinfo nvarchar(4000)
)
-- use DBCC INPUTBUFFER to capture last command
-- unfortunately only the first 255 characters are captured
insert @buffer
exec sp_executesql N'DBCC INPUTBUFFER(@@spid) WITH NO_INFOMSGS'
declare @lastcommand varchar(max)
select @lastcommand = eventinfo from @buffer
-- insert into audit table
insert into myauditlog(
eventdate, tablename, hostname,
appname, insertcount, deletecount, command
) values(
getdate(),
'THETABLE',
host_name(),
app_name(),
@insertcount,
@deletecount,
@lastcommand
)
end
end