I am trying to recursively iterate through a Bill Of Materials(BOM) in Sage Manufacturing Line 50 on MS-SQL server.
The BOM tree structure is contained in two tables BOMHeader and BOMComponent. These are linked by BOMHeader.ID = BOMComponent.HeaderID. So by linking these and querying With a specific BomHeader.BOMReference, I get The first tier of the BOM.
The Recursion occurs because each BOMComponent can itself be an assembly who's StockCode, which if it exists as a BOMHeader.BomReference indicates that it is a sub BOM and has sub-components in the BOMComponents Table.
I Spent about half an hour drawing a diagram, but I cannot post it as I need 10 reputation points
WITH BOM_CTE (HID, HRef, HDesc, SC, CDesc, CHID, CQ, SEQ)
AS
(
SELECT H.ID as HID, H.BomReference as HRef, H.Description as HDesc, C.StockCode as SC,C.Description as CDesc,C.HeaderID as CHID,C.Quantity as CQ,1 as SEQ
FROM [GNT\SAGEL50].[sagel50_46387].[dbo].BomHeaders H
JOIN [GNT\SAGEL50].[sagel50_46387].[dbo].BomComponents C
ON H.ID = C.HeaderID
WHERE H.BomReference like 'SA000001%'
UNION ALL
SELECT H.ID as HID, H.BomReference as HRef, H.Description as HDesc, C.StockCode as SC,C.Description as CDesc,C.HeaderID as CHID,C.Quantity as CQ,BC.SEQ+1
FROM [GNT\SAGEL50].[sagel50_46387].[dbo].BomHeaders H
JOIN [GNT\SAGEL50].[sagel50_46387].[dbo].BomComponents C
ON H.ID = C.HeaderID
JOIN BOM_CTE BC
ON HRef = BC.SC
)
Select * From BOM_CTE
The above code only lists the top level, and will not re-curse, by seeing if a resultant stockcode derived from the BOMComponents Table appears in the BOMHeader Table as a BOMReference (meaning it has sub components).
The recursion should end when all BomComponents have no StockCode reference in the BomHeader.BomReference (meaning there is no lower level)
I am after a recursive SQL code statement that can achieve a two linked table recursive tree lookup. I have looked a a lot of BOM questions, but they seem to be in one table, and also two table CTE, but I can't get my head around it, as I'm fairly new to SQL, especially recursion.
Thanks in advance for any help
Adam