Classic ASP 3.0 Create Array from a Recordset

John Swaringen picture John Swaringen · Dec 30, 2010 · Viewed 28.8k times · Source

I'm trying to fix an ASP Classic app and when I try to create an array from a Recordset Object. However I Can't get it to work correctly.

This code gives me a single record (the last one), but as far as I can see it is correct:

Dim Products
Dim Products_cmd
Dim Products_numRows

Set Products_cmd = Server.CreateObject ("ADODB.Command")
Products_cmd.ActiveConnection = Conn
Products_cmd.CommandText = "SELECT prod_id, prod_description FROM dbo.products ORDER BY prod_description ASC" 
Products_cmd.Prepared = true

Set Products = Products_cmd.Execute
Products_numRows = 0

Dim arrProducts()
arrProducts = Products.GetRows()

Using this code gives me an "Subscript out of range: 'UBound'

Dim Products
Dim Products_cmd
Dim Products_numRows

Set Products_cmd = Server.CreateObject ("ADODB.Command")
Products_cmd.ActiveConnection = Conn
Products_cmd.CommandText = "SELECT prod_id, prod_description FROM dbo.products ORDER BY prod_description ASC" 
Products_cmd.Prepared = true

Set Products = Products_cmd.Execute
Products_numRows = 0
Dim arrProducts()
Dim counter

For counter = 0 to Products.RecordCount - 1
    ReDim Preserve arrProducts(counter,2)
    arrProducts(counter,0) = Products.Fields.Item("prod_id").Value
    arrProducts(counter,1) = Products.Fields.Item("prod_description").Value
    Products.MoveNext
Next
Response.Write(Str(UBound(arrProducts)))

Any ideas would be GREATLY appreciated...

Answer

Eduardo Molteni picture Eduardo Molteni · Dec 30, 2010

Your are almost there, the problem is that GetRows() returns a 2 dimensional array, and you need to tell Ubound what dimension do you want.

Working code:

Dim Products
Dim Products_cmd
Dim Products_numRows

Set Products_cmd = Server.CreateObject ("ADODB.Command")
Products_cmd.ActiveConnection = Conn
Products_cmd.CommandText = "SELECT prod_id, prod_description FROM dbo.products ORDER BY prod_description ASC" 
Products_cmd.Prepared = true

Set Products = Products_cmd.Execute

Dim arrProducts
arrProducts = Products.GetRows()

dim i
response.write "<table>"
For i = 0 to ubound(arrProducts, 2)
   response.write "<tr>"
   response.write("<td>" + trim(i+1))
   response.write("<td>" + trim(arrProducts(0,i)))
   response.write("<td>" + trim(arrProducts(1,i)))
next
response.write "</table>"
%>