0

I've a set of elements in an array which is read from a file.Now i want to use this array value in sql statement in in Claus!for that i need to enclose these string by '(single quote).so I've tried with for loop to do this! is there any way to do this same opp? like any in build functions like qw... code:

open FILE, "<tab_name.txt" or die $!;
my @tab=<FILE>;
chomp(@tab);
@tab=split(",",$tab[0]);#set of like eg:$tab[0]=asc,cdf,sad,casd,aea,aee,asdf 
my @sql_str=();
foreach my $item(@tab){

        $item="'".$item."'";
        push(@sql_str,$item);#add comma
         push(@sql_str,",");
}
pop(@sql_str);#remove lase unwanted comma

i got the desired output like 'asc','cdf','sad','casd','aea','aee','asdf' but is there any way to do this?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Thiyagu ATR
  • 2,224
  • 7
  • 30
  • 44

3 Answers3

3

Do You need an array, or a string fr the in clasue? I assume a string is proper, so what about this?

my $sql_str = join ",", map { $dbh->quote $_ } split ",", $tab[0];

But Miguel Prz is right, You should use parameter binding instead! This will save Your Oracle server for parsing over and over again the same SQL statements.

Other minor issue. If You use my @tab=<FILE>; it will read the whole file. But in the code only the first line is used. So You could use my $tab = <FILE>; to read only the first line.

TrueY
  • 7,360
  • 1
  • 41
  • 46
3

To do this with placeholders (i.e., properly), you need to first gather all the values for the IN clause into a single array (@values) so that you know how many of them there are, then:

my $in_clause = join(', ', ('?') x scalar @values);
my $sql_str = "select field1, field2 from my_table where id in ( $in_clause )";
my $sth = $dbh->prepare($sql_str);
$sth->execute(@values);

(scalar isn't strictly necessary here, but included to make it a little more obvious what's going on for the OP.)

Dave Sherohman
  • 45,363
  • 14
  • 64
  • 102
2

This may works:

my $sql_str = join ',' => map { $_ = qq|'$_'|; } @tab;

But, manually building your SQL this way is a bad idea™. Parameter binding is the proper way to solve this problem.

Community
  • 1
  • 1
Miguel Prz
  • 13,718
  • 29
  • 42