0

我需要找出谁在删除/更新表 THETABLE 上的数据、时间、使用什么程序以及发送到导致修改的数据库的命令。

通过谷歌搜索和询问一些同事,推荐的方法是删除触发器。我知道如何创建触发器,例如:

create trigger whodunit
on THETABLE
for delete
as begin
    insert into MyAuditTbl(moddate, ...
end

但是如何获取发送到数据库的命令(查询/存储过程)、应用程序名称、IP 地址等?

4

1 回答 1

0

我找到了一些脚本并对其进行了定制以满足我的需求:

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
于 2013-06-05T04:54:39.540 回答