$dbh = DBI->connect($databaseName, $databaseUser, $databasePw) || die "Connect failed: $DBI::errstr "; $sth = $dbh->prepare("SELECT Name FROM currency_acc WHERE currency='SGD'"); #select the name from first table1 $sth->execute(); my $i=0; $count=0; while (@names = $sth->fetchrow_array()) { $count += ($names[0] =~ /^[A-Z]/i); #Counting howmany names need to be queried from the 2nd table for ($i=0; $i<$count; $i++) { $sth2 = $dbh->prepare("SELECT ACC, $names[$i], $names[$i++] FROM amount_type"); # Keeping the names as header $sth2->execute(); while(@new_result = $sth2->fetchrow_array()) { push @new_result2, $new_result[0]; } } } print "@new_result2 \n"; $sth->finish(); $sth2->finish();