Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.tools -> Re: Testing row existence in PL/SQL block?

Re: Testing row existence in PL/SQL block?

From: Daniel A. Morgan <dmorgan_at_exesolutions.com>
Date: Fri, 20 Jul 2001 23:15:38 -0700
Message-ID: <3B591E0A.5661D024@exesolutions.com>

Gamma wrote:

> I have a PL/SQL block that looks sorta like this:
>
> declare
> e int;
> begin
> select count(*) into e from SomeTable
> where SomeConditions;
> if e=0
> DoSomething
> else
> DoSomethingElse
> end if;
> DoMoreStuff;
> end;
>
> In summary, the block does one of two things depending on whether
> at least one row exists in SomeTable with certain conditions. The
> trouble is that the block seems inefficient; it counts all of the
> rows, but actually I can stop as soon as I find one. (Often it's
> even the case that there will be one row at most.)
>
> What would be the proper way to do this? I considered using a
> slightly different select-into statement, and then using exception
> handling to catch NO_DATA_FOUND, but then I couldn't return to the
> main execution block, so that's out.
>
> Another way might be to declare a cursor with the appropriate
> select, and then test it with %NOTFOUND. But often the select I
> create will use values obtained partway through the execution block,
> and by then it's too late to declare the cursor.
>
> Any ideas?
>
> --
>
> Paul Brinkley
> gamma_at_clark.net

Presumably your table has a primary key which is, by definition, not null so ...

BEGIN
   SELECT pk_field
   INTO x
   FROM some_table
   WHERE some_condition
   AND rownum = 1;

   do_something
EXCEPTION
   WHEN NODATAFOUND THEN
         do_something else
END; Daniel A. Morgan Received on Sat Jul 21 2001 - 01:15:38 CDT

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US