in reply to Nesting prepared DBI handles

You're not just re-using the prepared statement, you're interrupting it in the middle of each use. The next execute() drops everything that was found and cached previously and loads up a fresh list ready to be fetched. There's only one prepare, so there's only one cache of results that can be fetched. The trick is to fetch all your results first before issuing the next execute.

sub get_children { my $parent_id = shift; $executed_handle = $prepared_handle->execute($parent_id); # first retrieve all the results my @results; while (my $pointer = $executed_handle->fetchrow_hashref) { push @results, $pointer->{parent_id}; } # now deal with the results foreach (@results) { $results .= $_."\n"; get_children($_); } }

I'll also note that since you appear to be fetching only a single column (parent_id), then you could also skip the whole execute/fetch loop and select the results directly into an array ref. But I suspect your example may have been trimmed down for the purpose of the question, so this may not apply.

my $parent_id = shift; # first retrieve all the results my $results_ref = $dbh->selectcol_arrayref( $prepared_handle, undef, $parent_id); # now deal with the results foreach (@$results_ref) { $results .= $_."\n"; get_children($_); }