递归查询

stone_soup 2005-12-14 10:14:52
Tree表如下:
NodeId ParentId NodeName
0 -1 一
1 0 二
9 1 三
10 9 四
12 10 五
18 1 六
已知:Nodeid 能得到 NodeName的递归连接字符串吗?
例: 已知 结果
NodeId:10 四三二一
NodeId:18 六二一
NodeId:1 二一
请指教.
...全文
160 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
newredhat 2005-12-16
  • 打赏
  • 举报
回复
说一声 强!~
mislrb 2005-12-14
  • 打赏
  • 举报
回复
mark
stone_soup 2005-12-14
  • 打赏
  • 举报
回复
敬佩
lsqkeke 2005-12-14
  • 打赏
  • 举报
回复
路过 探了下头 又出去了
说了一声 “强”
子陌红尘 2005-12-14
  • 打赏
  • 举报
回复
create table Tree(NodeId int,ParentId int,NodeName varchar(4))
insert into Tree select 0 ,-1,'一'
insert into Tree select 1 ,0 ,'二'
insert into Tree select 9 ,1 ,'三'
insert into Tree select 10,9 ,'四'
insert into Tree select 12,10,'五'
insert into Tree select 18,1 ,'六'
go

create function f_getPath(@NodeId int)
returns varchar(8000)
as
begin
declare @ret varchar(8000),@ParentId int
set @ret = ''
select @ret=@ret+NodeName,@ParentId=ParentId from Tree where NodeId=@NodeId
while @@rowcount<>0
begin
set @NodeId=@ParentId
select @ret=@ret+NodeName,@ParentId=ParentId from Tree where NodeId=@NodeId
end
return @ret
end
go


select *,path=dbo.f_getPath(NodeId) from Tree
go

/*
NodeId  ParentId NodeName Path
0 -1 一 一
1 0 二 二一
9 1 三 三二一
10 9 四 四三二一
12 10 五 五四三二一
18 1 六 六二一
*/

drop function f_getPath
drop table Tree
go

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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