Donate

Recursive CTE Not Getting Top Level Superseded Parts In T-SQL

Hello,

I've been given a task to get the superseded partnumber of a certain part. The scenario is, the chain of the superseded is undetermined and could go as has high as four or more levels. See screenshot below of an example of product supersession. It illustrates that the part supersession of part M03971 is M32887 instead of its direct parent M04880.
Recursive CTE Not Getting Top Level Superseded Parts In T-SQL
Trying out the concept of recursive CTE gets only the lowest level instead without it's parent part supersessions.
WITH SupersededBy_Cte AS (
  SELECT
    [StdDescID],
    [PartNumber],
    [SupersededBY],
	0 AS [level]
  FROM [tblStdDesc] std1
  WHERE std1.SupersededBY IS NULL
  UNION All
  SELECT
    std2.[StdDescID],
    std2.[PartNumber],
    std2.[SupersededBY],
	cte.[level] + 1
  FROM SupersededBy_Cte cte
  INNER JOIN [tblStdDesc] std2
	ON std2.SupersededBY = cte.StdDescID  
)
SELECT 
    cte.[StdDescID],
    cte.[PartNumber],
    cte.[SupersededBY],
	cte.[level]
FROM SupersededBy_Cte cte
WHERE cte.StdDescID = 36782
ORDER BY cte.[level] DESC;
After searching the forums for more examples of recursive CTE's, I found an example that will traverse the chain from bottom to top instead of the top to bottom approach. Modifying the query above with the same approach in the example of the post such as below produced the expected results that I was hoping for. I can finally obtain the topmost part supersession of a specific part number.
WITH SupersededBy_Cte AS (
  SELECT
    [StdDescID],
    [PartNumber],
    [SupersededBY],
	0 AS [level]
  FROM [tblStdDesc] std1
  WHERE std1.StdDescID = 36782 OR (std1.StdDescID IS NULL AND std1.SupersededBY IS NULL)
  UNION All
  SELECT
    std2.[StdDescID],
    std2.[PartNumber],
    std2.[SupersededBY],
	cte.[level] + 1
  FROM SupersededBy_Cte cte
  INNER JOIN [tblStdDesc] std2
  ON std2.StdDescID = cte.SupersededBY  
)
SELECT  
    cte.[StdDescID],
    cte.[PartNumber],
    cte.[SupersededBY],
	cte.[level]
FROM SupersededBy_Cte cte
ORDER BY cte.[level] DESC
Recursive CTE Not Getting Top Level Superseded Parts In T-SQL


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Sharkoon SKILLER SGS2 Gaming Chair Product Review