基于现有的表,我使用CTE递归查询来得出以下数据.但未能进一步应用它.
数据如下
id name parentid -------------------------- 1 project 0 2 structure 1 3 path_1 2 4 path_2 2 5 path_3 2 6 path_4 3 7 path_5 4 8 path_6 5
我想以递归方式从上面的数据中形成完整路径.表示递归将提供以下输出.
FullPaths ------------- Project Project\Structure Project\Structure\Path_1 Project\Structure\Path_2 Project\Structure\Path_3 Project\Structure\Path_1\path_4 Project\Structure\Path_2\path_5 Project\Structure\Path_3\path_6
谢谢
解决方法
这是一个CTE的例子:
declare @t table (id int,name varchar(max),parentid int) insert into @t select 1,'project',0 union all select 2,'structure',1 union all select 3,'path_1',2 union all select 4,'path_2',2 union all select 5,'path_3',2 union all select 6,'path_4',3 union all select 7,'path_5',4 union all select 8,'path_6',5 ; with CteAlias as ( select id,name,parentid from @t t where t.parentid = 0 union all select t.id,parent.name + '\' + t.name,t.parentid from @t t inner join CteAlias parent on t.parentid = parent.id ) select * from CteAlias