Skip to content
April 29, 2013 / Rodrigo Chiolas

If exists pl/sql

Problem

Sometimes it’s necessary to check if a record exists and perform an action, or do some other action if it not exists.

Example:

if exists (select * from mytable where id = 12345) begin
-- do some processing on existing record
end
else begin
-- do some other processing
end

Solution

We need to count the record that we want to check and save it to a variable. After that we just use the result of the count to decide what to do.

Example:

DECLARE 
  cnt NUMBER;
BEGIN
  SELECT COUNT(*)
   INTO cnt
    FROM mytable
  WHERE id = 12345;

  IF( cnt = 0 ) --if not exists
  THEN
    ...
  ELSE --if exists
    ...
  END IF;
END;

References

Link that I used to write this post: Original Link

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: