1

我正在尝试收集一些 SQL 查询的统计信息。我正在使用SqlDbConnection类的RetrieveStatistics()方法来获取统计信息,并使用SqlCommand的ExecuteReader()方法来运行查询。 RetrieveStatistics()方法返回填充了执行查询的统计信息的字典。当我运行常规查询时,字典的SelectRows属性包含查询返回的实际行数。但是当我运行存储过程时,SelectRows 总是为零,尽管 reader 肯定包含行。

我在每个查询之前调用ResetStatistics()并将StatisticsEnabled设置为 true。

这是我的 Powershell 代码:

### Stored procedure

$cn = New-Object system.data.sqlclient.sqlconnection
$cn.ConnectionString = "Data Source=localhost;Initial Catalog=XXXX;Integrated Security=SSPI"
$cn.StatisticsEnabled = $true
$cmd = $cn.CreateCommand()
$cmd.CommandText = "[dbo].[spGetXXXX]"
$cmd.CommandType = "StoredProcedure"
$cn.Open()
$cmd.ExecuteReader()
# several rows returned
$cn.RetrieveStatistics()

Name                           Value
----                           -----
BytesReceived                  300
SumResultSets                  1
ExecutionTime                  5
Transactions                   0
BuffersReceived                1
IduRows                        0
ServerRoundtrips               1
PreparedExecs                  0
BytesSent                      132
SelectCount                    1
CursorOpens                    0
ConnectionTime                 51299
Prepares                       0
SelectRows                     0
UnpreparedExecs                1
NetworkServerTime              3
BuffersSent                    1
IduCount                       0

### Regular SQL query
$cn2 = New-Object system.data.sqlclient.sqlconnection
$cn2.ConnectionString = "Data Source=localhost;Initial Catalog=XXXX;Integrated Security=SSPI"
$cn2.StatisticsEnabled = $true
$cmd2 = $cn2.CreateCommand()
$cmd2.CommandText = "SELECT * FROM XXXX"
$cn2.Open()
$cmd2.ExecuteReader()

#rows returned

$cn2.RetrieveStatistics()

Name                           Value
----                           -----
BytesReceived                  12357
SumResultSets                  1
ExecutionTime                  12
Transactions                   0
BuffersReceived                2
IduRows                        0
ServerRoundtrips               1
PreparedExecs                  0
BytesSent                      98
SelectCount                    1
CursorOpens                    0
ConnectionTime                 11407
Prepares                       0
SelectRows                     112
UnpreparedExecs                1
NetworkServerTime              0
BuffersSent                    1
IduCount                       0
4

1 回答 1

0

这两个查询的区别在于,在存储过程调用读取器保持打开状态后,行号统计信息不会更新。

所以正确的代码应该是:

$connectionn.ResetStatistics()
$reader = $command.ExecuteReader()
$reader.Close() # !
$connection.RetrieveStatistics()
于 2012-08-31T19:02:36.940 回答