in reply to building sql statement

It's been a long time sine I've done serious database work, but have you looked at the DBI/DBD modules for your database? You may just be doing this the hard way.