Reputation: 27
I would like to use a CTE expression to create a recursive query (BOM) of all materials being sold. My CTE works fine but the problem is that I always want to keep the Grand Parent (the Finished Goods that is sold). so if for example I have a BOM which includes ingredients which themselves have BOM, at the end, I want all ingredients for all levels but keep the finished good item, not the ingredient item that have a BOM.
Here's my CTE:
With MyCTE
as
(
Select H.Item, H.BOMQuantity, D.ComponentItem, D.NetQuantity, 0 as Lvl
From Manufacturing.BillOfMaterialHeader H
Inner Join Manufacturing.BillOfMaterialDetail D On H.Item = D.Item And GetDate() BETWEEN D.EffectiveFrom And D.EffectiveTo
Inner Join Common.Item I On H.Item = I.Item
Where I.ItemGroup = 'U006'
UNION ALL
Select H.Item, H.BOMQuantity, D.ComponentItem, D.NetQuantity, Lvl + 1
From Manufacturing.BillOfMaterialHeader H
Inner Join Manufacturing.BillOfMaterialDetail D On H.Item = D.Item And GetDate() BETWEEN D.EffectiveFrom And D.EffectiveTo
Inner Join MyCTE B On D.Item = B.ComponentItem
)
Select *
From MyCTE
So what I would like as "Item" is always the Item coming from the first part of the query within the CTE, the sellable product and then go trough the recursive thing to get all ingredients of all level... But can't find the way.
Any help would be greatly appreciated. Thanks
Upvotes: 1
Views: 324
Reputation: 51514
Try this instead
With MyCTE
as
(
Select H.Item as BaseItem, H.Item, H.BOMQuantity, D.ComponentItem, D.NetQuantity, 0 as Lvl
From Manufacturing.BillOfMaterialHeader H
Inner Join Manufacturing.BillOfMaterialDetail D On H.Item = D.Item And GetDate() BETWEEN D.EffectiveFrom And D.EffectiveTo
Inner Join Common.Item I On H.Item = I.Item
Where I.ItemGroup = 'U006'
UNION ALL
Select
B.BaseItem,
H.Item,
H.BOMQuantity, D.ComponentItem, D.NetQuantity, Lvl + 1
From Manufacturing.BillOfMaterialHeader H
Inner Join Manufacturing.BillOfMaterialDetail D On H.Item = D.Item And GetDate() BETWEEN D.EffectiveFrom And D.EffectiveTo
Inner Join MyCTE B On D.Item = B.ComponentItem
)
Select *
From MyCTE
Upvotes: 2