给出以下表结构:
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,其中包含上述表格和信息。
答案 0 :(得分:3)
我想你想要这个
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;
答案 1 :(得分: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;
答案 2 :(得分:0)
下面的查询应该可以解决问题,基本上你必须加入表回自己创建父子关系并使用Childs.ParentNodeCode加入Parents.NodeCode
SELECT
P.NodeCode,
C.NodeCode AS ChildNodeCode
FROM
NodeTest P
INNER JOIN
NodeTest C
ON
P.NodeCode = C.ParentNodeCode
答案 3 :(得分:0)
这将起作用
从NodeTest中选择a.NodeCode,b.NodeName为内连接 Node.est b on a.NodeName = b.ParentNodeCode