2

I am trying to run two WHILE NOT loops for a recordset. One of the loops counts the number of items whilst the other prints the results. I cannot alter the SQL query, so this is the counting method I'm left with.

setPeopleCount = 0
While NOT rsSetContents.EOF
    setPeopleCount = setPeopleCount + 1
rsSetContents.MoveNext
Wend

While NOT rsSetContents.EOF
    Response.Write rs.Fields("exampleItem")&"<br>"
rsSetContents.MoveNext
Wend

My problem is running the two loops. After the first loop has finished the count, the record cursor is at the end of the file, so when the next loop needs to run - it doesn't because EOF is true.

How can I reset the cursor back to the beginning of the file so the second loop can run?

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
TheCarver
  • 19,391
  • 25
  • 99
  • 149

3 Answers3

4

You can use MoveFirst.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms677527(v=vs.85).aspx

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
1

Could you not count on the bottom loop? Or perhaps read the records into an object array then you are free to iterate over it as many times as u want

RockThunder
  • 146
  • 4
  • Unfortunately not, I need to use the count before the second loop starts. I've just used rs.MoveFirst and it worked. Thanks anyway – TheCarver Dec 20 '11 at 22:50
0

The MoveFirst requires proper cursor on the recordset - if for example you'll change to different database the default cursor might change and the code might fail.

I would suggest you to store the values while counting, thus save the second loop:

setPeopleCount = 0
Dim exampleItems()
ReDim exampleItems(-1)
While NOT rsSetContents.EOF
    setPeopleCount = setPeopleCount + 1
    ReDim Preserve exampleItems(UBound(exampleItems) + 1)
    exampleItems(UBound(exampleItems)) = rs("exampleItem")
    rsSetContents.MoveNext
Wend

'instead of a loop, just this:
Response.Write(Join(exampleItems, "<br />"))
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208