If I understand the question correctly, you could build a 'path' column in your CTE
Consider the following example
Create a test table and fill it with some data
create table locations (
id int,
parentid int,
place varchar(100)
)
insert into locations (id, parentid, place) values
(1, null, 'Europe'),
(2, 1, 'France'),
(3, 2, 'Paris'),
(4, 2, 'Marseille'),
(5, 2, 'Lyon'),
(6, 1, 'Italy'),
(7, 6, 'Rome'),
(8, 6, 'Milan'),
(9, 6, 'Venice'),
(10, 1, 'United Kingdom'),
(11, 10, 'London'),
(12, 10, 'Cambridge'),
(13, 10, 'Bath')
Query the data
with Places (id, parentid, place, level, path) AS (
select l.id,
l.parentid,
l.place,
1 as level,
cast('Continent' as varchar(1000))
from locations l
where l.parentid is null
union all
select l.id,
l.parentid,
l.place,
p.level + 1,
cast(case p.level
when 1 then p.path + '/Country'
when 2 then p.path + '/City'
end as varchar(1000))
from locations l
inner join places p on p.id = l.parentid
)
select *
from places
order by id
the result would be
id parentid place level path
-- -------- ----- ----- --------
1 NULL Europe 1 Continent
2 1 France 2 Continent/Country
3 2 Paris 3 Continent/Country/City
4 2 Marseille 3 Continent/Country/City
5 2 Lyon 3 Continent/Country/City
6 1 Italy 2 Continent/Country
7 6 Rome 3 Continent/Country/City
8 6 Milan 3 Continent/Country/City
9 6 Venice 3 Continent/Country/City
10 1 United Kingdom 2 Continent/Country
11 10 London 3 Continent/Country/City
12 10 Cambridge 3 Continent/Country/City
13 10 Bath 3 Continent/Country/City
[ADDED AN ALTERNATE EXAMPLE]
Regarding the football player example. The idea is the same as in the previous query. During each recursive loop, concatenate the values as a path to the result set.
Consider the following
The data
create table person (
id int,
fatherid int,
name varchar(100)
)
insert into person (id, fatherid, name) values
(1, null, 'Aveiro'),
(2, 1, 'Dos Santos'),
(3, 2, 'Ronaldo'),
(4, 3, 'Cristiano')
The query
with PersonHier (id, fatherid, name, level, fullname) AS (
select p.id,
p.fatherid,
p.name,
1 as level,
cast(p.name as varchar(max))
from person p
where p.fatherid is null
union all
select p.id,
p.fatherid,
p.name,
h.level + 1,
concat(p.name, ' / ', h.FullName)
from person p
inner join PersonHier h on h.id = p.fatherid
)
select *
from PersonHier
order by id
the result
id fatherid name level fullname
-- -------- ----- ----- ------------
1 NULL Aveiro 1 Aveiro
2 1 Dos Santos 2 Dos Santos / Aveiro
3 2 Ronaldo 3 Ronaldo / Dos Santos / Aveiro
4 3 Cristiano 4 Cristiano / Ronaldo / Dos Santos / Aveiro