请问树形结构的sql语句怎么写

sakas 2005-05-10 10:28:38
例如表table如下

souid destid lengh
a b 3
a v 4
b c 6
c g 8
g v 6

要写出a能到达的所有的目的地
...全文
235 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2005-05-11
  • 打赏
  • 举报
回复
树状结构一条语句是搞不掂的
sakas 2005-05-10
  • 打赏
  • 举报
回复
可以用一条sql语句实现吗 在sql server中
zjcxc 元老 2005-05-10
  • 打赏
  • 举报
回复
--示例数据

create table tb(souid varchar(10),destid varchar(10),lengh int)
insert tb select 'a','b',3
union all select 'a','v',4
union all select 'b','c',6
union all select 'c','g',8
union all select 'g','v',6
go

--查询的存储过程
create proc p_qry
@souid varchar(10)
as
set nocount on
declare @l int
set @l=1
create table #(souid varchar(10),lengh int,level int,path varchar(8000))
insert # select destid,lengh,@l,@souid+'->'+destid
from tb
where souid=@souid
while @@rowcount>0
begin
set @l=@l+1
insert # select a.destid,a.lengh+b.lengh,@l,b.path+'->'+a.destid
from tb a,# b
where a.souid=b.souid and b.level=@l-1
end
select * from #
go

--调用
exec p_qry 'a'
go

--删除测试
drop table tb
drop proc p_qry

/*--结果
souid lengh level path
---------- ----------- ----------- ------------------
b 3 1 a->b
v 4 1 a->v
c 9 2 a->b->c
g 17 3 a->b->c->g
v 23 4 a->b->c->g->v
--*/

34,576

社区成员

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

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