Select directly in the hierarchical user type

Is it possible to make a selection directly in the hierarchical user type?

Imagine a table structure like this:

PARENT
------
ID
NAME

CHILD
-----
ID
PARENT_ID
NAME

In addition, I have user types such as:

create or replace type child_item as object
(
  ID NUMBER(10),
  NAME VARCHAR(255)
);

create or replace type children_table as table of child_item;

create or replace type parent_item as object
(
  ID NUMBER(10),
  NAME VARCHAR(255),
  CHILDREN CHILDREN_TABLE
);

create or replace type parent_table as table of parent_item;

And an expression like this:

select * from parent p inner join child c on p.id = c.parent_id;

Now I want the result of this statement to be in a type object parent_table. Is this possible without using a complex loop FOR?

+3
source share
2 answers

You can use COLLECT :

SELECT parent_item(p.ID, 
                   p.NAME, 
                   CAST(COLLECT(child_item(c.id, c.NAME)) AS children_table))
  FROM PARENT p
 INNER JOIN child c ON p.id = c.parent_id
 GROUP BY p.ID, p.NAME

This will return a list PARENT_ITEMthat you can BULK COLLECT in PARENT_TABLE.

You can use COLLECT again in an external query to directly get PARENT_TABLE:

SELECT CAST(COLLECT(parents) AS parent_table)
  FROM (SELECT parent_item(p.ID, 
                           p.NAME, 
                           CAST(COLLECT(child_item(c.id, c.NAME)) 
                             AS children_table)
                          ) parents
          FROM PARENT p
         INNER JOIN child c ON p.id = c.parent_id
         GROUP BY p.ID, p.NAME)
+4

CAST(MULTISET()):

with data as (
select p.id pid,p.name pname,cast(multiset(select c.id,c.name 
from child c where c.parent_id=p.id) AS children_table) ct
from parent p
)
select cast(multiset(select pid,pname,ct from data) as parent_table) 
from dual;
+1

All Articles