I’m new to CTE’s in T-SQL but am loving them. However, I cannot get the logic right for this particular stored procedure I’m writing.
Given Table A with the columns:
Id Name Inherits ...
Where the column Inherits stores an int that is an id to another row in this same table.
And Table B with the columns:
Id Name AId ...
Where AId is a foreign key to a row in Table A.
How could one use a CTE to start from an arbitrary row (x) in A, collect all rows in B where AId = x.Id, and then recurse upwards in A by setting x to the row pointed to by x.Inherits. This should proceed until x.Inherits IS NULL.
So the overall effect is I want to return the related B rows for the starting A Id, and then all inherited B rows that we discover by examining the Inherits column of A recursively.
My thinking is to set up the CTE to recurse to the ‘root’ of A from an arbitrary row, and inside each recursive call have a JOIN to B. This is as far as I’ve got:
WITH c
AS
(
SELECT A.Inherits,A.Id, B.Name, 1 AS Depth
FROM tbl_A A
INNER JOIN tbl_B B ON B.AId = A.Id
WHERE A.Id = @ArbitraryStartingAId
UNION ALL
SELECT T.Inherits,T.Id, c.Name, c.Depth + 1 AS 'Level'
FROM tbl_A T
INNER JOIN c ON T.Id = c.Inherits
)
SELECT *
FROM c
Which produces:
1 4 b_val 1
11 1 b_val 2
NULL 11 b_val 3
Where b_val is taken from a Table B row (y) where @ArbitraryStartingAId = y.AId. The recursion on A is working, but not pulling in the correct corresponding B data upon each iteration.
If someone could help rewrite this to yield the results I need then that would be great.
Many thanks
Supposing we have
And some data:
We can build a CTE on
A, and then join toB:to get (with the anchor at
1):