Allows database administrators and application developers to monitor and record database activity.
Note xp_sqltrace has been replaced by xp_trace_addnewqueue as well as several other supporting extended procedures in the current version of Microsoft® SQL Server™. xp_sqltrace is documented here for backward compatibility only and may not be supported in future versions.
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]
Value | Description |
---|---|
audit | Logs all database activity requested by the specified filters to a file specified by outputfilename. Returns program control immediately. If traceid, bufsize, or timeout are specified, they are ignored. If audit is used without any parameters, a result set is generated displaying 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 a trace ID before starting a trace session. traceid is required. |
remove | Unloads all event handlers. Stops all data from being sent to 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 result set. traceid has no effect. |
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 remote procedure call (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. |
To specify more than one event, add the eventfilter values. For example, @EventFilter = 31 means that xp_sqltrace should monitor CONNECT, DISCONNECT, POST_LANGUAGE, POST_RPC, and ATTENTION events.
0 (success) or > 1 (failure)
xp_sqltrace returns this result set (values may vary).
Column name | Description |
---|---|
TraceId | Trace identification number used for the trace session |
Version | Version and build number that initiates the 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 utility or SQL Server Query Analyzer batch. After you choose the stop button in SQL Server Query Analyzer, another output row must be received for the trace to stop. This is a limitation of the SQL Server Query Analyzer interface.
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 specific to trace session output.
Event | Description |
---|---|
PAUSE (0) | Indicates 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 that meets the criteria specified in the xp_sqltrace command line. For example, if the system administrator already has three connections, three ACTIVE rows appear in the output. The trace session reports an ACTIVE row for preexisting connections. |
Execute permissions for xp_sqltrace default to the members of the sysadmin fixed server role but can be granted to other users.
This example begins a trace session displaying the event, the username, the application, the data or language statement, and other columns. All SELECT statements executed by the user sa are included in the trace. Events included in the trace are ATTENTION, CONNECT, DISCONNECT, POST-LANGUAGE, and POST-RPC events.
EXEC xp_sqltrace trace, @eventfilter = 31, @userfilter = 'sa',
@langfilter = '%select%'
These are the columns generated in the result set.
Column name | Data type | Description |
---|---|---|
Event | varchar(12) or int | Event (for example start, pause, active, connect, disconnect, SQL, attention) as varchar(12) unless @IntegerEvents = 1. |
UserName | char(30) NULL | Username of the user that generated the event. |
ID | int | Unique, increasing identifier for connections. |
SPID | int | Microsoft SQL Server process identification number. |
StartTime | datetime NULL | Time 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 | Time the language statement or remote stored procedure call stopped executing. For disconnect events, specifies the disconnect time. |
Application | char(30) NULL | Application that generated the event. |
Data | varchar(255) NULL or text NULL | Language statement or remote stored procedure call as varchar(255) unless @FullText = 1. |
Duration | int NULL | Amount of time in milliseconds 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 | int NULL | Amount of CPU time used in milliseconds. |
Reads | int NULL | Number of disk reads. |
Writes | int NULL | Number of synchronous disk writes. |
NT_Domain | char(30) NULL | Microsoft Windows NT® domain name of the user that generated the event. |
NT_User | char(30) NULL | Windows NT username of the user who generated the event. |
HostName | char(30) NULL | Name of the host that generated the event. |
HostProcess | int | Host process ID number for the host that generated the event. |
This example audits batches that contain SELECT statements executed by the user sa and places the output in a file called C:\SELECTS.LOG.
EXEC xp_sqltrace audit, @eventfilter = 31, @userfilter = 'sa',
@langfilter = '%select%', @FullFilePath = 'C:\SELECTS.LOG'
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. |
|
-- Start the trace. |
|
-- Pause the trace session. |
|
-- Begin trace session. |
|
-- Stop the trace session. |
The first two xp_sqltrace command examples stop all trace sessions executing on the current server, and the third example stops only the specified trace session.
-- Stops all trace sessions.
EXEC xp_sqltrace stop, @traceid = 0
-- OR
EXEC xp_sqltrace stop
-- Recommended way to stop a single trace session.
EXEC 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.
EXEC master.dbo.xp_sqltrace audit, 2, @FullFilePath =
'C:\MSSQL7\LOG\AUDIT.LOG'
END
GO
EXEC sp_procoption 'sp_sqlaudit', 'startup', true
GO
This example uses EXECUTE (or EXEC) to capture all of the server activity to a table named sqltrace in the pubs database. Note the transaction is not committed until xp_sqltrace STOP is executed 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 EXEC master..xp_sqltrace TRACE, @eventfilter = 31
From another connection, execute:
EXEC master..xp_sqltrace STOP, 1358560
/* where 1358560 is the trace session returned from xp_sqltrace */
This example loads an activity log into SQL Server using the bcp utility. First, create a log and capture the server activity to an activity log file. Next, create a table with this structure:
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='SQLTrace')
DROP TABLE SQLTrace
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
Monitoring with SQL Server Profiler | System Stored Procedures (SQL Server Profiler Extended Procedures) |