I have the following table @t:
ParentId SkuName ChildId
P1 X1 C1
C1 X2 C2
C2 X3 C2
If I pass the ParentId = P1, the desired output is x3
i.e. the stopping condition is the last row matching record and get the sku name for that
row. If no row matched, then return null
My attempt (no working though)
DECLARE @t TABLE (ParentId Varchar(100), Name VARCHAR(20), ChildId Varchar(100))
INSERT INTO @t(ParentId, Name, ChildId)
SELECT 'P1', 'X1', 'C1' UNION ALL
SELECT 'C1', 'X2', 'C2' UNION ALL
SELECT 'C2', 'X3', 'C2'
Declare @ParentId Varchar(10) = 'P1'
;With CTE As
(
Select
Rn = ROW_NUMBER() Over(Order By (Select 1))
,ParentId
, Name
, ChildId
From @t Where ParentId = @ParentId
Union All
Select
Rn + 1
,pc.ParentId as Parents
,pc.Name
,pc.ChildId
FROM @t pc
JOIN CTE gp on pc.Childid = gp.Parentid
)
Select *
From CTE
Please help