T-SQL递归使用CTE(知道祖母)

时间:2014-05-20 13:48:28

标签: sql sql-server recursion common-table-expression

我想使用CTE表达式来创建所有待售材料的递归查询(BOM)。我的CTE工作正常,但问题是我总是想要保留Grand Parent(已售出的成品)。因此,如果我有一个BOM,其中包含自己有BOM的成分,最后,我想要所有级别的所有成分,但保留成品好项目,而不是具有BOM的成分项目。

这是我的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

所以我想要的是" Item"始终是来自CTE中查询的第一部分的物品,可销售的产品然后通过递归的东西获得所有级别的所有成分......但是找不到方法。

非常感谢任何帮助。 感谢

1 个答案:

答案 0 :(得分:2)

试试这个

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