Move the statement handlers outside the recursive function. Then, instead of passing a dbh, you pass the properly initialized statement handlers;

In addition, you should change the fetch method, so you are sure that the recursed sth is not executing a nested operation while still handling the outer one.

This is untested but it should get you on track.

sub rebuild_tree { my $sth1 = shift; my $sth2 = shift; my $dir_ID = shift; my $left = shift; my $right = $left + 1; $sth1->execute($dir_ID) || return $right + 1; my $recs = $sth1->fetchall_arrayref(); for my $row (@$recs) { $right = rebuild_tree($sth1,$sth2, $row->[0], $right); } $sth2->execute($left, $right, $dir_ID); return $right + 1; } my $sql1 = "select ID, name from DIRECTORIES where parent_ID = ?"; my $sth1 = $dbh->prepare($sql1); my $sql2 = "update DIRECTORIES set lft = ?, rght = ? where ID = ?"; my $sth2 = $dbh->prepare($sql2); my ($dir_ID, $left) = (); # whatever you need my $right = rebuild_tree($sth1, $sth2, $dir_ID, $left );

Update
I remember now that have seen this approach before in one of Joe Celko's tricks in this article, which uses stored procedures to update the tree.

 _  _ _  _  
(_|| | |(_|><
 _|   

In reply to Re: DBI prepare and function recursion by gmax
in thread DBI prepare and function recursion by simon.proctor

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.