Re: query to trace all parents

From: Mark D Powell <Mark.Powell_at_eds.com>
Date: 24 Jun 2005 06:13:55 -0700
Message-ID: <1119618835.903186.126910_at_o13g2000cwo.googlegroups.com>


And what database is in use? If you have Oracle then you can use the connect by clause to solve this:

UT1 > set echo on
UT1 > drop table pc;

Table dropped.

UT1 > create table pc ( parent varchar2(01), child varchar2(01) );

Table created.

UT1 > insert into pc values ('A','B');

1 row created.

UT1 > insert into pc values ('B','C');

1 row created.

UT1 > insert into pc values ('B','E');

1 row created.

UT1 > insert into pc values ('C','D');

1 row created.

UT1 > insert into pc values ('E','F');

1 row created.

UT1 > insert into pc values ('E','G');

1 row created.

UT1 >
UT1 > select parent
  2 from pc
  3 connect by child = prior parent
  4 start with child = 'C'
  5 /

P
-
B
A

UT1 > select parent
  2 from pc
  3 connect by child = prior parent
  4 start with child = 'F'
  5 /

P
-
E
B
A

UT1 > select parent
  2 from pc
  3 connect by child = prior parent
  4 start with child = 'B'
  5 /

P
-
A

Oracle even provides functions that work with connect by to show the full path etc...

SQL> l

  1 select sys_connect_by_path(ename,'_')   2 from emp
  3 connect by mgr = prior empno
  4* start with ename = 'KING'
SQL> / SYS_CONNECT_BY_PATH(ENAME,'_')



_KING
_KING_JONES
_KING_JONES_SCOTT
_KING_JONES_SCOTT_ADAMS
_KING_JONES_FORD
_KING_JONES_FORD_SMITH

<snip>

Don't have Oracle. Well Joe Celko wrote a whole book on dealing with hierarchies using SQL.

HTH -- Mark D Powell -- Received on Fri Jun 24 2005 - 15:13:55 CEST

Original text of this message