1. 程式人生 > >根據分類ID獲得所有子ID和所有父ID

根據分類ID獲得所有子ID和所有父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)