2014-09-27 53 views
1

我有以下2个表:T-SQL递归查询,以显示嵌套的树结构

CREATE TABLE [Names] 
    (
    [Id] INT PRIMARY KEY, 
    [Name] VARCHAR(100) 
    ) 

CREATE TABLE [Relationships] 
    (
    [Parent] [int] REFERENCES [Names]([Id]), 
    [Child] [int] REFERENCES [Names]([Id]) 
    ) 

Sample Data: 

INSERT [NAMES] VALUES (1,'FRANK') 
INSERT [NAMES] VALUES (2,'JO') 
INSERT [NAMES] VALUES (3,'MARY') 
INSERT [NAMES] VALUES (4,'PETER') 
INSERT [NAMES] VALUES (5,'MAY') 

INSERT [RELATIONSHIPS] VALUES (1,2) 
INSERT [RELATIONSHIPS] VALUES (2,3) 
INSERT [RELATIONSHIPS] VALUES (4,2) 
INSERT [RELATIONSHIPS] VALUES (5,4) 

如何显示名字的嵌套(树)列表包括[ID],[名]和[等级] ,其中[Level]表示顶层的嵌套层次(Root:Level = 0; Root的第一个子层:Level = 1;等等)? 举例来说,结果应该显示:

Level  Relationship 
-----  ------------ 
2   FRANK <- JO 
3   FRANK <- JO <- MARY 
2   PETER <- JO 
3   MAY <- PETER <- JO 

回答

0

你可能会考虑切换到Hierarchical Data。 TSQL支持它并且不需要“重新发明轮子”。这将使您的查询更容易从长远来看。

Go here for a nice tutorial on the subject.

+1

,你能否证实在SQL分层数据支持多家长为孩子? – 2015-04-22 10:47:58

+1

分层数据仅支持每个孩子一个家长。请参阅[此表单](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bc9745ad-7508-4757-a7ab-71f40e465b3a/hierarchyid-multiple-parents-multiple-children-relation?forum= TRANSACTSQL)。如果您需要多父母多子女关系,该表单还包含其他一些选项 – SyntaxRules 2015-04-23 16:00:39

0

试试这个:

with Relatives as 
(
    select n.Id, cast(n.Name as varchar(max)) Relationship, 0 [Level] 
    from Names n 
    where not exists 
    (
     select * 
     from Relationships r 
     where n.Id = r.Child 
    ) 

    union all 

    select n.Id, p.Relationship + ' <- ' + n.Name Relationship, p.[Level] + 1 [Level] 
    from Names n 
    join Relationships r 
     on n.Id = r.Child 
    join Relatives p 
     on r.Parent = p.Id 
) 

select Relationship, [Level] 
from Relatives