Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Hierarchical Query

Author  Topic 

pradipta
Starting Member

1 Post

Posted - 2003-05-06 : 09:03:25
i have a table in my Sql Server database which contains data in a hierarchical manner is as below
table-1

child_id parent_id
1 2
2 3
3 4
4 5
5 6
11 5
17 4

Now i want to retrive all the children,grand children,grand-grand children of parent_id=5.How i can achive it through SQL query .Please help me its very very urgent
Thank u

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2003-05-06 : 10:18:03
Several articles here at SQL team suggest storing hiearchical data in a different form -- search the articles for Trees, be sure to read all comments, and Joe Celko has posted here and on the web many articles about his set-based tree model.

however, all of those require that you do a least a little restructuring of your data. if you already have the data, and just want to return all children of a particular parent (at all levels), then a UDF is the best way. Of course, you need SQL 2000 for this.


Here's an idea of 1 way to do it. this takes a Node as an argument and returns all child nodes. the "level" field is how many levels below the parent they are. thus 1 = child, 2 = grand-child, etc.

this idea can be altered to return all parents of a node or things of that nature.



create table tree (Node int primary key, parent int)

insert into tree
select 1, null union
select 2, 1 union
select 3, 1 union
select 4, 2 union
select 5, 3 union
select 6, 4 union
select 7, 4 union
select 8, 7 union
select 9, 3 union
select 10, 4 union
select 11, 7

GO
CREATE FUNCTION AllChildren(@Parent as int = Null)
Returns @t table (Node int, [Level] int)
as
begin
declare @notdone int;
declare @level int;
insert into @t
select Node, 1
from tree where (@Parent is null AND Parent is Null) OR
(@Parent = Parent)

set @NotDone = 1
set @level = 2
while (@Notdone <> 0)
begin
insert into @t
select tree.Node, @level
from tree
inner join @t t1
on tree.Parent = t1.node
where t1.level = (@Level - 1)

set @notdone = @@rowcount
set @level = @level + 1
end
return
end
GO

-- all children from the root (everyone):
select * from dbo.AllChildren(null)

-- all children of node 4:
select * from dbo.AllChildren(4)


DROP TABLE tree
drop function AllChildren



Let me know if this helps and/or if you need more functions like this.

- Jeff

Edited by - jsmith8858 on 05/08/2003 08:17:28
Go to Top of Page
   

- Advertisement -