A procedure to check if the records are in an ancestor descendant relationship
This procedure takes two ids and prints if these ids stand in an ancestor descendant relationship.
The select statement first evaluates the start with and connect by conditions to build an »intermediate« record set. Then, after creating this intermediate record set, it evaluates the where clause.
If it finds a record that matches the id of descendant, it has found an ancestor descendant relationship, otherwise, it's not an ancestor descendant relationship.
create procedure is_ancestor_descendant(ancestor in varchar2, descendant in varchar2) as
cnt number;
begin
select
count(*) into cnt
from
parent_child
where
child_ = descendant
start with
parent_ = ancestor
connect by
prior child_ = parent_;
if cnt > 0 then
dbms_output.put_line(ancestor || ' is an ancestor of ' || descendant);
else
dbms_output.put_line(ancestor || ' is no ancestor of ' || descendant);
end if;
end;
/