http://www.perlmonks.org?node_id=1031698


in reply to Using multiple values in a SQL "in" statement

Assuming you wanted the contents of @id in place of the question mark:

use strict; use warnings; my @id=(1,2,3,4,5); my $sql = "SELECT name FROM table where id in (".join( ",", @id).")"; print "$sql\n";

Replies are listed 'Best First'.
Re^2: Using multiple values in a SQL "in" statement
by space_monk (Chaplain) on May 02, 2013 at 09:54 UTC

    Normally your answers are very good, but this is not one of those answers. :-)

    Putting values directly into a SQL statement is a classic example of what not to do, because it is vulnerable to SQL injection attacks if the ID array values are externally sourced. The reason it is recommended to bind values in is to protect themselves from this sort of thing! :-)

    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

      Notice how, in one of the examples above, a string is (easily ...) constructed that consists of one-or-more question marks separated by commas.   This string is inserted dynamically (and safely) into the SQL string.   A corresponding parameter is added to the list of parameters at the same time, and the two are provided together when the query is run.   This technique is suitably dynamic, yet safe from injection.

      I will also endorse the notion of using DBIx::Class ... or SQL::Abstract if you have a lot of existing code to deal with.   They are solid and helpful.

      Thanks for the explanation. I had already realized that I did not read the question careful enough but I had not understood the full significance.