sql server怎么对树形结构表的节点进行拼接

2025-02-25 20:28:37
推荐回答(2个)
回答1:

DECLARE @temp nvarchar(MAX)='',@pid bigint=3;
WHILE @pid<>0 BEGIN IF @temp=''
SELECT @temp=TypeName,@pid=ParentId
FROM [dbo].[Test]
WHERE Id=@pid;
ELSE
SELECT @temp=(TypeName+'->'+@temp),@pid=ParentId
FROM [dbo].[Test]
WHERE Id=@pid;
END;
SELECT @temp AS TypeName;

回答2:

用标准sql的with实现递归查询(sql2005以上肯定支持,sql2000不清楚是否支持):

with subqry(id,name,pid) as (
select id,name,pid from test1 where id = 5
union all
select test1.id,test1.name,test1.pid from test1,subqry
where test1.pid = subqry.id
)
select * from subqry;