I'm trying to pull some data from a SQLite DB, where I need to execute very similar queries several times. Specifically, I want to pull the list of distinct values out of 3 different columns. I then want to be able to push the list of distinct values into their own arrays, so I can molest them later.

The brute force way to do it is:

# query to get Centers $cent_sth=$dbh->prepare("SELECT DISTINCT Center FROM People"); $cent_sth->execute() or die "Failed to retrieve list of centers from d +atabase. $DBI::errstr"; print " Centers are:\n"; while (@centers = $cent_sth->fetchrow_array()) { print "\t@centers[0]\n" unless (@centers[0]!~/^\d{2} -/); } # query to get Divsions $div_sth=$dbh->prepare("SELECT DISTINCT Div FROM People"); $div_sth->execute() or die "Failed to retrieve list of centers from da +tabase. $DBI::errstr"; print " Divisions are:\n"; while (@divs = $div_sth->fetchrow_array()) { print "\t@divs[0]\n"; } # query to get Departments $dept_sth=$dbh->prepare("SELECT DISTINCT Dept FROM People"); $dept_sth->execute() or die "Failed to retrieve list of centers from d +atabase. $DBI::errstr"; print " Departments are:\n"; while (@depts = $dept_sth->fetchrow_array()) { print "\t@depts[0]\n"; }

I think I ought to be able to do the same thing by looping over the same code 3 times. Something like:

my %orgs = ("Center", "cent_sth", "Div", "div_sth", "Dept", "dept_sth" +) while (($name, $this_sth)=each (%orgs)){ $this_sth=$dbh->prepare("SELECT DISTINCT $name FROM People"); $this_sth->execute() or die "Failed to retrieve list of $name from + database. $DBI::errstr"; }

But I'm pretty sure I'm not naming my statement handlers in a way that will allow me to use them later. What's the smart way to do this?


In reply to Looping over multiple queries by Mad_Mac

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.