Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

BULK COLLECT BEST PRACTICE

elessarJan 13 2014 — edited Jan 14 2014

Hi Everyone

    I was reading this blog by Steven Fuerstein reagrdindg bulk collects:-

http://www.oracle.com/technetwork/issue-archive/2008/08-mar/o28plsql-095155.html

  In it he suggests that the correct way to exit the cursor loop is when in record type in which you are fetching the cursor is zero and not when cursor is not found . Thie is done to make sure all rows are processed and none are left out.

   I did a little test of my own . Consider the emp table with a total of 12 records :-

DECLARE
  CURSOR EMP_CUR IS
    SELECT * FROM EMP;
  TYPE EMP_TAB IS TABLE OF EMP%ROWTYPE INDEX BY PLS_INTEGER;
  V_EMP_TAB EMP_TAB;
BEGIN
  OPEN EMP_CUR;
  LOOP
    FETCH EMP_CUR BULK COLLECT
      INTO V_EMP_TAB LIMIT 5;
    EXIT WHEN EMP_CUR%NOTFOUND;
    FOR IDX IN 1 .. V_EMP_TAB.COUNT LOOP
      DBMS_OUTPUT.put_line(IDX || ':- ' || V_EMP_TAB(IDX).ENAME);
    END LOOP;
  END LOOP;

  CLOSE EMP_CUR;
END;

    

This  gives the output of 10 rows as :-

 

1:- BLAKE
2:- TURNER
3:- JAMES
4:- ABC
5:- MARTIN
1:- CLARK
2:- KING
3:- MILLER
4:- DEF
5:- JOHN

Now consider the below code exactly the same but with exit condition shifted to bottom:-

DECLARE
  CURSOR EMP_CUR IS
    SELECT * FROM EMP;
  TYPE EMP_TAB IS TABLE OF EMP%ROWTYPE INDEX BY PLS_INTEGER;
  V_EMP_TAB EMP_TAB;
BEGIN
  OPEN EMP_CUR;
  LOOP
    FETCH EMP_CUR BULK COLLECT
      INTO V_EMP_TAB LIMIT 5;
      FOR IDX IN 1 .. V_EMP_TAB.COUNT LOOP
      DBMS_OUTPUT.put_line(IDX || ':- ' || V_EMP_TAB(IDX).ENAME);
    END LOOP;

  EXIT WHEN EMP_CUR%NOTFOUND;
  END LOOP;

  CLOSE EMP_CUR;
END

This gives output as:-

 

1:- BLAKE
2:- TURNER
3:- JAMES
4:- ABC
5:- MARTIN
1:- CLARK
2:- KING
3:- MILLER
4:- DEF
5:- JOHN
1:- ADAMS
2:- FORD

If this is the case please let me know why this way is not recommended in the blog.

Are there any adverse effects of this way  I do not know about?

This post has been answered by unknown-7404 on Jan 13 2014
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 11 2014
Added on Jan 13 2014
16 comments
4,597 views