Solved

Hierarchical SQL table and finding a record's lineage

Posted on 2010-11-29
3
732 Views
Last Modified: 2012-05-10
Hello.

I have a hierarchical SQL table mimicking a directory tree structure, with fields like the following:

ID
ParentID
ItemName

where a record's ParentID is defined as the ID of the record's intended parent record.

When I preform a Select, I would like to add a column, named "Path", that contains a string representation of an item's lineage, (Eg \GrandParent\Parent\Me).  Given the ID of any item within the table, how do I design a select command to recursively build a lineage string?  I use the word "recursion" loosely -- I know that actual recursion is a resource hog.  Does anyone have a workable strategy for this?

Something like:
SELECT ID, ParentID, ItemName (...something...) as Path
FROM MyTable
WHERE ID=@ID
0
Comment
Question by:ewolsing
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 18

Expert Comment

by:lludden
ID: 34231954
If you are using SQL 2005 or later, you might try a recursive CTE as opposed to a recursive function.

Check this MSDN article.

http://msdn.microsoft.com/en-us/library/ms186243.aspx
0
 
LVL 58

Accepted Solution

by:
cyberkiwi earned 500 total points
ID: 34232256
A sample
create table tree (ID int, ParentID int, ItemName varchar(100))
insert tree select
1,null,'GrandParent' union all select
2,1,'Parent' union all select
3,2,'Me'
GO

create function dbo.lineage(@id int)
returns varchar(max)
as
begin
declare @path varchar(max);
with tmp as (
	select level=1, parentId,convert(varchar(max),'\'+ItemName) Path
	from tree where id=@id
	union all
	select level+1,t.parentID,'\'+t.ItemName+tmp.path
	from tmp
	inner join tree t on tmp.parentID=t.id
	)
select top(1) @path=path from tmp order by level desc
return @path
end
GO

select id, parentid, dbo.lineage(id) as path
from tree
where id=3

Open in new window

0
 

Author Closing Comment

by:ewolsing
ID: 34232734
Thank you!  That was exactly what I was looking for.  While I've done a fair amount of SQL work, I've never played with recursion before.  I appreciate the insight.
0

Featured Post

Why You Need a DevOps Toolchain

IT needs to deliver services with more agility and velocity. IT must roll out application features and innovations faster to keep up with customer demands, which is where a DevOps toolchain steps in. View the infographic to see why you need a DevOps toolchain.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Tempdb Contention - SQL SERVER 10 41
SQL 'Fuzzy' (any part of string matches) match on passed text string in SPROC. 14 58
SQL Server Database Inventory 7 30
mssql 7 32
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question