I am guessing kasper is talking about going down an unlimited number of hierarchal levels. There are several posts and articles here about "trees and hierarchies". Here is some sample code I did some time ago: (you can just exec the entire code block to see the results)set nocount ondeclare @items Table (itemid int identity(1,1), itemName varchar(10))declare @association Table (itemid int, parentitemid int)declare @tree Table (parentitemid int, itemid int, lev int, struct varchar(200))declare @lev intset @lev = 0insert @items (itemname)select 'item01' unionselect 'item02' unionselect 'item03' unionselect 'item04' unionselect 'item05' unionselect 'item06' unionselect 'item07' unionselect 'item08' unionselect 'item09' unionselect 'item10' unionselect 'item11' unionselect 'item12'order by 1insert @associationselect 1,null union select 2,1 unionselect 3,1 unionselect 4,3 unionselect 5,4 unionselect 6,2 unionselect 7,2 unionselect 8,6 unionselect 9,6 unionselect 10,2 unionselect 11,10 unionselect 12, 1--get the root nodesinsert @treeselect null, a.itemid, @lev, itemnamefrom @association aJOIN @items i ON i.itemid = a.itemidwhere parentitemid is NULL--while children exist for current parent levelwhile @@Rowcount > 0Begin set @lev = @lev + 1 insert @tree select t.itemid, a.itemid, @lev, isNull(t.struct+'.','') + itemname from @association a JOIN @items i ON i.itemid = a.itemid JOIN @tree t ON t.itemid = a.parentitemid and t.lev = @lev - 1 --avoid circular references Left JOIN @tree excl ON excl.parentitemid = a.itemid where excl.itemid is NULLEndprint 'helper table: @tree'select * from @tree order by itemidprint 'One way to display the formatted tree'select replicate(char(9), lev) + convert(varchar,i.itemid) + '-' + itemname [struct]From @tree tJOIN @items i ON t.itemid = i.itemidOrder by i.itemid
Be One with the OptimizerTG