借助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
结果类似:
二:多行变成一行
实际上,上面的 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