The function described in the title is simple, the following example is also very simple, but you can according to your own needs to expand the function, I here just to a point, hehe ..., you can actually have time to do a SQL Server profiler to play a play. Supports SqlServer2005 and SqlServer2008
The first step:
Add Reference: Microsoft.SqlServer.ConnectionInfo
Using Microsoft.SqlServer.Management.Trace;
Using Microsoft.SqlServer.Management.Common;
Step Two:
Configure connection Information
Connectioninfobase conninfo = new Sqlconnectioninfo ();
((Sqlconnectioninfo) conninfo). ServerName = "ServerName";
((Sqlconnectioninfo) conninfo). UserName = "UserName";
((Sqlconnectioninfo) conninfo). Password = "Password";
((Sqlconnectioninfo) conninfo). Useintegratedsecurity = false;
Step Three:
Create the MYTDF.TDF file and put it in the same folder as the running program.
Note: the. tdf file is used later as a template for reading data, and you can create a new file yourself by creating a template in SQL Server Profiler.
Read information (including T-SQL statements and so on, add as needed, add only get the T-SQL statement function that is executing)
Traceserver trace = new Traceserver ();
Trace. Initializeasreader (Conninfo, "MYTDF.TDF");
while (trace. Read ())
{
statements;
Console.WriteLine (trace["TextData"]);
}
Console.read ();
Trace. Close ();
All code:
Using System;
Using System.Collections.Generic;
Using System.Text;
Using Microsoft.SqlServer.Management.Trace;
Using Microsoft.SqlServer.Management.Common;
Namespace ConsoleApplication2
{
Class Program
{
static void Main (string[] args)
{
Connectioninfobase conninfo = new Sqlconnectioninfo ();
((Sqlconnectioninfo) conninfo). ServerName = "ServerName";
((Sqlconnectioninfo) conninfo). UserName = "UserName";
((Sqlconnectioninfo) conninfo). Password = "Password";
((Sqlconnectioninfo) conninfo). Useintegratedsecurity = false;
Traceserver trace = new Traceserver ();
Trace. Initializeasreader (Conninfo, "MYTDF.TDF");
while (trace. Read ())
{
statements;
Console.WriteLine (trace["TextData"]);
}
Console.read ();
Trace. Close ();
}
}
}
Original address: http://www.cnblogs.com/skysing/archive/2009/08/18/1548696.html
Programmatically record all T-SQL statements executed by SQL Server on the current server < go >