检索存储过程的统计信息,SelectRows始终为0

时间:2012-08-31 15:04:41

标签: c# sql sql-server powershell

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

我在每次查询前调用 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

1 个答案:

答案 0 :(得分:0)

两个查询之间的区别在于存储过程后调用阅读器保持打开状态,并且行号统计信息未更新。

所以正确的代码就像:

$connectionn.ResetStatistics()
$reader = $command.ExecuteReader()
$reader.Close() # !
$connection.RetrieveStatistics()