Search code examples
oracle-databaseplsqlhierarchical-dataprocedurealter

Procedure to alter and update table on hierarchical relationship to see if there are any children


I have a hierarchical table on Oracle pl/sql. something like:

create table hierarchical (
   id             integer primary key,
   parent_id          references hierarchical ,
   name           varchar(100));

I need to create a procedure to alter that table so I get a new field that tells, for each node, if it has any children or not.

Is it possible to do the alter and the update in one single procedure? Any code samples would be much appreciated.

Thanks


Solution

  • You can not do the ALTER TABLE (DDL) and the UPDATE (DML) in a single step.

    You will have to do the ALTER TABLE, followed by the UPDATE.

    BEGIN
      EXECUTE IMMEDIATE 'ALTER TABLE hierarchical ADD child_count INTEGER';
      --
      EXECUTE IMMEDIATE '
      UPDATE hierarchical h
      SET child_count = ( SELECT COUNT(*)
                          FROM hierarchical h2
                          WHERE h2.parent_id = h.id )';
    END;
    

    Think twice before doing this though. You can easily find out now if an id has any childs with a query.

    This one would give you the child-count of all top-nodes for example:

    SELECT h.id, h.name, COUNT(childs.id) child_count
    FROM hierarchical h
    LEFT JOIN hierarchical childs ON ( childs.parent_id = h.id )
    WHERE h.parent_id IS NULL
    GROUP BY h.id, h.name
    

    Adding an extra column with redundant data will make changing your data more difficult, as you will always have to update the parent too, when adding/removing childs.