Allows database administrators and application developers to monitor and record database activity. Multiple instances of xp_sqltrace can be run simultaneously.
xp_sqltrace [[@Function = ] function] [, [ @EventFilter = ] eventfilter]
[, [ @LangFilter = ] 'langfilter'] [, [ @RPCFilter = ] 'rpcfilter'] [, [ @UserFilter = ] userfilter] [, [ @AppFilter = ] appfilter] [, [ @HostFilter = ] hostfilter] [, [@BufSize = ] bufsize] [, [ @TimeOut = ] timeout] [, [ @TraceId = ] traceid] [, [@FullText = ] fulltext] [, [ @FullFilePath = ] 'outputfilename'] [, [ @IntegerEvents = ] integerevents]
where
@Function value | Description |
---|---|
audit | Logs all database activity requested by the specified filters to a file specified by @FullFilePath. Returns program control immediately. If @TraceId, @BufSize, or @TimeOut parameters are specified, they are ignored. If audit is used without any parameters, generates a results set that displays the current audit settings for xp_sqltrace. Only one instance of audit can be executed at any time. A permanent connection is not necessary to execute an audit. For example, the system administrator can be connected, start the audit, and then disconnect. You can use audit in automatically started procedures. |
control | Changes the settings for a running instance from a separate connection. You must run xp_sqltrace without parameters to obtain an @TraceId before starting a trace session. The @TraceId parameter is required. |
remove | Unloads all event handlers. Stops all data from being sent t o trace sessions until trace handlers are loaded again. Using remove does not stop currently executing trace sessions. Starting or stopping a trace session also loads or unloads relevant handlers. You can use remove to temporarily pause all trace sessions. No other parameters are required. |
stop | Stops either a single trace session or all trace sessions for the current server. It is recommended that you execute xp_sqltrace stop, @traceid = <traceid> to stop a specific trace session. Using xp_sqltrace stop is useful if the server is under heavy load and the system administrator must stop all trace activities. |
trace | Captures all database activity requested by the specified filters and generates a log file or a results set. The @TraceId parameter has no effect. |
@EventFilter value | Description |
---|---|
0 | PAUSE. Temporarily pauses the trace session. Must be the only @EventFilter specified. |
1 | CONNECT. Trace CONNECT events to SQL Server. |
2 | DISCONNECT. Trace DISCONNECT events from SQL Server. |
4 | POST_LANGUAGE. Trace completed language events on SQL Server (for example, INSERT, SELECT). |
8 | POST_RPC. Trace completed RPC events on SQL Server. |
16 | ATTENTION. Trace ATTENTION events on SQL Server. |
32 | PRE_LANGUAGE. Trace language batches immediately prior to execution. Not currently used by SQLTRACE.EXE. |
64 | PRE_RPC. Trace RPC events immediately before execution. Not currently used by SQLTRACE.EXE. |
For more information about the SQL Trace log format, see the online Help for SQL Trace.
When using xp_sqltrace, an @Function = trace does not return program control until explicitly stopped. No other commands should be issued before the call to xp_sqltrace in an isql or ISQL/w batch. After you choose the stop button in ISQL/w, another output row must be received for the trace to stop. This is a limitation of the ISQL/w interface.
Note The recommended way to stop a trace session is to specify the trace identification number. For example:
xp_sqltrace stop, @traceid = <traceid>
Data can be captured to a table by using the INSERT statement's EXECute clause. Using the INSERT statement this way places xp_sqltrace within a transaction. If xp_sqltrace is used in a transaction, the transaction will not complete until the application stops xp_sqltrace. If the trace is not terminated before the server is stopped or if the database fills completely during a transaction, all changes are rolled back.
These are the events that are specific to trace session output.
Event | Description |
---|---|
PAUSE (0) | Indicates that the trace session was paused temporarily. |
START (254) | Indicates a START trace event. |
ACTIVE (255) | Indicates an ACTIVE connection event. A row appears in the output for every user who meets the criteria specified in the xp_sqltrace command line. For example, if the system administrator already has three connections, three ACTIVE rows will appear in the output. The trace session will report an ACTIVE row for pre-existing connections. |
For more information about monitoring database activity, see the online Help for SQL Trace.
This example begins a trace session that displays the event, the username, the application, the data or language statement, and other columns. All SELECT statements executed by either sa or probe users are included in the trace. Events included in the trace are attention, connect, disconnect, post-language, and post-rpc events.
xp_sqltrace trace, @eventfilter = 31, @userfilter = 'sa;probe', @langfilter = '%select%'
These are the columns generated in the results set.
Column name | Datatype | Description |
---|---|---|
Event | varchar(12) or int | Specifies the event (for example START, PAUSE, ACTIVE, Connect, Disconnect, SQL, Attention) as varchar(12) unless @IntegerEvents = 1. |
UserName | char(30) NULL | Specifies the username of the user that generated the event. |
ID | int | Specifies a unique, increasing identifier for connections. |
SPID | int | Specifies the SQL Server process identification number. |
StartTime | datetime NULL | Specifies the time that the language statement or remote stored procedure call started executing. For connect and disconnect events, specifies the time the user logged in. |
EndTime | datetime NULL | Specifies the time that the language statement or remote stored procedure call stopped executing. For disconnect events, specifies the disconnect time. |
Application | char(30) NULL | Specifies the application that generated the event. |
Data | varchar(255) NULL or text NULL | Specifies the language statement or remote stored procedure call as varchar(255) unless @FullText = 1. |
Duration | int NULL | Specifies the amount of time in milliseconds that the language statement or remote stored procedure call took to execute. For disconnect events, specifies the elapsed time in seconds since the user logged in. |
CPU | in NULLt | Specifies the amount of CPU time used in milliseconds. |
Reads | int NULL | Specifies the number of disk reads. |
Writes | int NULL | Specifies the number of synchronous disk writes. |
NT_Domain | char(30) NULL | Specifies the NT Domain name of the user that generated the event. |
NT_User | char(30) NULL | Specifies the NT User name of the user that generated the event. |
HostName | char(30) NULL | Specifies the name of the host that generated the event. |
HostProcess | int | Specifies the host process ID number for the host that generated the event. |
This example audits batches that contain SELECT statements executed by sa or probe users and places the output in a text file called C:\SELECTS.TXT.
xp_sqltrace audit, @eventfilter = 31, @userfilter = 'sa;probe', @langfilter = '%select%', @FullFilePath = 'C:\SELECTS.TXT'
This example starts a trace session for the first connection, and it allows the second connection to control the same trace session by using the trace identification number obtained and passed by the first connection.
Connection One | Connection Two |
---|---|
--obtain a traceid xp_sqltrace |
|
--start the trace xp_sqltrace trace, @eventfilter = 31 |
|
--pause the trace session xp_sqltrace control, @TraceId = <TraceId> |
|
--begin trace session xp_sqltrace control @TraceId = <TraceId>, @EventFilter = 4, @LangFilter = '%select%' |
|
--stop the trace session xp_sqltrace stop, @traceid = <traceid> |
The following two xp_sqltrace command examples stop all trace sessions executing on the current server while the third example stops only the specified trace session.
-- stops all trace sessions xp_sqltrace stop, @traceid = 0 -- OR xp_sqltrace stop --recommended way to stop a single trace session xp_sqltrace stop @TraceId = <TraceId>
This example creates a stored procedure to automatically start an audit session that audits disconnections.
print 'Creating auditing stored procedure' -- create stored procedure to enable xp_sqltrace run at startup go USE master go IF exists(SELECT * FROM sysobjects WHERE type = 'P' AND name = 'sp_sqlaudit') DROP PROCEDURE sp_sqlaudit go CREATE PROCEDURE sp_sqlaudit AS BEGIN -- @FullFilePath can be any file that SQL Server has write -- permissions EXECUTE master.dbo.xp_sqltrace audit, 2, @FullFilePath = 'C:\MSSQL\LOG\AUDIT.LOG' END go sp_makestartup 'sp_sqlaudit' go
This example uses the EXECUTE statement to capture all of the server activity to a table named sqltrace in the pubs database. Note that the transaction is not committed until you execute "xp_sqltrace stop" from another connection.
USE pubs GO IF EXISTS(SELECT * FROM sysobjects WHERE name = 'SQLTrace' AND type = 'U') BEGIN DROP TABLE SQLTrace END GO CREATE TABLE SQLTrace ( Event CHAR(12) NOT NULL, UserName CHAR(30) NOT NULL, ID int NOT NULL, SPID int NOT NULL, StartTime DATETIME NULL, EndTime DATETIME NULL, Application CHAR(30) NOT NULL, Data VARCHAR(255) NULL, Duration INT NULL, CPU INT NULL, Reads INT NULL, Writes INT NULL, NT_Domain VARCHAR(30) NULL, NT_User VARCHAR(30) NULL, HostName VARCHAR(30) NULL, HostProcess INT NULL ) GO EXEC master..xp_sqltrace GO INSERT INTO SQLTrace EXECUTE master..xp_sqltrace TRACE, @eventfilter = 31
From another connection, execute the following statement.
EXEC master..xp_sqltrace STOP, 1358560
/* where 1358560 is the trace session returned from xp_sqltrace */
You can easily load an activity log into SQL Server using BCP. First create a log and capture the server activity to an activity log file. Next, create a table with the following structure:
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'SQLTrace' AND type = 'U') BEGIN DROP TABLE SQLTrace END GO CREATE TABLE SQLTrace ( Event CHAR(12) NOT NULL, UserName CHAR(30) NOT NULL, ID INT NOT NULL, SPID INT NOT NULL, StartTime datetime NULL, EndTime datetime NULL, Application CHAR(30) NOT NULL, Data VARCHAR(255) NULL, Duration INT NULL, CPU INT NULL, Reads INT NULL, Writes INT NULL, NT_Domain VARCHAR(30) NULL, NT_User VARCHAR(30) NULL, HostName VARCHAR(30) NULL, HostProcess INT NULL ) GO
Finally, load the data using BCP.
bcp pubs..SQLTrace in c:\activity.log -Usa -Psecret -S -c
Execute permission defaults to the system administrator. It is recommended that the system administrator be the only login permitted to execute this procedure.