create function f_id( @id int --要查询的id )returns @re table(id int,level int) as begin declare @l int set @l=0 insert @re select id,@l from 表 where 上级id=@id while @@rowcount> 0 begin set @l=@l+1 insert @re select a.id,@l from 表 a join @re b on a.上级id=b.id and b.level=@l-1 end return end