I have a data structure inside a table in SQL Server 2005 representing a chain of related objects. Each object can have replacements in many steps. I want to perform a query that returns all objects and each object's leaf in the replacement chain.
The data:
id replacement
1 null
2 3
3 null
4 5
5 6
6 null
The result should be:
id replacement
1 null
2 3
3 null
4 6
5 6
6 null
I believe that a recursive CTE would be a good way to go, but I can't wrap my head around it. A constraints to the problem is that I can't change the data structure, since the database is not in my control.