Monday, April 06, 2015

Collections Initialisation in Oracle


This is one new thing I learned today about initialising a collection variable. If the varaible is initialised without giving the record count, then we need to extend the collection variable to add data to it. But if the variable is initialised with null then we need not extend the variable. Below is the sample code to explain that.

DECLARE

       TYPE PSOUG_TAB IS TABLE OF NUMBER;

       PTAB PSOUG_TAB;

BEGIN

        PTAB := PSOUG_TAB();

        --PTAB.EXTEND;

        PTAB(1) := 100;

        DBMS_OUTPUT.PUT_LINE('VALUE AT INDEX(1) IS '||PTAB(1));

        PTAB.EXTEND(5,1);

        DBMS_OUTPUT.PUT_LINE('VALUE AT INDEX(4) IS '||PTAB(4));

END;

The above code would throws an error, if the PTAB variable is not extended before addiing records to it. But the below code would not throw an error.

DECLARE

       TYPE PSOUG_TAB IS TABLE OF NUMBER;

       PTAB PSOUG_TAB;

BEGIN

        PTAB := PSOUG_TAB(null);

        --PTAB.EXTEND;

        PTAB(1) := 100;

        DBMS_OUTPUT.PUT_LINE('VALUE AT INDEX(1) IS '||PTAB(1));

        PTAB.EXTEND(5,1);

        DBMS_OUTPUT.PUT_LINE('VALUE AT INDEX(4) IS '||PTAB(4));

END;

The above code has been taken from http://psoug.org/definition/extend.htm .