Wednesday, December 22, 2010

How to create a SQL trace using T-SQL

Some users want to know if there is a way to monitor events on SQL server without using SQL Profiler. Yes, there is: the engine support behind SQL Profiler is the feature called SQL Trace which is introduced in SQL 2005. SQL Trace provides a set of stored procedures to create traces on an instance of the SQL Server Database Engine. These system stored procedures can be used from within user's own applications to create traces manually, and allows to write custom applications specific to their needs.

The following sample code shows how to create customized SQL trace to monitor events to user's interest

-- sys.traces shows the existing sql traces on the server 
SELECT * FROM sys.traces 
go
--create a new trace, make sure the @tracefile must NOT exist on the disk yet 
DECLARE @tracefile NVARCHAR(500) SET @tracefile=N'c:\temp\newtraceFile'
DECLARE @trace_id INT
DECLARE @maxsize BIGINT
SET @maxsize =1
EXEC sp_trace_create @trace_id OUTPUT,2,@tracefile ,@maxsize 
go
--- add the events of insterest to be traced, and add the result columns of interest
--  Note: look up in sys.traces to find the @trace_id, here assuming this is the first trace in the server, therefor @trace_id=1
DECLARE @trace_id INT = 1, @on BIT = 1, @current_num INT
SET @current_num =1
WHILE(@current_num <65)
BEGIN
	--add events to be traced, id 14 is the login event, you add other events per your own requirements, the event id can be found @ BOL http://msdn.microsoft.com/en-us/library/ms186265.aspx
	EXEC sp_trace_setevent @trace_id,14, @current_num,@on
	SET @current_num=@current_num+1
END 
go
 
--turn on the trace: status=1
-- use sys.traces to find the @trace_id, here assuming this is the first trace in the server, so @trace_id=1 
DECLARE @trace_id INT
SET @trace_id=1
EXEC sp_trace_setstatus  @trace_id,1
 
--pivot the traced event
SELECT LoginName,DatabaseName,* FROM ::FN_TRACE_GETTABLE(N'c:\temp\newtraceFile.trc',DEFAULT)
go
 
-- stop trace. Please manually delete the trace file on the disk
-- use sys.traces to find the @trace_id, here assuming this is the first trace in the server, so @trace_id=1 
DECLARE @trace_id INT
SET @trace_id=1
EXEC sp_trace_setstatus @trace_id,0 
EXEC sp_trace_setstatus @trace_id,2 
go

0 comments:

Post a Comment