Creating trace with system stored procedures

Following are the stored procedures which you should know:

  • sp_trace_create: This stored procedure is used to create a trace and returns the ID of newly created trace
  • sp_trace_setevent: This stored procedure is used to add or remove event classes and data columns to and from a given trace
  • sp_trace_setfilter: This stored procedure is used to set a filter condition on desired data column for a given trace
  • sp_trace_setstatus: This stored procedure is used to start, stop, or close a given trace

In this example, we will capture only two event classes:

  • Data File Auto Grow
  • Log File Auto Grow

For these mentioned event classes, we will be capturing the following data columns:

  • DatabaseName
  • FileName
  • StartTime
  • EndTime

By collecting these data columns, we can know which database file is automatically grown for which database and when.
We will not apply any filter in this trace because we want to capture and audit the database file growth events for all databases on the server. Thus, stored procedure sp_trace_setfilter will not be used in our example.

Follow the steps provided here to create a trace with system stored procedures:

1. Start SQL Server Management Studio and connect to SQL Server.
2. In the query window, type and execute the following T-SQL script to create a new trace through system stored procedures:

DECLARE @ReturnCode INT
DECLARE @TraceID INT
DECLARE @Options INT = 2
DECLARE @TraceFile NVARCHAR(245) = 'C:\MyTraces\MyTestTrace'
DECLARE @MaxFileSize INT = 5
DECLARE @Event_DataFileAutoGrow INT = 92
DECLARE @Event_LogFileAutoGrow INT = 93
DECLARE @DataColumn_DatabaseName INT = 35
DECLARE @DataColumn_FileName INT = 36
DECLARE @DataColumn_StartTime INT = 14
DECLARE @DataColumn_EndTime INT = 15
DECLARE @On BIT = 1
DECLARE @Off BIT = 0
--Create a trace and collect the returned code.
EXECUTE @ReturnCode = sp_trace_create
@traceid = @TraceID OUTPUT
,@options = @Options
,@tracefile = @TraceFile
--Check returned code is zero and no error occurred.
IF @ReturnCode = 0
BEGIN
BEGIN TRY
--Add DatabaseName column to DataFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_DataFileAutoGrow
,@columnid = @DataColumn_DatabaseName ,@on = @On
--Add FileName column to DataFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_DataFileAutoGrow
,@columnid = @DataColumn_FileName
,@on = @On
--Add StartTime column to DataFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_DataFileAutoGrow
,@columnid=@DataColumn_StartTime
,@on = @On
--Add EndTime column to DataFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_DataFileAutoGrow
,@columnid = @DataColumn_EndTime
,@on = @On
--Add DatabaseName column to LogFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_LogFileAutoGrow
,@columnid = @DataColumn_DatabaseName
,@on = @On
--Add FileName column to LogFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_LogFileAutoGrow
,@columnid = @DataColumn_FileName
,@on = @On
--Add StartTime column to LogFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_LogFileAutoGrow
,@columnid=@DataColumn_StartTime
,@on = @On --Add EndTime column to LogFileAutoGrow event.
EXECUTE sp_trace_setevent
@traceid = @TraceID
,@eventid = @Event_LogFileAutoGrow
,@columnid = @DataColumn_EndTime
,@on = @On
--Start the trace. Status 1 corresponds to START.
EXECUTE sp_trace_setstatus
@traceid = @TraceID
,@status = 1
END TRY
BEGIN CATCH
PRINT 'An error occurred while creating trace.'
END CATCH
END
GO

3. By executing the following query and observing the result set, make sure that the trace has been created successfully. This query should return a record for the trace that we created:

--Verify the trace has been created.
SELECT * FROM sys.traces
GO

4. The previous query will give you the list of traces that are currently running on the system. You should see your newly created trace listed in the result set of the
previous query. If the trace could be created successfully, execute the following T-SQL script to create a sample database and insert one million records:

--Creating Sample Database keeping Filegrowth Size
--to 1 MB for Data and Log file.
CREATE DATABASE [SampeDBForTrace] ON PRIMARY
(
NAME = N'SampeDB'
,FILENAME = N'C:\MyTraces\SampeDBForTrace_Data.mdf'
,SIZE = 2048KB , FILEGROWTH = 1024KB
)

LOG ON
(
NAME = N'SampeDBForTrace_log'
,FILENAME = N'C:\MyTraces\SampeDBForTrace_log.ldf'
,SIZE = 1024KB , FILEGROWTH = 1024KB
)
GO
USE SampeDBForTrace
GO
--Creating and Inserting one million records tbl_SampleData table.
SELECT TOP 1000000 C1.*
INTO tbl_SampleData
FROM sys.columns AS C1
CROSS JOIN sys.columns AS C2
CROSS JOIN sys.columns AS C3
GO

 

5. After executing the previous script, execute the following T-SQL script to stop and close the trace:

DECLARE @TraceID INT
DECLARE @TraceFile NVARCHAR(245) = 'C:\MyTraces\MyTestTrace.trc'
--Get the TraceID for our trace.
SELECT @TraceID = id FROM sys.traces
WHERE path = @TraceFile
IF @TraceID IS NOT NULL
BEGIN
--Stop the trace. Status 0 corroponds to STOP.
EXECUTE sp_trace_setstatus
@traceid = @TraceID
,@status = 0
--Closes the trace. Status 2 corroponds to CLOSE.
EXECUTE sp_trace_setstatus
@traceid = @TraceID
,@status = 2
END
GO

6. Execute the following query to verify that the trace has been stopped and closed successfully. This query should not return a record for our trace if it is stopped and closed successfully.

--Verify the trace has been stopped and closed.
SELECT * FROM sys.traces
GO

7. The previous query will not return the row for the trace that we created because the trace has now been stopped and closed. Inspect the resulting trace data collected in our trace file by executing the following query:

--Retrieve the collected trace data.
SELECT
TE.name AS TraceEvent
,TD.DatabaseName
,TD.FileName
,TD.StartTime
,TD.EndTime
FROM fn_trace_gettable('C:\MyTraces\MyTestTrace.trc',default) AS
TD
LEFT JOIN sys.trace_events AS TE
ON TD.EventClass = TE.trace_event_id
GO

In this recipe, we first created and configured our trace by executing a T-SQL script. The script first declares some required variables whose values are passed as parameters to system stored procedures. It creates a trace by executing the sp_trace_create stored procedure that returns ID of the newly created trace. The stored procedure sp_trace_create accepts the following parameters:

  • @traceid OUTPUT
  • @options
  • @tracefile

The @Options parameter is passed to specify the trace options. The following are the predefined values for the @Options parameter:

  • 2: TRACE_FILE_ROLLOVER
  • 4: SHUTDOWN_ON_ERROR
  • 8: TRACE_PRODUCE_BLACKBOX

The parameter @TraceFile specifies the location and file name where the trace file should be saved. @TraceID is the output variable and the returned ID value of the trace will be stored in this variable. If the stored procedure can create a trace file successfully, it returns 0 that gets stored in variable @ReturnCode.

data columns by calling stored procedure sp_trace_setevent for each combination of event class and data column one-by-one for following event classes and data columns:

  • DataFileAutoGrow event class and DatabaseName data column
  • DataFileAutoGrow event class and FileName data column
  • DataFileAutoGrow event class and StartTime data column
  • DataFileAutoGrow event class and EndTime data column
  • LogFileAutoGrow event class and DatabaseName data column
  • LogFileAutoGrow event class and FileName data column
  • LogFileAutoGrow event class and StartTime data column
  • LogFileAutoGrow event class and EndTime data column

Stored procedure accepts the following parameters:

  • @traceid
  • @eventid
  • @columnid
  • @on

How to get IDs for all event classes and data columns?

ID values for required event classes and data columns must be passed to the stored procedure sp_trace_setevent. You can get a list of EventIDs for all event classes by querying sys.trace_events system catalog view. To get a list of column IDs for all data columns, use sys.trace_columns system catalog view. Also, you can retrieve list of column IDs for all available columns for a given event by querying sys.trace_event_bindings system catalog view and by joining it with sys.trace_events and sys.trace_columns system catalog views on trace_event_id and trace_
column_id columns respectively.

The value of @ on parameter value can be either 0 or 1 where the value 1 means that event data for specified event class and data column should be captured otherwise not.After adding the required event classes and data columns, the stored procedure sp_trace_setstatus is used to set the status of the trace to START. Any trace that is created with system stored procedure is always in STOP state by default, and needs to be started explicitly by calling sp_trace_setstatus stored procedure. This stored procedure accepts the following parameters:

  • @traceid
  • @status

@TraceID is the ID of the trace we created and need to be started. @Status specifies the state of the trace. Possible values for @Status parameter are as follows:

  • 0: Stops a trace
  • 1: Starts a trace
  • 2: Closes a trace

Because we wanted to start our trace, we are passing a value of 1 to this parameter.

SQL Server keeps track of currently opened trace sessions. This list of traces can be retrieved by querying sys.traces system catalog view. We just make sure by querying this view that the trace is indeed created.

Next, we create a sample database named SampleDBTrace. We deliberately keep the value of FILEGROWTH attribute smaller in order to be able to produce Data File Auto Growth and Log File Auto Growth events. The script also creates a sample table named tbl_SampleData though SELECT … INTO statement in which we insert one million sample records by cross joining sys.columns system catalog view with itself multiple times. This operation requires additional space in data and log files to make room for inserting new records. For this, SQL Server has to increase the size of data and log files when required by one MB (specified value for the FILEGROWTH attribute). This causes DataFileAutoGrowth and LogFileAutoGrowth events to be raised.

Once the record insertion operation is completed, the script is executed to stop and close the trace by again calling the stored procedure sp_trace_setstatus twice with the appropriate status value for each call. Remember that to close a trace, it should be stopped first. So, a trace should be stopped first before it can be closed.After closing a trace, we make sure that the trace stopped and closed successfully by querying sys.traces system catalog view again.

Once our trace is stopped, we use fn_trace_gettable() function to query the captured trace data saved in specified trace file whose full file path is also being passed to the function for the first parameter filename. We also pass the default value for the second parameter number_files of the function which specifies that the function should read all rollover files to return trace data. Because this function does not return any column for the event class' name, we join it with sys.trace_events system catalog view on IDs of event classes in order to fetch the names of event classes.

If you want to analyze large size of trace data containing large number of trace files, then you should specify 1 for number_files parameter. If you specify default, the SQL Server tries to load all race files into memory and then inserts them into a table in a single operation, which may crash your system.

Microsoft.SQL.Server2012.Performance.Tuning.Cookbook学习笔记(二)的更多相关文章

  1. Microsoft.SQL.Server2012.Performance.Tuning.Cookbook学习笔记(一)

    一.Creating a trace or workload 注意点: In the Trace Properties dialog box, there is a checkbox option i ...

  2. sql分类及基本sql操作,校对规则(mysql学习笔记二)

    sql针对操作对象分为不同语言 数据操作(管理)语言 DML或者将其细分为 ( 查询  DQL 管理(增,删,改)  DML) 数据定义语言(对保存数据的格式进行定义) DDL 数据库控制语言(针对数 ...

  3. 《Microsoft Sql server 2008 Internals》读书笔记--第六章Indexes:Internals and Management(1)

    <Microsoft Sql server 2008 Internals>索引文件夹: <Microsoft Sql server 2008 Internals>读书笔记--文 ...

  4. Spark SQL 之 Performance Tuning & Distributed SQL Engine

    Spark SQL 之 Performance Tuning & Distributed SQL Engine 转载请注明出处:http://www.cnblogs.com/BYRans/ 缓 ...

  5. 《SQL必知必会》学习笔记二)

    <SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...

  6. SQL Server2012 T-SQL基础教程--读书笔记(1-4章)

    SQL Server2012 T-SQL基础教程--读书笔记(1-4章) SqlServer T-SQL 示例数据库:点我 Chapter 01 T-SQL 查询和编程背景 1.3 创建表和定义数据的 ...

  7. SQL Server2012 T-SQL基础教程--读书笔记(8 - 10章)

    SQL Server2012 T-SQL基础教程--读书笔记(8 - 10章) 示例数据库:点我 CHAPTER 08 数据修改 8.1 插入数据 8.1.1 INSERT VALUES 语句 8.1 ...

  8. SQL Server2012 T-SQL基础教程--读书笔记(5-7章)

    SQL Server2012 T-SQL基础教程--读书笔记(5-7章) SqlServer T-SQL 示例数据库:点我 Chapter 05 表表达式 5.1 派生表 5.1.1 分配列别名 5. ...

  9. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

随机推荐

  1. 前端小知识--区分get和post请求

    get和post是HTTP协议中的两种发送请求的方法. 如果你还不了解http,可以点击[HTTP协议①介绍](https://www.jianshu.com/p/632b890b75ac)[HTTP ...

  2. ios那些事之如何在ios5上运行gdb

    为啥要在ios上运行gdb? 这个问题见仁见智喽.对于搞开发的同学们来所, 有了gdb更方便跟踪分析别人的程序,取长补短:)这里不是教大家crack:) 运行环境: Mac OS 10.7.4 Xco ...

  3. WPF 的另类资源方式 Resources.resx

      类似Winform的搞法,可以把资源放到Resources.resx中. 1.字符串 打开这个编辑器后,输入Name和Value就可以了. CS代码里面,很简单的调用: var title = W ...

  4. Delphi 设计模式:《HeadFirst设计模式》Delphi7代码---装饰模式之StarBuzzCoffee[转]

     1  2{<HeadFirst设计模式>之装饰模式 }  3{ 本单元中的类为被装饰者         }  4{ 编译工具: Delphi7.0          }  5{ E-Ma ...

  5. CentOS7系统ifconfig无法使用的解决方法

    在使用RAKsmart美国服务器的时候,如果安装的CentOS7操作系统的话,可能会经常用到“ifconfig”命令.ifconfig命令大多是用于CentOS 6版本下面,主要用于查看网卡配置信息. ...

  6. flask中cookie和session设置

    flask中cookie和session介绍   一.cookie: 在网站中,http请求是无状态的.也就是说即使第一次和服务器连接后并且登录成功后,第二次请求服务器依然不能知道当前请求是哪个用户. ...

  7. python实例 列表

    #! /usr/bin/python # -*- coding: utf8 -*- #列表类似Javascript的数组,方便易用 #定义元组 word=['a','b','c','d','e','f ...

  8. 【洛谷】P1876 开灯

    P1876 开灯 题目背景 该题的题目是不是感到很眼熟呢? 事实上,如果你懂的方法,该题的代码简直不能再短. 但是如果你不懂得呢?那...(自己去想) 题目描述 首先所有的灯都是关的(注意是关!),编 ...

  9. 洛谷P1390 公约数的和 [2017年6月计划 数论12]

    P1390 公约数的和 题目描述 有一天,TIBBAR和LXL比赛谁先算出1~N这N个数中每任意两个不同的数的最大公约数的和.LXL还在敲一个复杂而冗长的程序,争取能在100s内出解.而TIBBAR则 ...

  10. 图文结合深入理解 JS 中的 this 值

    图文结合深入理解 JS 中的 this 值 在 JS 中最常见的莫过于函数了,在函数(方法)中 this 的出现频率特别高,那么 this 到底是什么呢,今天就和大家一起学习总结一下 JS 中的 th ...