SQL 遍历父子关系表(二叉树)
2007-04-09 14:58
281 查看
--建立測試環境
Create Table A
(IDInt,
fatherIDInt,
NameVarchar(10)
)
Insert A Select 1, NULL, 'tt'
Union All Select 2, 1, 'aa'
Union All Select 3, 1, 'bb'
Union All Select 4, 2, 'cc'
Union All Select 5, 2, 'gg'
Union All Select 6, 4, 'yy'
Union All Select 7, 4, 'jj'
Union All Select 8, 7, 'll'
Union All Select 9, NULL, 'uu'
Union All Select 10, 9, 'oo'
GO
--建立函數
Create Function GetChildren(@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where fatherID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.fatherID = B.ID And A.ID Not In (Select ID From @Tree)
Return
End
GO
--測試
Select * From dbo.GetChildren(1)
GO
--刪除測試環境
Drop Table A
Drop Function GetChildren
--結果
/*
IDfatherIDName
21aa
31bb
42cc
52gg
64yy
74jj
87ll
*/
Create Table A
(IDInt,
fatherIDInt,
NameVarchar(10)
)
Insert A Select 1, NULL, 'tt'
Union All Select 2, 1, 'aa'
Union All Select 3, 1, 'bb'
Union All Select 4, 2, 'cc'
Union All Select 5, 2, 'gg'
Union All Select 6, 4, 'yy'
Union All Select 7, 4, 'jj'
Union All Select 8, 7, 'll'
Union All Select 9, NULL, 'uu'
Union All Select 10, 9, 'oo'
GO
--建立函數
Create Function GetChildren(@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where fatherID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.fatherID = B.ID And A.ID Not In (Select ID From @Tree)
Return
End
GO
--測試
Select * From dbo.GetChildren(1)
GO
--刪除測試環境
Drop Table A
Drop Function GetChildren
--結果
/*
IDfatherIDName
21aa
31bb
42cc
52gg
64yy
74jj
87ll
*/
相关文章推荐
- SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点(转)
- SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点
- SQL 遍历父子关系表(二叉树)获得所有子节点
- 数据库 SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点
- SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点(转)
- SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点(转)
- 数据库 SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点
- sql 遍历二叉树所有子节点
- 在使用Hibernate时,因为一个查询需要更多的表连接而要使用SQL来解决性能问题。然而返回的结果集中包含了没有映射的Entity类中的表字段,在这个SQL中还有使用如何将层次关系的父子结点显示为横行
- 今天开始学Java 现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
- Oracle与SQL-Server数据库SQL"树查询"对比[按照父子节点关系递归拼接]
- 关于在Webservice里使用LinqToSQL遇到一对多关系的父子表中子表需要ToList输出泛型而产生循环引用错误的解决办法!(转)
- sql 根据关系表查找相应的父子类的数据
- T-SQL开发 - 06.父子节点遍历
- 【SQL】遍历辖区表,并按祖父子顺序展示
- 【数据结构与算法】二叉树前序、中序、后序遍历间关系
- 现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
- 二叉树中的先序遍历、中序遍历和后序遍历关系
- 请使用PL/SQL来按父子层次关系查询出表的所有数据
- c++现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度