Reputation: 2209
I have a dynamic function to call a stored procedure and store the recordset in an array, which I want to use in another sub. But I don't get the result in an array like this:
Array(0,0) = 1
Array(0,1) = Miller
Array(1,0) = 2
Array(1,1) = Jones
Array(2,0) = 3
Array(2,1) = Jackson
....
My Array result is like this:
Array(0,0) = 1
Array(1,0) = Miller
Array(0,1) = 2
Array(1,1) = Jones
Array(0,2) = 3
Array(1,2) = Jackson
....
To understand the process I'm showing you the SQL-statement
:
CREATE PROCEDURE dbo.sp_GetAllPersons
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT u.ID, u.Name
FROM dbo.v_Users u
END
GO
The function to get the recordset and store it in an array:
Public Function fGetDataBySProc(ByVal sProcName As String) As Variant
...
Dim Cmd As New ADODB.Command
With Cmd
.ActiveConnection = cn
.CommandText = sProcName
.CommandType = adCmdStoredProc
End With
Dim ObjRs As New ADODB.Recordset: Set ObjRs = Cmd.Execute
Dim ArrData() As Variant
If Not ObjRs.EOF Then
ArrData = ObjRs.GetRows(ObjRs.RecordCount)
End If
ObjRs.Close
cn.Close
fGetDataBySProc = ArrData
End Function
The sub where the function is called:
Public Sub cbFillPersons()
Dim sProcString As String: sProcString = "dbo.sp_GetAllPersons"
Dim ArrData As Variant: ArrData = fGetDataBySProc(sProcString)
Dim i as Integer
' Just for testing
For i = LBound(ArrData) To UBound(ArrData)
Debug.Print "AddItem: " & ArrData(0, i)
Debug.Print "List: " & ArrData(1, i)
Next
End Sub
I don't know, what I'm doing wrong. Maybe it is the .GetRows()
-method?
Upvotes: 1
Views: 2082
Reputation: 54807
You could transpose your resulting array using the getTransposedArray
function.
Then the last line in your fGetDataBySProc
function would be:
fGetDataBySProc = getTransposedArray(ArrData)
The Function
Function getTransposedArray(Data As Variant) _
As Variant
Dim LB2 As Long
LB2 = LBound(Data, 2)
Dim UB2 As Long
UB2 = UBound(Data, 2)
Dim Result As Variant
ReDim Result(LB2 To UB2, LBound(Data, 1) To UBound(Data, 1))
Dim i As Long
Dim j As Long
For i = LBound(Data, 1) To UBound(Data, 1)
For j = LB2 To UB2
Result(j, i) = Data(i, j)
Next j
Next i
getTransposedArray = Result
End Function
Upvotes: 2