declare @table table(id int identity(1,1),[sid] int,pid int,dtrea varchar(max))
declare @value int = 123
while @value <= 143
begin
insert into @table([sid],[pid]) values(@value,case when @value > 123 then @value -1 end)
set @value += 1
end
declare @index int = 1
while exists(select 1 from (select ROW_NUMBER() OVER(ORDER BY [sid]) rownum,* from @table) as t where rownum = @index)
begin
declare @sid int = 0
select @sid = [sid] from (select ROW_NUMBER() OVER(ORDER BY [sid]) rownum,* from @table) as t where rownum = @index
declare @str varchar(max) = '' select @str = CAST(@sid as varchar(3))
declare @t_sid int = @sid
declare @level int = 1
while exists(select 1 from @table where pid = @t_sid)
begin
select @t_sid = [sid] from @table where pid = @t_sid
select @str += CHAR(10) + CHAR(13) + ' |_'+CAST(@t_sid as varchar(3)) + '('+CAST(@level as varchar(3))+'级)'
set @level += 1
end
update @table set dtrea = @str where [sid] = @sid
set @index += 1
end
select * from @table
declare @某节点 varchar(100)
WITH cte AS (SELECT * ,0 AS level FROM 表 WHERE [sid] =@某节点 UNION ALL SELECT g.*,level+1 FROM 表 g INNER JOIN cte ON g.[pid]=cte.[sid]
select *,level from cte