Greetings, fellow coders!
I have this table that contains categories and subcategories (actually I don't, but let's stick to a classic example):
Id ParentId Name
1 NULL A
2 1 B
3 2 C
4 3 D
5 NULL B
6 5 D
Is there a way for me to get category "D" (id 4) by querying the table for the full path? (see pseudocode below)
SELECT * FROM Categories WHERE FullPath = "A/B/C/D"
// Result:
Id ParentId Name
4 3 D
I know that it's possible to use left joins to get the full path, but how do I write queries to get the leaf node by providing a path?
EDIT (Solution):
Help the help from both van and Eric, this is what I did:
with p as
(
select
c.*,
cast(c.Name as varchar(1024)) as NamePath
from
Categories c
where
ParentCategoryId is null
union all
select
c.*,
cast(p.NamePath + '/' + c.Name as varchar(1024)) as NamePath
from
Categories c
inner join p on
c.ParentCategoryId = p.CategoryId
)
select Id, Name
from p
where NamePath = 'A/B/C/D'
Thanks guys, both your answers were very helpful! I wish that I was able to mark them both as the solution.
This time I will simply go for the one with the leasts ammount of points (that is van).