use DBI; my $hour_db = DBI->connect("DBI:mysql:database=$db;host=$host;mysql_socket=/opt/lampstack-5.5.27-0/mysql/tmp/mysql.sock","root","", {'RaiseError' => 1}); my @column_names = ("MO_resp","MT_resp","AO_resp"); foreach my $column_name (@column_names) { my $hour_sth = $hour_db->prepare("Select sum($column_name) from $table_name where Date='$db_date' and Hour like='$hour:%'"); $hour_sth->execute() or die $DBI::errstr; ..... }