给定以下表结构:
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,它包含上面显示的表和信息。