in reply to Re^4: Query using more than one array!
in thread Query using more than one array!

use strict; use List::MoreUtils qw/zip/; use DBI; my @reg_num = qw/12345 98564 33234 112345 87564 2345678 938566 1234486 + 223456 123488/; my @month = qw/03 01 01 10 05 11 03 05 02 09/; my $sql_part = join ' or ', map {'(reg_num = ? AND month = ?)'} 1 .. @ +reg_num; my $dbh = DBI->connect("DBI:ODBC:$myserver",$u, $p,); my $sth = $dbh->prepare( "SELECT name, last_name, reg_num, month, year FROM members WHERE $sql_part AND year='2009"); $sth->execute(zip @reg_num, @month);

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^6: Query using more than one array!
by Anonymous Monk on May 14, 2009 at 14:14 UTC
    What about something like this:

    use strict; use DBI; my @reg_num = qw/12345 98564 33234 112345 87564 2345678 938566 1234486 + 223456 123488/; my @month = qw/03 01 01 10 05 11 03 05 02 09/; my $dbh = DBI->connect("DBI:ODBC:$myserver",$u, $p,); my $sql = "select name, last_name, reg_num, month, year + from members where year='2009' AND ("; for my $i (0 .. $#reg_num) { $sql .= "reg_num = '$reg_num[$i]' AND month = '$month[$i]' "; $sql .= 'OR ' unless $i == $#reg_num; } $sql .= ')'; # don't forget the ) on the end of the SQL my $sth = $dbh->prepare($sql, { RaiseError => 1 }); $sth->execute();


    Let me know what you think?!
      As a general rule it is best to use placeholders in your SQL. It avoids all kind of nasty surprises, there is no need to quote the parameters yourself and although in this particular example I see no problem, why not always using a "Best Practice"? Also it makes for easier code IMHO.

      Using join and map further avoids to have to check explicitly for the "end" condition. And personally I like map: it is so powerful and compact, yet still it conveys its meaning in a very clear way.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James