I have a table like following:

```
ID         Type      ParentID
001         C          007
002         C          005
003         B          007
004         C          008
005         R          NULL
006         C          004
007         B          004
008         R          009
009         X          NULL

```

The type hierarchy is X>R>C=B. I need to find all the records' R parent for B and C. 
The challenge is some of the B or C records' parents are B or C and X needs to be excluded.
Results would be:

```
ID         Type      ParentID     MasterParentID
001         C          007           008
002         C          005           005
003         B          007           008
004         C          008           008
005         R          NULL          NULL
006         C          004           008
007         B          004           008 
008         R          009           NULL
009         X          NULL          NULL

```

Any suggestions? Much appreciated.