SQL知道执行了哪些查询

时间:2011-12-10 16:24:18

标签: sql-server sql-server-2008

是否可以在SQL Server 2008中获取用户执行什么查询的信息?如果某人更改了示例视图,则信息将保存在DDL_Log中。

我没有对一个表进行审核,我必须知道用户执行什么查询,是否可以知道?

我必须知道例如用户X做

SELECt id FROM Person

或例如用户Y做

UPDATE TOP(1) Person SET Name = 'John' WHERE id = 6

1 个答案:

答案 0 :(得分:2)

考虑使用sp_trace_xxx程序捕获活动:

-- Create a Queue
declare @rc int
declare @TraceID int
declare @maxfilesize bigint
declare @traceoptions int
declare @stoptime datetime
set @traceoptions = 2
set @maxfilesize = 999  
set @stoptime = '2011-12-10 19:20:00'

exec @rc = sp_trace_create @TraceID output, 0, N'd:\sql server\deftrace', @maxfilesize, @stoptime

if (@rc != 0) goto error

-- Set the events
declare @on bit
set @on = 1
-- SQL:BatchCompleted events
exec sp_trace_setevent @TraceID, 12, 1, @on -- textdata
exec sp_trace_setevent @TraceID, 12, 9, @on -- client process id
exec sp_trace_setevent @TraceID, 12, 10, @on -- application name
exec sp_trace_setevent @TraceID, 12, 11, @on -- login name
exec sp_trace_setevent @TraceID, 12, 12, @on -- spid
exec sp_trace_setevent @TraceID, 12, 13, @on -- duration (usec)
exec sp_trace_setevent @TraceID, 12, 14, @on -- start time
exec sp_trace_setevent @TraceID, 12, 15, @on -- end time
exec sp_trace_setevent @TraceID, 12, 16, @on -- reads
exec sp_trace_setevent @TraceID, 12, 17, @on -- writes
exec sp_trace_setevent @TraceID, 12, 18, @on -- cpu
exec sp_trace_setevent @TraceID, 12, 34, @on -- object name
exec sp_trace_setevent @TraceID, 12, 35, @on -- database name

-- RPC:Completed events
exec sp_trace_setevent @TraceID, 10, 1, @on -- textdata
exec sp_trace_setevent @TraceID, 10, 9, @on -- client process id
exec sp_trace_setevent @TraceID, 10, 10, @on -- application name
exec sp_trace_setevent @TraceID, 10, 11, @on -- login name
exec sp_trace_setevent @TraceID, 10, 12, @on -- spid
exec sp_trace_setevent @TraceID, 10, 13, @on -- duration (usec)
exec sp_trace_setevent @TraceID, 10, 14, @on -- start time
exec sp_trace_setevent @TraceID, 10, 15, @on -- end time
exec sp_trace_setevent @TraceID, 10, 16, @on -- reads
exec sp_trace_setevent @TraceID, 10, 17, @on -- writes
exec sp_trace_setevent @TraceID, 10, 18, @on -- cpu
exec sp_trace_setevent @TraceID, 10, 34, @on -- object name
exec sp_trace_setevent @TraceID, 10, 35, @on -- database name

-- Filter out the SQL Profiler events
exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Profiler'

-- Set the trace status to start
exec sp_trace_setstatus @TraceID, 1

-- display trace id for future references
select TraceID=@TraceID
goto finish

error:
select ErrorCode=@rc

finish:
go

然后运行:

exec sp_trace_setstatus @TraceID, 0
exec sp_trace_setstatus @TraceID, 2

停止追踪(或等到@stoptime)。要查看已执行的查询,请运行:

SELECT DatabaseName, TextData, Reads, Writes, CPU, SPID, Duration / 1000 Duration, StartTime, EndTime, ClientProcessID, LoginName, ApplicationName
FROM fn_trace_gettable('d:\sql server\deftrace.trc', default);

这些代码示例对诊断和查询分析很有用。通过一些调整,您可以使用它们来记录命令,用户和时间戳。