数据表
ID Name Parent_ID
1 计算机 NULL
2 联想计算机 1
3 戴尔计算机 1
6 手机 NULL
7 诺基亚手机 6
8 苹果手机 6
9 HTC手机 6
10 工程采购 NULL
11 建筑工程 10
12 房产采购 10
13 联想悦动 2
根据传入的分类ID,返回它下面的所有子分类。
-- 根据ID获得它下面的所有子分类
create function UF_GetChildMaterialCategories( @Id int )
returns @tb table (ID int)
as
begin
insert into @tb
select ID from MaterialCategories where Parent_ID = @Id
while @@Rowcount >0 --只要有下级节点就循环
begin
insert into @tb
select a.ID from MaterialCategories as a inner join @tb as b on a.Parent_ID = b.id and a.id not in(select id from @tb)
end
return
end
go
--执行
select * from UF_GetChildMaterialCategories(1)
根据传入的分类ID,返回它的上级分类。
--根据传入的分类ID,返回它的上级分类。
create function UF_GetParentMaterialCategories( @Id int )
returns @tb table (id int)
as
begin
insert into @tb
select parent_id from MaterialCategories where id = @Id
while @@Rowcount >0
begin
insert into @tb
select a.parent_id
from MaterialCategories as a inner join @tb as b on a.id = b.id and a.parent_id not in(select id from @tb)
end
return
end
go
--执行
select * from UF_GetParentMaterialCategories(13)