1

给定以下表结构:

CREATE TABLE [dbo].[NodeTest] (
[Id]             INT            IDENTITY (1, 1) NOT NULL,
[NodeCode]       NVARCHAR (50)  NOT NULL,
[ParentNodeCode] NVARCHAR (50)  NULL,
[NodeName]       NVARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

以及以下数据:

insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0', null, 'ROOT')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('01', '0', '01')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('02', '0', '02')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('03', '0', '03')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('011', '01', '011')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('012', '01', '012')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('021', '02', '021')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('022', '02', '022')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('023', '02', '023')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('024', '02', '024')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('025', '02', '025')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('031', '03', '031')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('032', '03', '032')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0111', '011', '0111')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0112', '011', '0112')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0311', '031', '0311')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0322', '032', '0322')

如何编写一个视图来列出节点及其所有后代?例如,对于节点 01,我将得到:

01 011
01 012
01 0111
01 0112

使用这个SQLFiddle,它包含上面显示的表和信息。

4

4 回答 4

3

工作SQLFiddle

我想你想要这个

with cte as 
    (
        select * from NodeTest where ParentNodeCode = '01'
        union all
        select NodeTest.* 
        from NodeTest
        inner join cte  on cte.NodeCode = NodeTest.ParentNodeCode
    )
    select * from cte;
于 2013-10-11T09:45:43.650 回答
2

使用公用表表达式 (CTE)

declare @parentCode varchar(20) = '01'

;with cte as 
(
    select * from NodeTest where ParentNodeCode = @parentCode
    union all
    select NodeTest.* 
    from NodeTest
         inner join cte on cte.NodeCode = nodeTest.ParentNodeCode
)
select @parentCode, nodeCode from cte;
于 2013-10-11T09:50:30.340 回答
0

下面的查询应该可以解决问题,基本上你必须加入到表本身以创建父子关系并在 Parent.NodeCode 上加入 Childs.ParentNodeCode

SELECT 
    P.NodeCode,
    C.NodeCode AS ChildNodeCode
FROM
    NodeTest P
INNER JOIN
    NodeTest C
ON
    P.NodeCode = C.ParentNodeCode
于 2013-10-11T09:48:42.387 回答
0

这会起作用

select a.NodeCode,b.NodeName from NodeTest a 内连接 NodeTest b on a.NodeName = b.ParentNodeCode

于 2013-10-22T10:31:06.790 回答