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

时间:2016-08-17 17:50:08

标签: c# visual-studio tsql sqlcommand

我使用session类从Visual Studio 2015运行查询。我需要知道运行查询所用的时间和结果集的大小。我知道我可以通过SQL Server Management Studio获取该信息,但我不知道如何从Visual Studio获取该信息。

3 个答案:

答案 0 :(得分:2)

您可以使用StopWatch计时:

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

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

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

答案 1 :(得分:0)

首先,进入Visual Studio中的SQL Server对象资源管理器(View> SQL Server对象资源管理器)。然后选择查询您选择的数据库。右键单击>新查询。在运行查询之前,请选择“包含实际执行计划”'靠近页面顶部:Picture of button near top of page

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

我希望这有帮助!

答案 2 :(得分:0)

您可以使用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;

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

要查找表的所有统计信息,请使用以下代码,以便循环显示所有统计信息并获取每个统计信息:

var allStat = myTable.Statistics;

请查看以下链接以获取更多信息:

Statistic Class on MSDN