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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |