http://qs321.pair.com?node_id=181142


in reply to Creating Dynamic SQL statements using arrays

great question, one I have struggled with a lot myself. since I see that you're using DBI, I thought that I'd chime in with this.

the first line of code is borrowed directly from chromatic's DBI is OK article, and has been among the most helpful lines of code I've found in getting my SQL queries to behave the way I want them to:

my $values = join(', ', map { $dbh->quote($_) } @formdata{@fields});

uses a hash slice and the map function to make sure that whatever values are associated with the keys listed in @fields are quoted in such a way as to be properly understood by the SQL engine. Of similar use would be:

my $keys = join(', ' map {$dbh->quote_identifier($_) } @fields);

which would correctly quote your field names as appropriate for identifiers in an SQL statement.

You might also be able to use placeholders to speed the process up. If you are in a situation where the identifiers (left hand of the equal sign in your SQL query) are static, and only the values (right hand side of the equal sign in the query) are changing, you can use place holders and
$sth = $dbh->prepare_cached($sql)
passing the values as parameters when you execute the $sth. You can read more about this process in the article above, or at this node or in the documentation.

hope this added something,
--au

update: changed some things to improve formatting, clarity, and grammar... bah.