Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

returning first row of SQL query

by whittick (Acolyte)
on Mar 29, 2012 at 11:52 UTC ( [id://962354]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I have a script (below) and rather than cycle through each row of the table I would like to just return the first row. Is this possible?

my $query="SELECT severity, source, displayname FROM alert WHERE displ +ayname LIKE '%$displayname%' ORDER BY severity DESC"; my $sth=$dbh->prepare($query); $sth->execute(); #Loop through for each row returned while ( @row = $sth->fetchrow_array ) { $severity = $row[0]; $source = $row[1]; $displayname = $row[2]; print "$severity\n"; }

Thanks

Replies are listed 'Best First'.
Re: returning first row of SQL query
by moritz (Cardinal) on Mar 29, 2012 at 12:35 UTC

    If you just want one row, there's no need to do a while-loop at all:

    $sth->execute; my ($serverity, $source, $displayname) = $sth->fetchrow_array; $sth->finish; print "severity\n";

    Just because the docs use fetchrow_* together with while doesn't mean you have to do that too. It's good to stick to the patterns from the documentation as long as your use case also matches that of the documentation.

Re: returning first row of SQL query
by Anonymous Monk on Mar 29, 2012 at 12:02 UTC

    Is there a reason why you cannot put LIMIT 1 (or TOP 1 or whatever your server dialect requires) into your SQL query?

    Anyway, $sth->finish discards the rest of the rows.

      LIMIT 1 works perfectly, sorry I hadn't thought of solving the problem with SQL rather than through perl!

Re: returning first row of SQL query
by marto (Cardinal) on Mar 29, 2012 at 12:29 UTC
Re: returning first row of SQL query
by wallisds (Beadle) on Mar 29, 2012 at 19:22 UTC
    my $query="SELECT severity, source, displayname FROM alert WHERE displayname LIKE '%$displayname%' ORDER BY severity DESC LIMIT 1"; my ($severity, $source, $displayname) = $dbh->selectrow_array($query);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://962354]
Approved by ww
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-19 02:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found