I am using the following query to assign level code to item.
;with C ( Ingredient_Item_No,
Lvl,
Trail)
as (
select
Matl.Ingredient_Item_No,
2 as Lvl,
CAST(('/' + Matl.Ingredient_Item_No + '/') as varchar(max)) as Trail
from Materials as Matl
and Matl.Product_Item_No = Lvl.Item_No
where Lvl.Level_Code = 1
union all
select
Matl.Ingredient_Item_No,
C.Lvl + 1,
C.trail + CAST((Matl.Ingredient_Item_No +'/') as varchar(max))
from NVA_Work_Rollup_BOM_Materials as Matl
inner join C
on Matl.Product_Item_No = C.Ingredient_Item_No
where CHARINDEX(CAST((Matl.Ingredient_Item_No + '/') as varchar(max)), C.trail) = 0
)
select * from C
The "Material" table structure is like this:
Product Ingredient
A B
B C
D E
E F
C A
The Level_Code have a list of item that already been assigned with level 1. I use the trial column to store the ingredient hierarchy. Whenever the ingredient is already in the trail for the item, I will not assign it with another level. But that also means there is bad record that not supposed to be in the material table. For example, if I have A (1) -> B (2) -> C (3) -> A, A could not be the ingredient of the product C since it is a low level product. it also means that the pair (c (product), A (ingredient)) is a wrong record that need to be take out from 'Material' table. My problem is that I could use the trail to keep track the right order. But how could I retrieve the last pair that with wrong order, such as C -> A?
Edit:
Here is what table 'Lvl' Looks like
item_no level_Code
A 1
B 1
Any help will be appreciated!