惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
雷峰网
雷峰网
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
G
Google Developers Blog
腾讯CDC
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Microsoft Security Blog
Microsoft Security Blog
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
C
Check Point Blog
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
Y
Y Combinator Blog
L
LangChain Blog
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

博客园 - 小呆也行

数据库分区(一) SQL SERVER 分区 向大数据进军 SqlServer中查看数据库所有表的表空间和索引空间信息 C#winform部署中自定义配置文件 url问题 - 小呆也行 - 博客园 COM+的使用(转) Sql中查找数据库中,所有包含字段的表名 死亡机器(转) 厚黑口才学大全(读后感) ASP TO ASP.NET migration,a new approach (Reprinted) ASP向ASP.AET迁移要注意的问题(转) Linq的模糊查询 - 小呆也行 - 博客园 0.4-0.3==0.1 听懂面试官问题背后的潜台词 聪明人把知道说出来,而智者则不声张 我一进教室就震惊了 注册assembly的问题 学习.NET 事例网站
SQL 遍历父子关系表(二叉树)获得所有子节点 所有父节点(转)
小呆也行 · 2010-11-24 · via 博客园 - 小呆也行

--建立測試環境
Create Table A
(ID Int,
 fatherID Int,
 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

--取父节点

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[GetParent](@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where ID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
Return
End

--測試
Select * From dbo.GetChildren(1)

Select * From dbo.GetParent(9)
GO