将所有的父节点包含在当前行中或所有的字节点

借助3个知识点可以完成这个步骤

一:with 字句

declare @pids nvarchar(max);
declare @pNames nvarchar(max);
set @pids='';
set @pNames='';
with cte as
( select id,parentid,name from EL_QuestionBank.QuestionCategory where id='41fc6f0d18434129a975c722ac5c3208'
union all
select b.id,b.parentid,b.name from cte A ,EL_QuestionBank.QuestionCategory B where a.parentid = b.id )
select @pids=@pids + id + ',', @pNames=@pNames + name + '->' from cte
select @pids, @pNames

结果类似:

image

 

二:多行变成一行

实际上,上面的 with 字句,如果使用

select * from cte

则查询出来的是多行数据。而借助于 向变量赋值的 SELECT 语句 我们将多行变成一行;

 

三:使用自定义函数

修正一下上面的语句,创建自定义函数,类似为:

create function f_pidname(@id nvarchar(50)) returns nvarchar(max) as
begin
    declare @pids nvarchar(max);
    declare @pNames nvarchar(max);
    set @pids='';
    set @pNames='';
    with cte as
    ( select id,parentid,name from EL_QuestionBank.QuestionCategory where id=@id
    union all
    select b.id,b.parentid,b.name from cte A ,EL_QuestionBank.QuestionCategory B where a.parentid = b.id )
    select @pids=@pids + id + ',', @pNames=@pNames + name + '->' from cte
    return @pids + '###' + @pNames
end
go
select top 100 *, dbo.f_pidname(parentid) from EL_QuestionBank.QuestionCategory A
drop function f_pidname

我们最终实现了将全部的 父节点的 id 等信息嵌套到当前行中。

现在,所有的字节点包含在当前行中就同理了:

create function f_cidname(@id nvarchar(50)) returns nvarchar(max) as
begin
    declare @cids nvarchar(max);
    set @cids='';
    declare @pNames nvarchar(max);
    set @pNames='';
    with cte as
    ( select id,parentid,name from EL_QuestionBank.QuestionCategory where id=@id
    union all
    select b.id,b.parentid,b.name from cte A ,EL_QuestionBank.QuestionCategory B where a.id = b.parentid )
   
    select TOP 100 @cids=@cids + id + ',', @pNames=@pNames + name + '->' from cte
    return @cids + '###' + @pNames
end
go
select top 100 *, dbo.f_cidname(id) from EL_QuestionBank.QuestionCategory A where id='1'
drop function f_cidname

posted @   陆敏技  阅读(393)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
Web Counter
Coupon for Contacts
点击右上角即可分享
微信分享提示