--处理函数
create function f_tree()
returns @re table(id int,level int)
as
begin
declare @l int
set @l=1
insert @re select id,@l
from 表
where parentid=0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a join @re b
on a.parentid=b.id and b.level=@l-1
end
return
end
go--调用函数实现功能1,得到指定id的深度
select 深度=level from f_tree() where id=3--实现功能2,这棵树的最大深度
select 最大深度=max(level) from f_tree()

解决方案 »

  1.   

    --测试--测试数据
    create table 表(id int,parentid int,content varchar(10))
    insert 表 select 1,0,'aa'
    union all select 2,0,'bb'
    union all select 3,1,'cc'
    union all select 4,1,'aa'
    union all select 5,3,'dd'
    union all select 6,5,'aa'
    union all select 7,2,'aa'
    union all select 8,3,'dd'
    union all select 9,6,'aa'
    go--处理函数
    create function f_tree()
    returns @re table(id int,level int)
    as
    begin
    declare @l int
    set @l=1
    insert @re select id,@l
    from 表
    where parentid=0
    while @@rowcount>0
    begin
    set @l=@l+1
    insert @re select a.id,@l
    from 表 a join @re b
    on a.parentid=b.id and b.level=@l-1
    end
    return
    end
    go--调用函数实现功能1,得到指定id的深度
    select 深度=level from f_tree() where id=3--实现功能2,这棵树的最大深度
    select 最大深度=max(level) from f_tree()
    go--删除测试
    drop table 表
    drop function f_tree/*--测试结果深度          
    ----------- 
    2(所影响的行数为 1 行)最大深度        
    ----------- 
    5(所影响的行数为 1 行)
    --*/