Click here to Skip to main content
15,885,366 members
Articles / Database Development / SQL Server

How to retrieve SqlConnection statistics for executed T-SQL commands

Rate me:
Please Sign up or sign in to vote.
3.80/5 (6 votes)
7 Oct 2007CPOL1 min read 34.5K   20   3
Sample code describing how to retreive statistical information about the T-SQL commands executed.

Introduction

In this short article, I want to illustrate a sample code describing how you can retrieve statistical information about the T-SQL statements executed over a SqlConnection.

Background

While I was developing the PragmaSQL T-SQL editor, guys using the initial versions wanted to know how many rows were affected as a result of a T-SQL statement (DML) being executed. My first attempt was to trace the T-SQL statements sent by Management Studio to the server. But this was useless, since Management Studio was not sending any extra statements to figure out how many rows were affected. My second attempt was to wire-up to SqlInfoMessageEventHandler and inspect the info messages returned by the server. But, SQL Server was not sending any extra information about the executed statements via this event. Then, while I was looking at the SqlConnection properties, I noticed the StatisticsEnabled property, and this was what would meet my requirement.

Using the code

Retrieving statistical information over a SqlConnection is very simple. Here is the sample code:

C#
//
// Sample T-SQL execute code
//  
private void ExecuteSql(SqlConnection conn, string scriptText)
{
    SqlCommand cmd = null;
    try
    {
        conn.StatisticsEnabled = true;
        conn.ResetStatistics();
        cmd = new SqlCommand(conn, conn);
        cmd.ExecuteNonQuery();
        
        // Here is the sample wrapper to process statistics.
        ProcessConnectionStatistics(conn.RetrieveStatistics());
    }
    finally
    {
        conn.StatisticsEnabled = false;
        if(cmd != null)
         cmd.Dispose();
    }
}


// Sample function to process SqlConnection statistics
// This function only extracts the entry with name IduRows.
// to reflect the rows affected.
private void ProcessConnectionStatistics(IDictionary stats)
{
  foreach (object key in stats.Keys)
  {
    object statVal = stats[key];
    if (key == null || key.ToString().ToLowerInvariant() != 
        "IduRows".ToLowerInvariant())
      continue;

    string statValStr = statVal.ToString();
    if (String.IsNullOrEmpty(statValStr) || statValStr.Trim() == "0")
      continue;

    MessageBox.Show(String.Format("( %s ) rows affected.",statValStr);
  }
}

That is all. You can explore the dictionary items for other statistical data. The SqlConnection statistical data includes timing and other interesting statistics about the T-SQL statements executed.

Notice: Sure, gathering statistical information from the SqlConnection increases the time your scripts take to get executed. I did not measure the increase in time, but in my case, this was unimportant.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader PragmaTouch
Turkey Turkey
- Software developer
- Has BS degree in Computer Engineering
- Has MBA degree
- Programmed with C, C++, Delphi, T-SQL and recently C#
- Little educational experience with Prolog
- Feel enthusiasm about NHibernate and LINQ
- Love to develop on Cuyahoga Web Framework
- Developer of PragmaSQL Editor
(Code Project Members Choice Winner for 2009 and 2010)
- Developed JiraTouch and MoodleTouch for iPhone
- PragmaTouch Lead (www.pragmatouch.com)

Comments and Discussions

 
Generalsample of statistics would be helpful Pin
grundt9-Oct-07 5:11
grundt9-Oct-07 5:11 
GeneralRe: sample of statistics would be helpful Pin
Ali Ozgur9-Oct-07 5:21
Ali Ozgur9-Oct-07 5:21 
GeneralRe: sample of statistics would be helpful Pin
Syed Rizwan Shah17-Oct-07 1:10
professionalSyed Rizwan Shah17-Oct-07 1:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.