Forum OpenACS Q&A: Multiple Selection...while loops

Collapse
Posted by Bob OConnor on

Here is a simple question for which I hope there is a simple answer:
I want to do a:

set selection [ns_db select $db "select...
...
while {[ns_db getrow $db $selection]} {
set_variables_after_query

And then do the same loop AGAIN on the same tcl page.
How do I reset the database so that I can loop thru again?

TIA - Bob

Collapse
Posted by Michael A. Cleverly on
Assuming you don't break out of your while loop early (in which case you'd need to do a ns_db flush $db) then simply do another set selection [ns_db select $db "..."] and loop through it in a subsequent while loop.

You can re-use any handle as long as you've previously read back any waiting rows, or have manually flushed it.

Collapse
Posted by Alex Sokoloff on
But doesn't that just re-run the query? Hypothetically it could return different data from the first time, although it would usually work fine. Is there some way to run through the ns_set twice?
Collapse
Posted by Michael A. Cleverly on
The query is only re-run if the SQL statement (the ... in ns_db select $db "...") is the same. There are plenty of Tcl scripts in ACS/OpenACS that grab a handle, then execute multiple (different) queries. Often times the subsequent queries are based on data retrieved in the first.

The $selection ns_set holds different data with each call to ns_db getrow. If for some reason you want to preserve the ns_sets (and have, say, a list or array of ns_set's) then you'd need to do an ns_set copy $selection inside each while loop and lappend the newly copied set to a list (or stuff it inside an array or something).

Collapse
Posted by Bob OConnor on

Thank you Michael. For further clarity I also found this document written by Phillip G. in July 1999:

http://www.arsdigita.com/asj/aolserver/introduction-2.html

-Bob