With the previous links, I came up with this...-- Setup sample dataDECLARE @Table1 TABLE ( SiteID INT, Dept INT, Parent INT )INSERT @Table1SELECT 1, 19677, 0 UNION ALLSELECT 1, 19678, 19677 UNION ALLSELECT 1, 19679, 19677 UNION ALLSELECT 1, 19680, 19677 UNION ALLSELECT 2, 9423, 0 UNION ALLSELECT 2, 9424, 9423 UNION ALLSELECT 2, 9425, 9424 UNION ALLSELECT 2, 9426, 9423 UNION ALLSELECT 2, 9427, 9424 UNION ALLSELECT 3, 9813, 0 UNION ALLSELECT 3, 9814, 9813 UNION ALLSELECT 3, 9815, 9814 UNION ALLSELECT 3, 9816, 9813 UNION ALLSELECT 3, 9817, 9816 UNION ALLSELECT 4, 9994, 0 UNION ALLSELECT 4, 9995, 9994 UNION ALLSELECT 4, 9996, 9995 UNION ALLSELECT 4, 9997, 9994 UNION ALLSELECT 4, 9998, 9996 UNION ALLSELECT 4, 9999, 9994 UNION ALLSELECT 4, 10004, 9994 UNION ALLSELECT 4, 10005, 10004DECLARE @Table2 TABLE ( Dept INT, Parent INT )INSERT @Table2SELECT 9423, 19678 UNION ALLSELECT 9813, 19679 UNION ALLSELECT 9994, 19680-- Display the result;WITH cteSource(SiteID, Dept, Parent)AS ( SELECT t1.SiteID, t1.Dept, COALESCE(t2.Parent, t1.Parent) AS Parent FROM @Table1 AS t1 LEFT JOIN @Table2 AS t2 ON t2.Dept = t1.Dept), cteTree(SiteID, Dept, Parent, DeptPath)AS ( SELECT SiteID, Dept, Parent, '/' + CAST(Dept AS VARCHAR(MAX)) + '/' FROM cteSource WHERE Parent = 0 UNION ALL SELECT t.SiteID, s.Dept, s.Parent, t.DeptPath + CAST(s.Dept AS VARCHAR(MAX)) + '/' FROM cteTree AS t INNER JOIN cteSource AS s ON s.Parent = t.Dept)SELECT SiteID, Dept, ParentFROM cteTreeORDER BY DeptPath
N 56°04'39.26"E 12°55'05.63"