无限级分类查询子类SQL

create table #tb(类别id  int,类别名称 varchar(40),上级类别id int)
insert #tb select  1 ,'顶级类别', 0
insert #tb select  2 ,'类别1', 1
insert #tb select  3 ,'类别2', 1
insert #tb select  4 ,'类别1_1', 2
;with cte as 
(
    select 类别id,类别名称,上级类别id,CAST(row_number() over(order by 类别id) as varbinary(max)) as sort
    from #tb
    where 上级类别id = 1
    
    union all
    
    select a.类别id,a.类别名称,a.上级类别id,sort+CAST(row_number() over(partition by a.上级类别id order by a.类别id) as BINARY)
    from  #tb a
    inner join cte b
    ON a.上级类别id = b.类别id 
)
select 类别id,类别名称,上级类别id
from  cte 
order by sort


类别id        类别名称                                     上级类别id
----------- ---------------------------------------- -----------
2           类别1                                      1
4           类别1_1                                    2
3           类别2                                      1
(3 行受影响)


--drop table #tb
--create table #tb(CategoryId  int,CategoryName nvarchar(500),ParentCategoryId int,Featured bit,ChildCount int)
/*
insert #tb select  1 ,'顶级类别', 0
insert #tb select  2 ,'类别1', 1
insert #tb select  3 ,'类别2', 1
insert #tb select  4 ,'类别1_1', 2
*/
alter function [dbo].[GetChilds](@id int)
returns @Tree table (CategoryId int,CategoryName nvarchar(500),ParentCategoryId int,DisplayOrder int,Featured bit,ChildCount int)
as
begin
insert @Tree select CategoryID,CategoryName,ParentCategoryId,DisplayOrder,Featured,(select COUNT(1) from Category p where p.ParentCategoryId=@id) as ChildCount from Category where CategoryID=@id
;with cte as 
(
    select CategoryId,CategoryName,ParentCategoryId,DisplayOrder,Featured,CAST(row_number() over(order by CategoryId) as varbinary(max)) as sort
    from Category
    where ParentCategoryId = @id
    
    union all
    
    select a.CategoryId,a.CategoryName,a.ParentCategoryId,a.DisplayOrder,a.Featured,sort+CAST(row_number() over(partition by a.ParentCategoryId order by a.CategoryId) as BINARY)
    from  Category a
    inner join cte b
    ON a.ParentCategoryId = b.CategoryId 
)
insert @Tree 
select CategoryId,CategoryName,ParentCategoryId,DisplayOrder,Featured,(select COUNT(1) from cte q where q.ParentCategoryId=cte.CategoryId) as ChildCount
from  cte 
--order by ParentCategoryId,DisplayOrder,CategoryId,sort

return
end
--select * from #tb



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值