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 treeselect 1, null unionselect 2, 1 unionselect 3, 1 unionselect 4, 2 unionselect 5, 3 unionselect 6, 4 unionselect 7, 4 unionselect 8, 7 unionselect 9, 3 unionselect 10, 4 unionselect 11, 7GOCREATE FUNCTION AllChildren(@Parent as int = Null)Returns @t table (Node int, [Level] int)asbegin 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 returnendGO-- all children from the root (everyone):select * from dbo.AllChildren(null)-- all children of node 4:select * from dbo.AllChildren(4)DROP TABLE treedrop function AllChildren
Let me know if this helps and/or if you need more functions like this.- JeffEdited by - jsmith8858 on 05/08/2003 08:17:28