Quantcast
Viewing all articles
Browse latest Browse all 10

Recursive Query

Construct hierarhy path instead of sum.

declare  @BOM table(
id int
,parentId int
,qty float
)
insert @BOM values
( 20,10,2)
,(25,10,3)
,(30,20,5)
,(30,25,7)
,(40,30,11)

;with cte as(
	select [parentId] as assmblId, id, parentId, qty, CAST(id as varchar(max)) as hpath
	from @BOM 
	where [parentId] not in (select id from @BOM)
	union all
	select cte.assmblId, bom.id, bom.parentId, bom.qty, cte.hpath+'.'+CAST(bom.id as varchar(20))
	from cte
	join @BOM bom on cte.id = bom.parentId
)
select *
from cte
order by hpath
P.S. Celko's method is realy fast. But it comes with a price (not price of a book).  Nested Sets model requires more code and more processing to maintain it then traditional child/parent matrix.

Serg


Viewing all articles
Browse latest Browse all 10

Trending Articles