... $sth->execute($objid); my @rows = @{$sth->fetchall_arrayref()}; $sth->finish(); foreach $row (@rows) { ... #### Sub GetChildren{ my ($objid) = @_; my $sth = $dbh->prepare(<<' ;'); SELECT objid, type FROM table WHERE parentid=? ; # Initial fetch. $sth->execute($objid); @rows = @{$sth->fetchall_arrayref()}; while (@rows) { my ($objid, $type) = @{shift(@rows)}; if ($type eq "Container") { # Add to todo list. $sth->execute($objid); push(@rows, @{$sth->fetchall_arrayref()}); next; } do something else } $sth->finish(); }