根據分類ID獲得所有子ID和所有父ID

數據表
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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章