Matt M
Matt M

Reputation: 3779

How can I tell which record causes the error while doing a cursor fetch?

Is there any way to tell which record is causing the error while doing a cursor fetch? For example, let's say I have a table with one column (varchar2), "value", with the following values:

1, 2, 3, 4, g, 5, 6

I do the following:

DECLARE
    answer number;
    CURSOR c1 IS
    SELECT to_number(value) FROM table;
BEGIN
   OPEN c1;  
   LOOP
      FETCH c1 INTO answer;
      EXIT WHEN c1%NOTFOUND;
      DBMS_OUTPUT.PUT_LINE(answer);
   END LOOP;
   CLOSE c1;
 EXCEPTION WHEN invalid_number THEN    
    dbms_output.put_line('an invalid number exception was encountered');
END;

Would it ouput without issue until 'g' was encountered? This is a trivial example of a real issue I'm trying to debug. In the real example, it outputs the exception message and nothing else. Does this mean it's the first record that causes the issue, or it just doesn't work this way?

Upvotes: 3

Views: 1990

Answers (1)

DCookie
DCookie

Reputation: 43533

It should output values until the row with the exception is encountered, at least according to my test of your procedure. That is, unless you're doing an ORDER BY in your query, in which case you'll likely see the exception before any rows are fetched.

You can see for yourself what is being fetched by trying it without the TO_NUMBER function in your select. Something like this could help:

DECLARE
    answer number;
    temp   VARCHAR2(10);
    CURSOR c1 IS
    SELECT ID FROM table;
BEGIN
   OPEN c1;
   LOOP
      FETCH c1 INTO temp;
      EXIT WHEN c1%NOTFOUND;
      DBMS_OUTPUT.PUT(temp||': Converted is: ');
      dbms_output.put_line(to_number(temp));
   END LOOP;
   CLOSE c1;
 EXCEPTION WHEN invalid_number THEN    
    dbms_output.put_line('an invalid number exception was encountered');
           WHEN OTHERS THEN
    dbms_output.put_line('Some other error');
END;
/

Upvotes: 6

Related Questions