日期:2014-05-18  浏览次数:20627 次

通过sql语句从树的页上或者节点找到树的根???
比如
表:tree
字段   id   pid   name
          1     0       xx
          2     1       xxx
          3     2       xxxx
          4     0       aa
          5     4       aaa
          6     5       aaaa

如果知道id是3怎么能找到id是1的记录。

------解决方案--------------------
create table tree(id int, pid int, name varchar(20))
insert into tree select 1, 0, 'xx '
union all select 2, 1, 'xxx '
union all select 3, 2, 'xxxx '
union all select 4, 0, 'aa '
union all select 5, 4, 'aaa '
union all select 6, 5, 'aaaa '


declare @id int
set @id = 3
while(select pid from tree where id=@id) <> 0
select @id=id from tree where id=(select pid from tree where id=@id)
select * from tree where id=@id
------解决方案--------------------
create table tree(id char(1) ,pid char(1),name varchar(10))
insert tree
select '1 ', '0 ' , 'xx '
union select '2 ', '1 ', 'xxx '
union select '3 ', '2 ' , 'xxxx '
union select '4 ', '0 ' , 'aa '
union select '5 ', '4 ' , 'aaa '
union select '6 ', '5 ' , 'aaaa '

-----查询函数
CREATE FUNCTION f_Pid(@ID char(3))
RETURNS @t_Level TABLE(ID char(3),Level int)
AS
BEGIN
DECLARE @Level int
SET @Level=1
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT> 0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.PID,@Level
FROM tree a,@t_Level b
WHERE a.ID=b.ID
AND b.Level=@Level-1
END
RETURN
END
GO

-----查询语句
SELECT a.*
FROM tree a,f_Pid( '3 ') b
WHERE a.ID=b.ID and a.pid=0