简体   繁体   中英

T-SQL Recursive using CTE (Know the grand parent)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM