请教这个树形数据怎么样遍历?

scong 2005-03-02 05:28:16
表是:
id name parentid
1 a -1
2 aa1 1
3 aa2 1
4 b -1
5 aaa1 2
6 bb1 4

我想把这些数据生成一个有序的树,该怎么写?树的深度是不定的,thx
...全文
125 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
tdy6666 2005-03-07
  • 打赏
  • 举报
回复
佩服的五体投地!
scong 2005-03-03
  • 打赏
  • 举报
回复
太谢谢zjcxc(邹建) 了
xluzhong 2005-03-02
  • 打赏
  • 举报
回复
学习!
lxzm1001 2005-03-02
  • 打赏
  • 举报
回复
sorry 楼上老大以经答好了,我也学点了
zjcxc 2005-03-02
  • 打赏
  • 举报
回复
--写个处理函数
create function f_id()
returns @re table(id int,[level] int,sid varchar(8000))
as
begin
declare @l int
set @l=0
insert @re select id,@l,right(10000+id,4)
from 表 where parentid=0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l,b.sid+right(10000+a.id,4)
from 表 a,@re b
where a.parentid=b.id and b.[level]=@l-1
end
return
end
go

--调用函数实现排序
select a.*
from 表 a,f_id()b
where a.id=b.id
order by b.sid
go
scong 2005-03-02
  • 打赏
  • 举报
回复
沉的真快:(
补充一下,最后得到的数据应该是:
id name parentid
1 a -1
2 aa1 1
5 aaa1 2
3 aa2 1
4 b -1
6 bb1 4

各位帮帮忙啊。。。。

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧