Search code examples
plsqlcursor

Cursor within cursor to compare same column's record not executing


I am working on small PL/SQL program which compare the column record with itself using cursor. When I execute the code it takes long time seems like falling in endless loop.

Table Data :-

STD
----
 2
 1
 4
 3
 6
 5
 8
 7
 10
 9
 12
 11

below is my code:-

declare 
s number;
s1 number;
c number := 0;
cursor c1 is (select std from data);
cursor c2 is (select std from data);
begin
open c1;
loop
    fetch c1 into s;
     open c2;
        loop
            fetch c2 into s1;
            if s < s1
            then    
                c := c + 1;
           end if;
        end loop;
     insert into con values(c);
     close c2;       
end loop;
close c1; 
end;
/

Expected result :-

C=10
C=10
C=8
C=8
C=6
C=6
C=4
C=4
C=2
C=2
C=0
C=null

Solution

  • You should add

    EXIT WHEN c1%NOTFOUND;

    EXIT WHEN c2%NOTFOUND;

    after corresponding fetch. e.g.

    declare 
    s number;
    s1 number;
    c number := 0;
    cursor c1 is (select std from data);
    cursor c2 is (select std from data);
    begin
    open c1;
    loop
        fetch c1 into s;
        EXIT WHEN c1%NOTFOUND;
         open c2;
            loop
                fetch c2 into s1;
                EXIT WHEN c2%NOTFOUND;
                if s < s1
                then    
                    c := c + 1;
               end if;
            end loop;
         insert into con values(c);
         close c2;       
    end loop;
    close c1; 
    end;
    /