So I've got a big pile of tables in a mySQL database and I want to get a list of only the tables that have data; that is, I want to list all tables but those with zero rows. The best way I've been able to come up with to do this is the relatively ugly following code. There must be a better way!
#Assuming $sth has just been executed with a "show tables" query
while(@tmp = $sth->fetchrow_array())
{
my $tablename = $tmp[0];
my $sth2 = $dbh->prepare("select count(*) from $tablename");
$sth2->execute();
$numrows = ($sth2->fetchrow_array())[0];
if($numrows > 0)
{
push @tables, $tablename;
}
}
The whole having to create and execute another statement just seems... excessive. Non-perl like. It's especially pesky since DBI won't let me do something like this, which at least would allow me to call "prepare" only once:
my $sth2 = $dbh->prepare("select count(*) from ?");
$sth2->execute($tablename);
Apologies if this is more an SQL question than a perl question... I've poked around the DBI docs and haven't seen anything obvious.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.