Q
Problem solve Get help with specific problems with your technologies, process and projects.

How do I find out if a cursor returned any records?

I opened a cursor and I want to know if the query returned any records or not. How do I do this? I tried with the "EXCEPTION, WHEN NO_DATA_FOUND" construct, but it doesn't work.

I opened a cursor and I want to know if the query returned any records or not. How do I do this? I tried with the "EXCEPTION, WHEN NO_DATA_FOUND" construct, but it doesn't work.
You can use attributes of the cursor to return the number of rows fetched from the cursor. You are probably familiar with the %NOTFOUND attribute to know when to exit from a loop after the last row is returned from the FETCH command. You can also use the %ROWCOUNT attribute to determine how many rows have been fetched from the cursor so far. The following code example shows how %ROWCOUNT can be used:
DECLARE
   CURSOR c1 IS SELECT empid,ename FROM emp;
   id   emp.empid%TYPE;
   name emp.ename%TYPE;
   counter NUMBER;
BEGIN
   counter:=0;
   OPEN c1;
   LOOP
      FETCH c1 INTO id,name
      EXIT WHEN c1%NOTFOUND;
      counter := c1%ROWCOUNT;
      DBMS_OUTPUT.PUT_LINE(' Rows processed: '||counter);
   END LOOP;
   CLOSE c1;
END;
/
Other cursor attributes include %FOUND and %ISOPEN.
This was last published in February 2006

Dig Deeper on Oracle database design and architecture

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close