如何从 C# 代码中获取 SQL 查询统计信息?

How do you get a SQL query statistics info from code in C#?

我正在 运行使用 SqlCommand class 从 Visual Studio 2015 年开始查询。我需要知道 运行 查询所用的时间和结果集的大小。我知道我可以使用 SQL Server Management Studio 获取该信息,但我不知道如何从 Visual Studio.

获取它

首先,进入 Visual Studio 中的 SQL 服务器对象资源管理器(查看 > SQL 服务器对象资源管理器)。然后 select 查询您选择的数据库。右键单击 > 新建查询。在 运行 查询之前,select 'Include Actual Execution Plan' 在页面顶部附近:Picture of button near top of page

然后您可以 运行 查询,在页面底部您会看到多个选项卡,例如结果、消息和执行计划。 Select 执行计划,您将能够以百分比形式查看查询成本,但将鼠标悬停在成本或聚簇索引扫描部分上可以找到更多信息。

希望对您有所帮助!

您可以使用 StopWatch 来计时:

StopWatch sw = new StopWatch();
sw.Start();
// Run query here
sw.Stop();

// Check sw.ElapsedMilliseconds or some other property you prefer

要获得结果集的大小,您可以计算 datareader.Read() 或其他替代方法的迭代次数。

您可以使用 SMO。请尝试下面的代码。

Server myServer = new Server("ServerName");
myServer.ConnectionContext.LoginSecure = true;
myServer.ConnectionContext.Connect();

Database db = myServer.Databases["dbName"];

Table myTable = db.Tables["TableName", "SchemaName"];

Statistic stat = default(Statistic);
stat = new Statistic(myTable, "StatisticName");
StatisticColumn statcol = default(StatisticColumn);
statcol = new StatisticColumn(stat, "FieldName");
stat.StatisticColumns.Add(statcol);
stat.Refresh();
var x = stat.LastUpdated;

您还可以找到其他属性。您还可以更新统计信息甚至创建统计信息等等。

要查找 table 的所有统计信息,请使用以下代码,这样您就可以遍历所有统计信息并获取每个统计信息的信息:

var allStat = myTable.Statistics;

查看下方link了解更多信息:

Statistic Class on MSDN