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
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 '')
I cannot thank you enough for all your help, Gordon. You helped me with some of the fundamental flaws and I finished some tweaks and for the most part have what I need.... at least for now. This has been driving me nuts for quite some time. The code I settled on is below in case it could be of help to someone else down the road
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 ba.ppn_i, bb.cpn_i, bb.bomname_i, bb.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 top 1000 BMStudy.*, i.ITEMDESC from BMStudy, iv00101 i
where CPN_I = itemnmbr
order by BOMLEVEL, CPN_I ASC
OPTION (MAXRECURSION 0)
Thanks again!