0

This is really getting annoying. The following is a method which is contained in a custom database class. I query data into a recordset then try to convert this data into an array w/o field names. It appears to be working within the function because I setup a response.write to check if there were any values. But once out of the function, things go haywire (the array is not the same).

Public Function To2Array()
    dim A, x, columns
    columns = Rs.Fields.Count
    Rs.MoveFirst()
    x = 0
    do until Rs.EOF
        Redim A(x+1,columns)
        for y = 0 to columns - 1
            A(x,y) = Rs.Fields.Item(y)
                            response.write A(x,y) 'returns correct value
        Next
        x = x + 1       
        Rs.MoveNext()
    loop
    To2Array = A
End Function 

I assign the return array but there appears to be nothing.

arr = db.To2Array()
response.write(arr(1,0)) 'returns nothing

Can anyone figure out what I'm doing wrong?

2 Answers 2

3
  1. You can only grow the last dimension of an VBScript array. So you need an colsXrows array.
  2. To keep the 'old' part of a dynamic array, you must ReDim Preserve.
  3. To get a two dimensional array from a recordset, use .GetRows - and avoid all risks of 'rolling your own'.
Sign up to request clarification or add additional context in comments.

3 Comments

Using GetRows is ideal. @annoying_squid Just to note that using ReDim in a loop should be avoided. If you really want to 'roll your own' then you could read the RecordCount and just ReDim once.. but GetRows is the much better option.
My mind is wired for C arrays. @Andy why is GetRows better than rolling your own?
GetRows is purpose-made to retrieve records form a recordset into an array - in one go. Read the link Ekkehard provided, noting that by not providing the number of rows it will retrieve ALL the rows from the recordset.
1

You lose the values in A every time you redim it. Using redim preserve prevents this, but you can only redim the last array dimension when you use preserve.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.