Recursive Query for Bill Of Materials

后端 未结 2 989
孤城傲影
孤城傲影 2020-12-17 04:30

I\'ve just started teaching myself SQL recently and have been able to piece together almost everything I need from various tutorials, but this one has me banging my head aga

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 04:39

    I think your logic was basically ok. Here are two improvements. First, the level is incremental so you can see what happens with the recursion. Second, it uses an explicit join:

    With BMStudy as (
          select bm.ppn_i, bm.cpn_i, bm.bomname_i, bm.QUANTITY_I, 1 as BOMLevel
          from BM010115 bm
          where bm.PPN_I like '0123105-HWT' and bm.BOMNAME_I like ''
          UNION ALL
          select bb.ppn_i, ba.cpn_i, bb.bomname_i, ba.quantity_i, (BOMLevel + 1) as BOMLevel
          from BMStudy ba join
               BM010115 bb
               on ba.cpn_i = bb.ppn_i
          where bb.BOMNAME_I like ''
         )
    select * from BMStudy;
    

    I suspect your problem is the condition where bb.BOMNAME_I like ''. Is it possible that this value is really NULL rather than blank?

    You should also check what this non-recursive, one-level down query does:

          select bb.ppn_i, ba.cpn_i, bb.bomname_i, ba.quantity_i, (BOMLevel + 1) as BOMLevel
          from BM010115 ba join
               BM010115 bb
               on ba.cpn_i = bb.ppn_i
          where bb.BOMNAME_I like '' and
                (ba.PPN_I like '0123105-HWT' and ba.BOMNAME_I like '')
    

提交回复
热议问题