try this:create table tableA(childID int,name char(1),parentID int)insert into tableAselect 1,'a',-1 union allselect 2,'b',-1 union allselect 3,'c',1 union allselect 4,'d',3 union allselect 5,'e',2select G1.childID as G1_childID,G1.name as G1_childName,G1.parentID as G2_parentID,g2.name as G2_parentName,G2.parentID as G3_grandParentID,G3.name as G3_grandParendNameinto tableBFrom tableA as G1 --generation1 join tableA as G2 --generation2on g1.parentID = g2.childID join tableA as G3 --generation3on g2.parentID = g3.childIDwhereg1.parentID > 0union allselect G1.childID as G1_childID,G1.name as G1_childName,G1.parentID as G2_parentID,g2.name as G2_parentName,'' G3_grandParentID,'' as G3_grandParendNameFrom tableA as G1 --generation1 join tableA as G2 --generation2on g1.parentID = g2.childIDwhereg1.parentID > 0union allselect G1.childID as G1_childID,G1.name as G1_childName,'' as G2_parentID,'' as G2_parentName,'' G3_grandParentID,'' as G3_grandParendNameFrom tableA as G1 --generation1whereg1.parentID > 0--(7 row(s) affected)selectx.*into tableCfrom (select * from tableBexceptselect * from tableBwhere G3_grandParentID = G2_ParentIDor G2_ParentID = G1_ChildID)x where x.g3_grandparentID > 0select * from tableCunion allselect * from(select * from tableBexceptselect * from tableBwhere G3_grandParentID = G2_ParentIDor G2_ParentID = G1_ChildID) as xwherex.G1_childID > (Select G1_childID from tablec)