Hi TGFirst of all thanks for persevering.Secondly, some sample code:SET NOCOUNT ON;DECLARE @tblTree TABLE ( TreeID int, ParentTreeID int, Hierarchy varchar(900));DECLARE @lnkTreeItem TABLE ( TreeID int, ItemID int -- item is a pk from another table);INSERT INTO @tblTree(TreeID, ParentTreeID, Hierarchy)SELECT 1, null, '.2.' UNIONSELECT 2, 1, '.2.10.' UNIONSELECT 3, 2, '.2.10.83.' UNIONSELECT 4, 3, '.2.10.83.101.' UNIONSELECT 5, 3, '.2.10.83.102.' UNIONSELECT 6, 3, '.2.10.83.103.' UNIONSELECT 7, 3, '.2.10.83.104.' UNIONSELECT 8, 2, '.2.10.84.' UNIONSELECT 9, null, '.3.' UNIONSELECT 10, 9, '.3.29.' UNIONSELECT 11, 10, '.3.29.50' UNIONSELECT 12, 9, '.3.77.' UNIONSELECT 13, 12, '.3.77.90.'INSERT INTO @lnkTreeItem(TreeID, ItemID)SELECT 1, 1 UNIONSELECT 2, 1 UNIONSELECT 3, 1 UNIONSELECT 8, 1 UNIONSELECT 9, 1 UNIONSELECT 10, 1 UNIONSELECT 12, 1 UNIONSELECT 13, 1SELECT A.HierarchyFROM @tblTree A INNER JOIN @lnkTreeItem B ON A.TreeID = B.TreeIDWHERE B.ItemID = 1;SET NOCOUNT OFF;
Output.2..2.10..2.10.83..2.10.84..3..3.29..3.77..3.77.90.
But my desired output is:.2.10.83..2.10.84..3.29..3.77.90.
Notice that .2.10.83. and .3.29. are parents but in the item/tree link table only the parent nodes have been chosen.I could use the desired output to display a breadcrumb if I so wished. The reason I don't require .2., .2.10., .3. and .3.77. is because they are already encoded in the desired output rows.***** EURIKA *****I have finally figured out what I want to do!The answer to my question is:SELECT HierarchyFROM ( SELECT A.TreeID, A.Hierarchy FROM @tblTree A INNER JOIN @lnkTreeItem B ON A.TreeID = B.TreeID WHERE B.ItemID = 1 ) DRVDesiredA LEFT OUTER JOIN ( SELECT A.ParentTreeID FROM @tblTree A INNER JOIN @lnkTreeItem B ON A.TreeID = B.TreeID WHERE B.ItemID = 1 ) DRVDesiredB ON DRVDesiredB.ParentTreeID = DRVDesiredA.TreeIDWHERE DRVDesiredB.ParentTreeID IS NULL;
Output.2.10.83..2.10.84..3.29..3.77.90.
Because I am just after the leaf-nodes (which your original query does) of my subset.Again, thank you for your help!
I think sometimes we just need to chat for the answer to present itself!CheersMoosh