--查询的函数
create function f_id(@id int)
returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l
from menu
where id=@id --如果只包含下级,则改条件为: pid=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from menu a join @re b on a.pid=b.id and b.level=@l-1
end
return
end
go--调用
select * from f_id(1)--如果还要包含节点的其他信息
select a.* from menu a join f_id(1) b on a.id=b.id