語言

SQL Server 的提供者統計資料

Microsoft.Data.SqlClient 支援執行階段統計資料。 透過將有效 StatisticsEnabled 物件的 SqlConnection 屬性設定為 True 來啟用統計。

啟用統計後,呼叫 RetrieveStatistics,以取得 IDictionary 物件在某個時間點的快照。 列舉其無序的名稱/值對以讀取計數器。 要重設計數器,請呼叫 ResetStatistics。

如果你沒有啟用統計,則 RetrieveStatistics 會回傳每個計數器的初始值,且不會拋出例外。 停用統計後,計數器會保留到該點為止收集的數值。

所有收集到的統計值都是以個別連線為基礎。

可用的統計值

Microsoft SQL Server 提供者會顯示 18 個統計值。 閱讀字典的 Count 屬性以取得可用詞條的數量。 所有計數器都使用 Int64、在 C# 中名為 Long 且在 Visual Basic 中名為 long 的 64 位元型別。

最大值,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 從游標擷取資料列的敘述。 對 SELECT 語句而言,提供者會在 SqlDataReader 到達結果末尾時更新計數。
SelectRows 在應用程式開始使用提供者並啟用統計功能後,傳回所選擇的資料列數目。 此計數器會反映 SQL 陳述式產生的所有資料列,即使呼叫者並未實際取用的資料列也算在內。 例如,在讀取整個結果集之前關閉資料讀取器並不會影響計數。 這包括透過 FETCH 語句從游標中擷取的列。
ServerRoundtrips 傳回應用程式開始使用提供者並啟用統計資料之後,連線傳送命令至伺服器並收到回覆的次數。
SumResultSets 傳回應用程式開始使用提供者並啟用統計資料之後,已使用的結果集數目。 例如,這會包含傳回給用戶端的任何結果集。 針對游標,每個擷取或區塊抓取作業都被視為獨立的結果集。
Transactions 傳回應用程式開始使用提供者並啟用統計資料 (包括復原) 之後,已啟動的使用者交易數目。 如果是使用自動認可來執行連線,系統會將每個命令都視為一個交易。

此計數器會在 BEGIN TRAN 敘述執行後立即遞增交易計數,無論交易是被提交還是之後回滾。
UnpreparedExecs 傳回應用程式開始使用提供者並啟用統計功能後,透過連線所執行的未準備好的陳述式數目。

取得一個值

下列主控台應用程式會顯示如何在連線上啟用統計資料、擷取四個獨立統計資料值,並將其寫到主控台視窗。

注意

以下範例使用了 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 "...";
    }
  }
}

另請參閱