db_foreach

one of the documented procedures in this installation of the ACS
Usage:
db_foreach   sql   code_block   args
What it does:
Performs the SQL query $sql, executing $code_block once for each row with variables set to column values.

Example:

db_foreach "select foo, bar from greeble" {
    ns_write "<li>foo=$foo; bar=$bar\n"
} if_no_rows {
    # This block is optional.
    ns_write "<li>No greebles!\n"
}
Defined in: /web/philip/packages/acs-core/10-database-procs.tcl

Source code:


    if { [llength $args] != 0 } {
	if { [llength $args] != 2 ||  (![string equal [lindex $args 0] "else"] && ![string equal [lindex $args 0] "if_no_rows"]) } {
	    error "db_foreach called incorrectly: second argument must be 'else' or 'if_no_rows' and followed by another code block"
	}
    }

    db_with_handle db {
	set selection [ns_db select $db $sql]
	
	set counter 0
	while { [ns_db getrow $db $selection] } {
	    for { set i 0 } { $i < [ns_set size $selection] } { incr i } {
		upvar [ns_set key $selection $i] column_value
		set column_value [ns_set value $selection $i]
	    }
	    uplevel $code_block
	    incr counter
	}
	if { $counter == 0 && [llength $args] == 2 } {
	    uplevel [lindex $args 1]
	}
    }


philg@mit.edu