hardikv has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to write followings.
Requirement: query "Employee" table for emp_id and first_name, for each returned emp_id, query customer table for customer_name where id=emp_id(from employee table).
but not getting expected output. Any problem with the code?
#!/home/y/bin/perl use DBI; use File::Basename; #Database handler my $dbh= DBI->connect("dbi:mysql:$conf{MSQL_DB}:$conf{MSQL_DB_HOST}:33 +06", "$conf{MSQL_DB_USER}" , "$conf{MSQL_DB_PSW}" , { RaiseError => 1 +, AutoCommit =>0} ) || die "Database Connection Failed: $DBI::errstr" + ; print "$conf{MSQL_DB} DB :Connection succeeded\n"; my $pr = qq{select emp_id, first_name from employee where city= "Atlan +ta" }; #stage prepare and execute my $sth = $dbh->prepare($pr); $sth->execute(); # bind sql columns $sth->bind_columns( undef, \$emp_id, \$first_name); while ($sth->fetch) { print "EMP_ID = $emp_id, FirstName=$first_name \n"; # Capture the quarantine_stage_id my $pr1 = qq{select customer_name from customer where id = $emp_id } +; # Prepare and Execute the SQL statement my $sth1 = $dbh->prepare($pr1); $sth1->execute(); $cust_id; $sth1->bind_columns( undef, \$cust_id ); while ($sth1->fetch) { print "Customer Table: Customer ID = $cust_id \n"; if ($emp_id == $cust_id) { print "\n Match\n"; } else {print "Doesn't Match"} } $sth1->finish(); } $sth->finish(); $dbh->disconnect();

Replies are listed 'Best First'.
Re: how to use nested statement handler?
by wfsp (Abbot) on Nov 12, 2009 at 08:46 UTC
    my $pr1 = qq{select customer_name from customer where id = $emp_id } +; my $sth1 = $dbh->prepare($pr1); $sth1->execute(); $cust_id; $sth1->bind_columns( undef, \$cust_id );
    I reckon that inspite of the name of the variable it actually contains customer_name which you are comparing with $emp_id which is probably not what you want.

    Notes: Use strict and warnings
    You most likely could do this with a JOIN. Check the SQL docs.

    Update: Also, have a look at Placeholders in the mighty DBI docs.

Re: how to use nested statement handler?
by stefbv (Priest) on Nov 12, 2009 at 09:55 UTC
    In the second select statement use '?':
    my $pr1 = qq{select customer_name from customer where id = ? };
    and move the parameter to execute
    $sth1->execute($emp_id);