获得所有父节点列表

hz_gis 2010-04-28 05:26:46
问题描述:表里有Type字段和RType字段,其中RType作为父节点和Type相关联
类似这样
Type Rtype
101
201 101
301 201

我的目的是,通过301获得201和101,
即通过一个子节点获得其所有父节点的列表,打个比方,就是通过族谱上的一个人获得他所有祖宗的名字。
不想用程序写,不知道SQL怎么样实现这样的递归问题。
求高手赐教,感激不禁。
...全文
99 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
hz_gis 2010-04-28
  • 打赏
  • 举报
回复
谢谢楼上两位大大,分不多,不成敬意
--小F-- 2010-04-28
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 hz_gis 的回复:]
有人吗?在线等
[/Quote]

2楼的有什么不对的地方么?
hz_gis 2010-04-28
  • 打赏
  • 举报
回复
有人吗?在线等
ws_hgo 2010-04-28
  • 打赏
  • 举报
回复
create table #EnterPrise
(
Department nvarchar(50),--部门名称
ParentDept nvarchar(50),--上级部门
DepartManage nvarchar(30)--部门经理
)
insert into #EnterPrise select '技术部','总经办','Tom'
insert into #EnterPrise select '商务部','总经办','Jeffry'
insert into #EnterPrise select '商务一部','商务部','ViVi'
insert into #EnterPrise select '商务二部','商务部','Peter'
insert into #EnterPrise select '程序组','技术部','GiGi'
insert into #EnterPrise select '设计组','技术部','yoyo'
insert into #EnterPrise select '专项组','程序组','Yue'
insert into #EnterPrise select '总经办','','Boss'
--查询部门经理是Tom的下面的部门名称
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='Tom'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.ParentDept=h1.Department
)
select * from hgo
/*
Department ParentDept DepartManage rank
--------------- -------------------- ----------------------- -----------
技术部 总经办 Tom 0
程序组 技术部 GiGi 1
设计组 技术部 yoyo 1
专项组 程序组 Yue 2
*/
--查询部门经理是GiGi的上级部门名称
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='GiGi'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.Department=h1.ParentDept
)
select * from hgo
/*
Department ParentDept DepartManage rank
-------------------- ---------------------- ----------- -----------
程序组 技术部 GiGi 0
技术部 总经办 Tom 1
总经办 Boss 2
*/



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2010/01/31/5274571.aspx
--小F-- 2010-04-28
  • 打赏
  • 举报
回复
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2010-04-28 17:27:25
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([Type] int,[Rtype] int)
insert [tb]
select 101,null union all
select 201,101 union all
select 301,201
--------------开始查询--------------------------
;with f as
(
select * from tb where [Type]=301
union all
select a.* from tb a join f b on a.[Type]=b.[Rtype]
)
select * from f where [type]<>301
----------------结果----------------------------
/* Type Rtype
----------- -----------
201 101
101 NULL

(2 行受影响)


*/
haitao 2010-04-28
  • 打赏
  • 举报
回复
sql2005后使用cte可以递归

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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