Retrieve the path of a node

Hi Experts,

I have a table like this:
CategoryId
ParentCategoryId
CategoryName

I have a categoryId and I want to list all the parents up the root category.

I want to find all the parents to get the complete path.
Example:
Id      Name     ParentId
0       root       null
1       node1    0
2       node2    1
3       node3    0
4       node4    2
I want to find the path of node4 which result is:
root/node1/node2/node4

Thanks in advance for your help.
LVL 9
nouloukAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
see here for how to implement a helper function for that:
http://www.sql-server-helper.com/functions/get-tree-path.aspx
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nouloukAuthor Commented:
Thanks  angelIII,

your link gives me a solution if I add a new level column to my table.
Is it possible to do this  using CTE recursion ?
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>your link gives me a solution if I add a new level column to my table.
?? I don't see such a column in the code ? just ID and parentID ...

>Is it possible to do this  using CTE recursion ?
yes, that should be possible:


declare @id int
set @id = 4
 
declare @path varchar(max)
with p ( id, parentid, name, level )
as (
  select id, parentid, name, 0 as level
  from yourtable 
  where id = @id
 UNION ALL
   select t.id, t.parentid, t.name, p.level + 1
   from yourtable t
   join p 
     on p.parentid = t.id
  )
select @path = coalesce(@path + '/') + name
from  p
order by p.level desc

Open in new window

0
nouloukAuthor Commented:
Perfect.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.