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

Hi,

I am using DBI library to connect to Oracle dB. I am using fetchrow_hashref() function to retrive data from a select query

The problem I have is the order of the columns in the select query. It is not the same as what I give in the select statement

For eg, suppose I have select e1,e2,e3,e4 from emp; I get the order of the columns as e1,e4,e3,e2 How do I ensure that I get the same order in the resultset as I define in the select query

Replies are listed 'Best First'.
Re: Select query result sets
by moritz (Cardinal) on Aug 20, 2010 at 13:48 UTC
    Hashes don't have an intrinsic ordering; if you want to preserve the order, use selectrow_arrayref instead.
    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Select query result sets
by roboticus (Chancellor) on Aug 20, 2010 at 14:13 UTC

    You can use fetchrow_arrayref as moritz suggested, or you can refer to the columns by name. I prefer using column names, as I find the code easier to read. Something like:

    while (my $hr = $S->fetchrow_hashref) { my $cur_total = $hr->{Quantity} * $hr->{Unit_Price}; my $cur_tax = 0; $cur_tax = $cur_total * $hr->{Tax_Rate} if $hr->{Taxable} eq 'Y'; ... }

    That's more readable (to me, at any rate) than a bunch of array subscripts that I have to remember. And if the query changes a bit, I don't need to worry about renumbering the indices.

    ...roboticus

Re: Select query result sets
by Tux (Canon) on Aug 20, 2010 at 14:23 UTC

    As moritz said, a hash has no order, and why would you need an "order" in a hashref?

    my $sth = $dbh->prepare ("select a1, a2, a3, a4 from tbl"); $sth->execute; my %rec; $sth->bind_columns (\@rec{my @fld = @{$sth->{NAME_lc}}); while ($sth->fetch) { say "Column a1: $rec{a1}"; }

    Then @fld contains the fields returned from the select in the order of how Oracle returns them.


    Enjoy, Have FUN! H.Merijn
Re: Select query result sets
by Anonymous Monk on Aug 23, 2010 at 09:14 UTC
    Hello Monks,

    Thank you for the reply. The reason for not using fetchrow->arrayref is we require the column names as well We need to pass the entire resultset (Column names & column values) to a hash which prints it to the file. The extract from the script is given below

    <p> Pls let me know how do I get the column names & values & pass to a has +h </p> $stmt = $dbh->prepare("$sql17"); $stmt->execute(); if($DBI::errstr) { warn "Execution of SQL failed: $DBI::errstr\n"; $dbh->rollback; closeOracleConnection($dbh); } else @rowData = $stmt->fetchrow_array(); $rowcnt = $#rowData; for ($i = 0; $i < $rowcnt; $i++) { @rs = $stmt->fetchrow_hashref(); push(@retArray,@rs); } $stmt->finish; if ($#retArray == -1) { print (stdout "\nCould not generate values\n"); exit (-1); }