Language

SQL Server のプロバイダー統計情報

Microsoft.Data.SqlClient では、ランタイム統計がサポートされます。 有効なSqlConnection オブジェクトのStatisticsEnabled プロパティをTrueに設定して、統計を有効にします。

統計を有効にした後、RetrieveStatistics オブジェクトで特定時点のスナップショットを取得するために IDictionary を呼び出します。 カウンターを読み取るには、順不同の名前と値のペアを列挙します。 カウンターをリセットするには、ResetStatistics を呼び出します。

統計を有効にしていない場合、 RetrieveStatistics は例外なしで各カウンターの初期値を返します。 統計を無効にすると、カウンターはその時点まで収集された値を保持します。

すべての統計情報の値は、接続ごとに収集されます。

使用できる統計情報の値

Microsoft SQL Server プロバイダーは、18 個の統計値を公開します。 ディクショナリの Count プロパティを読み取り、使用可能なエントリの数を取得します。 すべてのカウンターは、C# では long、Visual Basic では Long と呼ばれる 64 ビット型 Int64 を使用しています。

最大値 Int64.MaxValueは (2^63)-1 です。 その上限では、カウンターは正確ではなくなります。 したがって、統計量の最大有効値は Int64.MaxValue - 1、または (2^63)-2 となります。

注

返される統計の数、名前、および順序は将来変更される可能性があるため、プロバイダー統計情報を返す場合には、辞書を使用します。 アプリケーションでは、辞書にある特定の値に依存しないようにする必要がありますが、その値が存在するかどうかを確認し、それに応じて分岐する必要があります。

次の表では、使用可能な統計値について説明します。 個々の値のキー名は、.NET Framework の地域別バージョン全体でローカライズされているわけではありません。

キー名 説明
BuffersReceived アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、SQL Server からプロバイダーが受信した表形式データ ストリーム (TDS) パケットの数を返します。
BuffersSent 統計が有効になった後にプロバイダーから SQL Server に送信された TDS パケットの数を返します。 大規模なコマンドでは、複数のバッファーが必要になる場合があります。 たとえば、大規模なコマンドがサーバーに送信され、6 個のパケットが必要な場合、ServerRoundtrips は 1 ずつ増え、BuffersSent は 6 ずつ増えます。
BytesReceived アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、SQL Server からプロバイダーが受信した TDS パケット内のデータのバイト数を返します。
BytesSent アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、TDS パケットで SQL Server に送信されるデータのバイト数を返します。
ConnectionTime 統計情報が有効になった後に接続が開かれている時間 (ミリ秒) を示します (接続が開かれる前に統計情報が有効になっていた場合は、合計接続時間を示します)。
CursorOpens アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、接続経由でカーソルが開かれた回数を返します。

SELECTステートメントによって返される読み取り専用/順方向専用の結果はカーソルとは見なされないため、このカウンターには影響しません。
ExecutionTime 統計情報が有効になってから、プロバイダーが処理に費やした累計時間 (ミリ秒) を返します。この時間には、サーバーからの応答を待つために費やされた時間と、プロバイダー自体がコードを実行するために費やした時間が含まれます。

タイミング コードが含まれるクラスは次のとおりです。

SqlConnection

SqlCommand

SqlDataReader

SqlDataAdapter

SqlTransaction

SqlCommandBuilder

パフォーマンスが重視されるメンバーをできるだけ小規模に保つため、次のメンバーは時刻指定されません。

SqlDataReader

this[] 演算子 (すべてのオーバーロード)

GetBoolean

GetChar

GetDateTime

GetDecimal

GetDouble

GetFloat

GetGuid

GetInt16

GetInt32

GetInt64

GetName

GetOrdinal

GetSqlBinary

GetSqlBoolean

GetSqlByte

GetSqlDateTime

GetSqlDecimal

GetSqlDouble

GetSqlGuid

GetSqlInt16

GetSqlInt32

GetSqlInt64

GetSqlMoney

GetSqlSingle

GetSqlString

GetString

IsDBNull
IduCount アプリケーションがプロバイダーの使用を開始し、統計情報を有効にした後、接続を介して実行された INSERT、 DELETE、および UPDATE ステートメントの合計数を返します。
IduRows アプリケーションがプロバイダーの使用を開始し、統計情報を有効にした後、接続を介して実行された INSERT、 DELETE、および UPDATE ステートメントの影響を受ける行の合計数を返します。
NetworkServerTime アプリケーションがプロバイダーを使って開始され、統計情報が有効になった後にプロバイダーがサーバーからの応答を待つために費やした累計時間 (ミリ秒) を返します。
PreparedExecs アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、接続経由で実行された準備済みコマンドの数を返します。
Prepares アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、接続経由で準備されたステートメントの数を返します。
SelectCount アプリケーションが統計を有効にした後に接続を介して実行される SELECT ステートメントの数を返します。 カーソルから行を取得する FETCH ステートメントが含まれます。 SqlDataReader のステートメントについて、SELECT が結果の末尾に到達した時点で、プロバイダーはカウント値を更新します。
SelectRows アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、選択された行の数を返します。 この数には、SQL ステートメントによって生成されたすべての行が反映され、呼び出し元によって実際に使用されなかった行も含まれます。 たとえば、結果セット全体を読み取る前にデータ リーダーを終了しても、数には影響しません。 これには、FETCH 文を介してカーソルから取得された行が含まれます。
ServerRoundtrips アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、接続によってコマンドがサーバーに送信され、応答が返された回数を返します。
SumResultSets アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、使用された結果セットの数を返します。 たとえば、これにはクライアントに返される結果セットが含まれます。 カーソルの場合、各フェッチまたはブロックフェッチ操作は、独立した結果セットと見なされます。
Transactions アプリケーションがプロバイダーの使用を開始し、統計情報が有効になった後に、ロールバックを含む開始されたユーザー トランザクションの数を返します。 自動コミットをオンにして接続が実行されている場合、各コマンドはトランザクションと見なされます。

このカウンターでは、後でトランザクションがコミットされるか、ロール バックされるかに関係なく、BEGIN TRAN ステートメントが実行されるとすぐにトランザクション数が増えます。
UnpreparedExecs アプリケーションがプロバイダーの使用を開始し、統計情報を有効にした後、接続を通じて実行された未準備のステートメントの数を返します。

値の取得

次のコンソール アプリケーションは、接続で統計情報を有効にして、4 つの各統計情報の値を取得し、コンソール ウィンドウに出力する方法を示します。

注

次の例では、SQL Server に含まれるサンプル AdventureWorks データベースを使用します。 サンプル コードに示されている接続文字列は、データベースがローカル コンピューターにインストールされ、使用可能であることを前提としています。 必要に応じて、お使いの環境に合わせて接続文字列を変更してください。

Option Strict On

Imports System
Imports System.Collections
Imports System.Data
Imports Microsoft.Data.SqlClient

Module Module1

  Sub Main()
    Dim connectionString As String = GetConnectionString()

    Using awConnection As New SqlConnection(connectionString)
      ' StatisticsEnabled is False by default.
      ' It must be set to True to start the
      ' statistic collection process.
      awConnection.StatisticsEnabled = True

      Dim productSQL As String = "SELECT * FROM Production.Product"
      Dim productAdapter As _
          New SqlDataAdapter(productSQL, awConnection)

      Dim awDataSet As New DataSet()

      awConnection.Open()

      productAdapter.Fill(awDataSet, "ProductTable")

      ' Retrieve the current statistics as
      ' a collection of values at this point
      ' and time.
      Dim currentStatistics As IDictionary = _
          awConnection.RetrieveStatistics()

      Console.WriteLine("Total Counters: " & _
          currentStatistics.Count.ToString())
      Console.WriteLine()

      ' Retrieve a few individual values
      ' related to the previous command.
      Dim bytesReceived As Long = _
          CLng(currentStatistics.Item("BytesReceived"))
      Dim bytesSent As Long = _
          CLng(currentStatistics.Item("BytesSent"))
      Dim selectCount As Long = _
          CLng(currentStatistics.Item("SelectCount"))
      Dim selectRows As Long = _
          CLng(currentStatistics.Item("SelectRows"))

      Console.WriteLine("BytesReceived: " & bytesReceived.ToString())
      Console.WriteLine("BytesSent: " & bytesSent.ToString())
      Console.WriteLine("SelectCount: " & selectCount.ToString())
      Console.WriteLine("SelectRows: " & selectRows.ToString())

      Console.WriteLine()
      Console.WriteLine("Press any key to continue")
      Console.ReadLine()
    End Using

  End Sub

  Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,
    ' you can retrieve it from a configuration file.
    Return "..."
  End Function
End Module
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;

namespace CS_Stats_Console_GetValue
{
  class Program
  {
    static void Main(string[] args)
    {
      string connectionString = GetConnectionString();

      using (SqlConnection awConnection =
        new SqlConnection(connectionString))
      {
        // StatisticsEnabled is False by default.
        // It must be set to True to start the
        // statistic collection process.
        awConnection.StatisticsEnabled = true;

        string productSQL = "SELECT * FROM Production.Product";
        SqlDataAdapter productAdapter =
          new SqlDataAdapter(productSQL, awConnection);

        DataSet awDataSet = new DataSet();

        awConnection.Open();

        productAdapter.Fill(awDataSet, "ProductTable");
        // Retrieve the current statistics as
        // a collection of values at this point
        // and time.
        IDictionary currentStatistics =
          awConnection.RetrieveStatistics();

        Console.WriteLine("Total Counters: " +
          currentStatistics.Count.ToString());
        Console.WriteLine();

        // Retrieve a few individual values
        // related to the previous command.
        long bytesReceived =
            (long) currentStatistics["BytesReceived"];
        long bytesSent =
            (long) currentStatistics["BytesSent"];
        long selectCount =
            (long) currentStatistics["SelectCount"];
        long selectRows =
            (long) currentStatistics["SelectRows"];

        Console.WriteLine("BytesReceived: " +
            bytesReceived.ToString());
        Console.WriteLine("BytesSent: " +
            bytesSent.ToString());
        Console.WriteLine("SelectCount: " +
            selectCount.ToString());
        Console.WriteLine("SelectRows: " +
            selectRows.ToString());

        Console.WriteLine();
        Console.WriteLine("Press any key to continue");
        Console.ReadLine();
      }

    }
    private static string GetConnectionString()
    {
      // To avoid storing the connection string in your code,
      // you can retrieve it from a configuration file.
      return "...";
    }
  }
}

すべての値の取得

次のコンソール アプリケーションは、接続で統計情報を有効にし、使用可能なすべての統計情報の値を列挙子を使って取得して、コンソール ウィンドウに出力する方法を示します。

注

次の例では、SQL Server に含まれるサンプル AdventureWorks データベースを使用します。 サンプル コードに示されている接続文字列は、データベースがローカル コンピューターにインストールされ、使用可能であることを前提としています。 必要に応じて、お使いの環境に合わせて接続文字列を変更してください。

Option Strict On

Imports System
Imports System.Collections
Imports System.Data
Imports Microsoft.Data.SqlClient

Module Module1
  Sub Main()
    Dim connectionString As String = GetConnectionString()

    Using awConnection As New SqlConnection(connectionString)
      ' StatisticsEnabled is False by default.
      ' It must be set to True to start the
      ' statistic collection process.
      awConnection.StatisticsEnabled = True

      Dim productSQL As String = "SELECT * FROM Production.Product"
      Dim productAdapter As _
          New SqlDataAdapter(productSQL, awConnection)

      Dim awDataSet As New DataSet()

      awConnection.Open()

      productAdapter.Fill(awDataSet, "ProductTable")

      ' Retrieve the current statistics as
      ' a collection of values at this point
      ' and time.
      Dim currentStatistics As IDictionary = _
          awConnection.RetrieveStatistics()

      Console.WriteLine("Total Counters: " & _
          currentStatistics.Count.ToString())
      Console.WriteLine()

      Console.WriteLine("Key Name and Value")

      ' Note the entries are unsorted.
      For Each entry As DictionaryEntry In currentStatistics
        Console.WriteLine(entry.Key.ToString() & _
            ": " & entry.Value.ToString())
      Next

      Console.WriteLine()
      Console.WriteLine("Press any key to continue")
      Console.ReadLine()
    End Using

  End Sub

  Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,
    ' you can retrieve it from a configuration file.
    Return "..."
  End Function
End Module
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.Data.SqlClient;

namespace CS_Stats_Console_GetAll
{
  class Program
  {
    static void Main(string[] args)
    {
      string connectionString = GetConnectionString();

      using (SqlConnection awConnection =
        new SqlConnection(connectionString))
      {
        // StatisticsEnabled is False by default.
        // It must be set to True to start the
        // statistic collection process.
        awConnection.StatisticsEnabled = true;

        string productSQL = "SELECT * FROM Production.Product";
        SqlDataAdapter productAdapter =
            new SqlDataAdapter(productSQL, awConnection);

        DataSet awDataSet = new DataSet();

        awConnection.Open();

        productAdapter.Fill(awDataSet, "ProductTable");

        // Retrieve the current statistics as
        // a collection of values at this point
        // and time.
        IDictionary currentStatistics =
            awConnection.RetrieveStatistics();

        Console.WriteLine("Total Counters: " +
            currentStatistics.Count.ToString());
        Console.WriteLine();

        Console.WriteLine("Key Name and Value");

        // Note the entries are unsorted.
        foreach (DictionaryEntry entry in currentStatistics)
        {
          Console.WriteLine(entry.Key.ToString() +
              ": " + entry.Value.ToString());
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to continue");
        Console.ReadLine();
      }

    }
    private static string GetConnectionString()
    {
      // To avoid storing the connection string in your code,
      // you can retrieve it from a configuration file.
      return "...";
    }
  }
}

関連項目