Search code examples
oracle-databaseplsqlnested-table

Oracle-PL/SQL Functions with return type nested table Error Type is incomplete or malformed


CREATE TYPE dname AS OBJECT
(
  depno      NUMBER,
  cnt_dname  NUMBER
);
/

CREATE TYPE nt_dname_dname AS TABLE of dname;
/

CREATE OR REPLACE FUNCTION f1 RETURN nt_dname 
AS    
    nt_dname        t_d     := t_d();
    n               NUMBER  := 0;
BEGIN
    FOR x IN 
    (
        SELECT  department_id, count(employee_id)
        FROM    employees
        GROUP BY department_id
    )
    LOOP
        nt_dname.EXTEND;
        n               := n+1;
        nt_dname(n)     := dname(x.depno,x.cnt_dname);
    END LOOP; 

    RETURN t_d;
END;
/   

I'm getting the following error message

Error: PL/SQL: Compilation unit analysis terminated
Error(1,20): **PLS-00320: the declaration of the type of this expression is 
incomplete or malformed**

Kindly suggest where it is wrong. I'm trying to get count of employees in each department and giving it as output (RETURN nested_table).


Solution

  • The following compiles, though I haven't tested it:

    create or replace function f1
        return nt_dname_dname
    as
        t_d nt_dname_dname := nt_dname_dname();
        n   number := 0;
    begin
        for r in (
            select department_id as depno
                 , count(employee_id) as cnt_dname
            from   employees
            group  by department_id
        )
        loop
            t_d.extend;
            n := n + 1;
            t_d(n) := dname(r.depno, r.cnt_dname);
        end loop;
    
        return t_d;
    end;
    

    Personally I would review all of the naming, as dname, nt_dname_dname and t_d are a bit confusing, to me at least.