我用命令调用存储过程。我收到记录集中的结果。现在我需要进行一些计算,因此需要知道返回的记录数。 RecordSet.RecordCount 应该给我,但只返回 -1。我尝试了 CursorType 和 CursorLocation 的不同值,尝试了 MoveLast。没有任何帮助。
我做了一个临时解决方案,假设记录数是固定的。
这里有很多关于 RecordCount 的主题,还有我读过的文章,但似乎没有任何帮助。是我使用命令的问题吗?我看到的大多数示例都不使用命令。
我是一名经验丰富的程序员,但不太习惯 SQL 和 VBA。谁可以给我一些帮助?
最诚挚的问候, 沃尔夫冈
Sub CallStoredProcedure()
Dim Conn As ADODB.Connection, RecordSet As ADODB.RecordSet
Dim Command As ADODB.Command
Dim ConnectionString As String, StoredProcName As String
Dim LoginID As ADODB.Parameter, Entity_Id As ADODB.Parameter
Application.ScreenUpdating = False
Set Conn = New ADODB.Connection
Set RecordSet = New ADODB.RecordSet
Set Command = New ADODB.Command
'w
RecordSet.CursorType = adOpenStatic
RecordSet.CursorLocation = adUseClient
ConnectionString = "Provider=SQLOLEDB;Data Source=HIQARBL218\SQLEXPRESS;Initial Catalog=SweSalaryStore;Trusted_Connection=yes;"
On Error GoTo CloseConnection
Conn.Open ConnectionString
StoredProcName = "dbo.getInfoFromSQLDB"
With Command
.ActiveConnection = Conn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
Set EMPNR = Command.CreateParameter("@EMPNR", adVarChar, adParamInput, 100, "107")
Command.Parameters.Append EMPNR
Set PERNR = Command.CreateParameter("@PERNR", adVarChar, adParamInput, 100, "1111110008")
Command.Parameters.Append PERNR
Set CMPNR = Command.CreateParameter("@CMPNR", adVarChar, adParamInput, 100, "5612")
Command.Parameters.Append CMPNR
Set PERIODFROM = Command.CreateParameter("@PERIODFROM", adVarChar, adParamInput, 100, "1001")
Command.Parameters.Append PERIODFROM
Set PERIODTO = Command.CreateParameter("@PERIODTO", adVarChar, adParamInput, 100, "1701")
Command.Parameters.Append PERIODTO
Set RecordSet = Command.Execute
Sheets("Sheet1").Range("A5").CopyFromRecordset RecordSet
'loop to get column headings.
For i = 0 To RecordSet.Fields.Count - 1
Sheets("Sheet1").Cells(1, i + 1).Value = RecordSet.Fields(i).Name
Next i
'Calculate last row in RecordSet
Dim lastRow As Integer
lastRow = 2000
'lastRow = RecordSet.RecordCount 'NOT WORKING!!!
'Average OB
Dim AvgOB As Double
AvgOB = Excel.WorksheetFunction.Average(Range(Sheets("Sheet1").Cells(5, 2), Sheets("Sheet1").Cells(lastRow, 2)))
AvgOB = Excel.WorksheetFunction.Round(AvgOB, 2)
Sheets("Sheet1").Cells(2, 2).Value = AvgOB
Sheets("Sheet1").Cells(3, 2).Value = AvgOB * 12
RecordSet.Close
Conn.Close
On Error GoTo 0
Application.ScreenUpdating = True
Exit Sub
CloseConnection:
Application.ScreenUpdating = True
MsgBox "SQL Stored Procedure Did Not Execute Sucessfully!", vbCritical, "SQL Error"
Conn.Close
End Sub
你已经完成了
Sheets("Sheet1").Range("A5").CopyFromRecordset RecordSet
所以此时返回的记录数就是从a5往下占用的行数:
Dim lastrow as long 'not integer!
lastrow = Sheets("Sheet1").Range("A5").currentregion.rows.count + 4
加四是从第 5 行开始
Conn.CursorLocation = adUseClient
这样就解决了。在这里找到它: ADODB RecordSet RecordCount 不返回有用信息