日期:2014-05-17  浏览次数:20534 次

怎样写这个递归查询

fid pid
1 0
2 0
3 1
4 3
5 4
6 0
7
8
9
10

fid=5的上一级是 fid=4 而 fid=4的上一级是 fid=3 再上一级为0就是最大的一级
想查询条件 fid=4时候返回 3,1,0

------解决方案--------------------
BOM精华帖。
2K5 CTE
2K的话麻烦。要整函数。
------解决方案--------------------
SQL code

--> 测试数据: @T
declare @T table (fid int,pid int)
insert into @T
select 1,0 union all
select 2,0 union all
select 3,1 union all
select 4,3 union all
select 5,4 union all
select 6,0


--得到某节点的所有父节点
;with maco as
(
select * from @T where fid=4
union all
select a.* from @T a ,maco b where a.fid=b.pid
)
select * from maco order by fid
/*
fid         pid
----------- -----------
1           0
3           1
4           3
*/

------解决方案--------------------
这头像是小齐嘛?要是是的话,难得啊!
探讨
BOM精华帖。
2K5 CTE
2K的话麻烦。要整函数。