views:

58

answers:

1

Assuming you have the following database table:

 create table Names (
  Id INT IDENTITY NOT NULL,
    Name NVARCHAR(100) not null,
    ParentNameId INT null,
    primary key (Id)
 )

 create index IX_Name on Names (Name)

 alter table Names
  add constraint FK_NameNames
  foreign key (ParentNameId) 
  references Names

This allows the definition of hierarchical names. Each name can have one parent name, and any number of child names.

I wish to find the record corresponding to a qualified name such as "a:b:c", where colons delimit each name. I have currently done so using joins:

 select
  Id
 from
  Names names0
  inner join Names names1 on names0.ParentNameId = names1.Id
  inner join Names names2 on names1.ParentNameId = names2.Id
 where
  names0.Name = 'a' and
  names1.Name = 'b' and
  names2.Name = 'c' and
  names0.ParentNameId is null

What I'm wondering is whether there's a more efficient way to do this that does not involve denormalization of the data or taking a hard dependency on any particular DBMS.

Thanks

+1  A: 

You might like to read this: http://www.developersdex.com/gurus/articles/112.asp

Alex Deem
Celko's work on trees and hierarchies in SQL should be required reading for anyone in the RDBMS field.
Tom H.
Thanks. That's nothing short of awesome. Hopefully I can get NHibernate to work with this approach.
giggidy