BULK COLLECT WITH LIMIT Clause

BULK COLLECT WITH LIMIT Clause:

in example we take emp table,in emp table have total 14 records

declare
  cursor c1 is select * from emp;
  type tt is table of c1%rowtype index by binary_integer;
  t tt;
  cnt number :=0;
begin
     open c1;
     loop
          fetch c1 bulk collect into t limit 5;
          exit when c1%notfound;
             for i in 1.. t.count 
             loop
                 cnt :=cnt+1;
                 dbms_output.put_line(cnt ||'    '||t(i).ename);
             end loop;
      end loop;
 close c1;
end;
/
1    SMITH
2    ALLEN
3    WARD
4    JONES
5    MARTIN
6    BLAKE
7    CLARK
8    SCOTT
9    KING
10    TURNER


PL/SQL procedure successfully completed.


note:It only displayed 10 records, where are my last 4 rows? The problem is we are using "exit when c1%notfound;" just after bulk collect. In the 3rd iteration when Oracle bulk collected the last 4 rows and cursor got exhausted, Oracle Set c1%notfound as true and we exited from our for loop.

method 1
declare
  cursor c1 is select * from emp;
  type tt is table of c1%rowtype index by binary_integer;
  t tt;
  cnt number :=0;
begin
     open c1;
     loop
          fetch c1 bulk collect into t limit 5;
                       for i in 1.. t.count 
             loop
                 cnt :=cnt+1;
                 dbms_output.put_line(cnt ||'    '||t(i).ename);
             end loop;
 exit when c1%notfound;
      end loop;
 close c1;
end;

/
1    SMITH
2    ALLEN
3    WARD
4    JONES
5    MARTIN
6    BLAKE
7    CLARK
8    SCOTT
9    KING
10    TURNER
11    ADAMS
12    JAMES
13    FORD
14    MILLER

PL/SQL procedure successfully completed.

2nd method :
Alternatively we can also use collection.count to check if collection is empty after bulk collect operation, instead of using "%NOTFOUND" as in the following example.


declare
  cursor c1 is select * from emp;
  type tt is table of c1%rowtype index by binary_integer;
  t tt;
  cnt number :=0;
begin
     open c1;
     loop
          fetch c1 bulk collect into t limit 5;
  exit when t.count=0;
                       for i in 1.. t.count 
             loop
                 cnt :=cnt+1;
                 dbms_output.put_line(cnt ||'    '||t(i).ename);
             end loop;
      end loop;
 close c1;
end;
/
1    SMITH
2    ALLEN
3    WARD
4    JONES
5    MARTIN
6    BLAKE
7    CLARK
8    SCOTT
9    KING
10    TURNER
11    ADAMS
12    JAMES
13    FORD
14    MILLER

PL/SQL procedure successfully completed.

Comments

Popular posts from this blog

PRAGMA SERIALLY_REUSABLE

COLLECTION METHODS

CURSOR PARAMETERS