Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Using multiple values in a SQL "in" statement

by scorpio17 (Monsignor)
on May 01, 2013 at 21:30 UTC ( #1031654=note: print w/ replies, xml ) Need Help??


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

my @id=(1,2,3,4); my $question_mark_string = join(',', ('?') x scalar(@id) ); # ?,?,?,? my $sth = $dbh1->prepare("SELECT name FROM table where id in ( $questi +on_mark_string )") or die "Couldn't prepare statement: " . $dbh1->err +str; $sth->execute(@id)


Comment on Re: Using multiple values in a SQL "in" statement
Download Code
Re^2: Using multiple values in a SQL "in" statement
by jhourcle (Prior) on May 02, 2013 at 02:28 UTC

    I either use that logic, or when I'm lazy about typing:

    my $sth = $dbh1->prepare('SELECT name FROM table WHERE id IN ( ?'.(',?' x $#id).' )') or ...

    ... but I wouldn't recommend this if other people might be expected to actually maintain it.

Re^2: Using multiple values in a SQL "in" statement
by perlvroom (Acolyte) on May 02, 2013 at 17:51 UTC
    This worked great. thanks. Can you give me a brief explanation of what's happening at this line?  my $question_mark_string = join(',', ('?') x scalar(@id) );

      It's three operations. The x operator, is either a string or list multiplier. Here, it's being used on an list, as the item is in parens:

         ('?') x scalar(@id)

      scalar(@id) gives the number of items in the array. So we end up with a list of question marks the same size as the @id array.

      The join will flatten a list into a single string, placing the first argument in between each item. So we're placing a comma between each of the question marks.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1031654]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-08-23 10:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (173 votes), past polls