Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PL/SQL - Pre actions if cursor is found

I have a simple cursor like this:

CURSOR emp_cur
IS
  SELECT *
    FROM employee
    WHERE age > 20; 

In my procedure, I want to do some pre-actions only if there are employee in cursor. After that pre-action, I process all rows.

I need this because only if exists employee in that cursor i need to cleanup some tables, otherwise i should "RETURN".

so the code could be:

OPEN emp_cur;
/* Here i need to do pre-action only if emp_cur has rows*/
IF /* has rows*/
THEN
  /* do some actions*/
END IF;

LOOP
  FETCH emp_cur INTO emp_rec;
  EXIT WHEN emp_cur%NOTFOUND;
END LOOP;

CLOSE emp_cur;

For now, i have a "dirty" solution where i open cursor:

  1. First to check if there are rows
  2. Do pre-action and close
  3. Open/fetch again to process rows, and close again
like image 401
Mistre83 Avatar asked Mar 20 '26 11:03

Mistre83


1 Answers

First to check if there are rows

You cannot know about the rows until you FETCH.

From documentation link ,

After a cursor or cursor variable is opened but before the first fetch, %FOUND returns NULL. After any fetches, it returns TRUE if the last fetch returned a row, or FALSE if the last fetch did not return a row.

Once you have fetched the rows, then before processing the rows, you could use %FOUND.

For example,

OPEN c1;
  LOOP
    FETCH c1 INTO my_ename, my_salary;
    IF c1%FOUND THEN  -- fetch succeeded
      -- Do something
    ELSE  -- fetch failed, so exit loop
      EXIT;
    END IF;
  END LOOP;
like image 134
Lalit Kumar B Avatar answered Mar 23 '26 02:03

Lalit Kumar B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!