將所有的父節點包含在當前行中或所有的字節點

2021-09-06 14:52:45 字數 2444 閱讀 8124

借助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

將所有的父節點包含在當前行中或所有的字節點

借助3個知識點可以完成這個步驟 一 with 字句 declare pids nvarchar max declare pnames nvarchar max set pids set pnames with cte as select id,parentid,name from el questi...

樹的某節點的所有父節點

定位乙個節點遞迴實現為 node findnode const node root,int val 輸出到當前節點的所有路徑,也就是當前節點的所有父親節點集合 這個很有用的,呵呵,知道的人自然知道 這個實現其實是根據中序遍歷得到的,採用中序遍歷的方式查詢節點,當查詢到當前節點的時候堆疊中儲存的就是當...

根據子節點遞迴查詢所有父節點

有個需求,需要根據給定的子節點向上遞迴查詢所有父節點,網上查詢了一些,但是都不是很滿意,有的是需要用到全域性變數定義儲存列表,但是會有併發問題,然後自己手寫乙個 test void contextloads1 public listgetpid listidlist,integer pid,list...