儲存過程構建遞迴樹

2021-06-15 20:50:38 字數 1632 閱讀 7762

--示例資料  

create   table   tb(子結點   int,父結點   int,名稱   varchar(20))  

insert   tb   select   1,0,'父結點名稱1'  

union   all   select   2,1,'子結點名稱'  

union   all   select   3,2,'子結點名稱'  

union   all   select   4,2,'子結點名稱'  

union   all   select   5,1,'子結點名稱'  

union   all   select   6,1,'子結點名稱'  

union   all   select   7,1,'子結點名稱'  

union   all   select   8,7,'子結點名稱'  

union   all   select   9,7,'子結點名稱'  

go  

--查詢處理的函式  

create   function   f_id(  

)returns   @re   table(id   int,level   int,sid   varchar(8000))  

as  

begin  

declare   @l   int  

set   @l=0  

insert   @re   select   子結點,@l,right(10000+子結點,4)  

from   tb   where   父結點=0  

while   @@rowcount>0  

begin  

set   @l=@l+1  

insert   @re   select   a.子結點,@l,b.sid+right(10000+a.子結點,4)  

from   tb   a,@re   b  

where   a.父結點=b.id   and   b.level=@l-1  

end  

return  

end  

go  

--呼叫(查詢所有的子)  

select   結果=space(b.level   *4)+a.名稱  

from   tb   a,f_id()   b   where   a.子結點=b.id  

order   by   b.sid  

go  

--刪除測試  

drop   table   tb  

drop   function   f_id  

/*--測試結果  

結果                                            

-------------------------  

父結點名稱1  

子結點名稱  

子結點名稱  

子結點名稱  

子結點名稱  

子結點名稱  

子結點名稱  

子結點名稱  

子結點名稱  

(所影響的行數為   9   行)  

--*/ 

遞迴構建決策樹

def majoritycnt classlist 傳入的引數是已經劃分完所有特徵之後的資料集,例如 yes yes maybe classcount 建立乙個字典 for vote in classlist if vote not in classcount.keys classcount vot...

重現二叉搜尋樹遞迴構建的過程

二叉查詢樹 binary search tree 又 二叉搜尋樹,二叉排序樹 它或者是一棵空樹,或者是具有下列性質的二叉樹 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值 它的左 右子樹也分別為二叉排序樹。簡單而言就是 左邊...

MySQL儲存過程遞迴呼叫

有分類表tb system category,結構如下 create table tb system category id int 11 not null auto increment,c parent id int 11 not null,c name varchar 50 not null,c...