三種實現(xiàn)方法實現(xiàn)數(shù)據(jù)表中遍歷尋找子節(jié)點
發(fā)布日期:2022-02-03 11:57 | 文章來源:源碼之家
表結(jié)構(gòu):
IdParentId
10
21
32
...... 針對該表結(jié)構(gòu)解釋如下:
1的父節(jié)點為0,
2的父節(jié)點為1,
3的父節(jié)點為2
......
以此類推,要求給定一個父節(jié)點的值,比如1,
用SQL語句查詢的到該父結(jié)點下的所有子節(jié)點 下面的Sql是在SqlServer下調(diào)試通過的,如果是Oracle,則有ConnectBy可以實現(xiàn).
建立測試表: DropTableDbTree CreateTableDbTree ( [Id]Int, [Name]NVarChar(20), [ParentId]Int )
插入測試數(shù)據(jù): InsertIntoDbTree([Id],[ParentId])Values(1,0) InsertIntoDbTree([Id],[ParentId])Values(2,1) InsertIntoDbTree([Id],[ParentId])Values(3,1) InsertIntoDbTree([Id],[ParentId])Values(4,3) InsertIntoDbTree([Id],[ParentId])Values(5,4) InsertIntoDbTree([Id],[ParentId])Values(6,7) InsertIntoDbTree([Id],[ParentId])Values(8,5) 實現(xiàn)方法一:
代碼如下: Declare@IdInt Set@Id=1---在次修改父節(jié)點 Select*Into#TempFromDbTreeWhereParentIdIn(@Id) Select*Into#AllRowFromDbTreeWhereParentIdIn(@Id)--1,2
WhileExists(Select*From#Temp) Begin Select*Into#Temp2From#Temp TruncateTable#Temp
InsertInto#TempSelect*FromDbTreeWhereParentIdIn(SelectIdFrom#Temp2) InsertInto#AllRowSelect*From#Temp DropTable#Temp2 End Select*From#AllRowOrderById
DropTable#Temp DropTable#AllRow
實現(xiàn)方法二:
代碼如下: CreateTable#AllRow ( IdInt, ParentIdInt )
Declare@IdInt Set@Id=1---在次修改父節(jié)點
Delete#AllRow
--頂層自身 InsertInto#AllRow(Id,ParentId)Select@Id,@Id
While@@RowCount>0 Begin InsertInto#AllRow(Id,ParentId) SelectB.Id,A.Id From#AllRowA,DbTreeB WhereA.Id=B.ParentIdAnd NotExists(SelectIdFrom#AllRowWhereId=B.IdAndParentId=A.Id) End
DeleteFrom#AllRowWhereId=@Id Select*From#AllRowOrderById DropTable#AllRow
實現(xiàn)方法三:
代碼如下: 在SqlServer2005中其實提供了CTE[公共表表達式]來實現(xiàn)遞歸: 關(guān)于CTE的使用請查MSDN Declare@IdInt Set@Id=3;---在次修改父節(jié)點
WithRootNodeCTE(Id,ParentId) As ( SelectId,ParentIdFromDbTreeWhereParentIdIn(@Id) UnionAll SelectDbTree.Id,DbTree.ParentIdFromRootNodeCTE InnerJoinDbTree OnRootNodeCTE.Id=DbTree.ParentId )
Select*FromRootNodeCTE
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
上一篇:
關(guān)注官方微信