65.9K
CodeProject 正在变化。 阅读更多。
Home

如何检索已执行 T-SQL 命令的 SqlConnection 统计信息

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.80/5 (6投票s)

2007年10月8日

CPOL

1分钟阅读

viewsIcon

35275

示例代码,描述如何检索有关已执行的 T-SQL 命令的统计信息。

引言

在这篇简短的文章中,我想说明一个示例代码,描述如何可以检索通过 SqlConnection 执行的 T-SQL 语句的统计信息。

背景

在开发 PragmaSQL T-SQL 编辑器时,使用初始版本的用户想知道 T-SQL 语句(DML)执行后受影响的行数。我第一次尝试是跟踪 Management Studio 发送到服务器的 T-SQL 语句。但这没用,因为 Management Studio 没有发送任何额外的语句来确定受影响的行数。我第二次尝试是连接到 SqlInfoMessageEventHandler 并检查服务器返回的信息消息。但是,SQL Server 没有通过此事件发送有关已执行语句的任何额外信息。然后,当我查看 SqlConnection 属性时,我注意到了 StatisticsEnabled 属性,这正是满足我要求的。

使用代码

通过 SqlConnection 检索统计信息非常简单。以下是示例代码

//
// 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);
  }
}

就这样。您可以探索字典项以获取其他统计数据。SqlConnection 统计数据包括有关已执行的 T-SQL 语句的时间和其他有趣的统计信息。

注意:当然,从 SqlConnection 收集统计信息会增加脚本执行的时间。我没有测量时间的增加,但在我的情况下,这并不重要。

© . All rights reserved.