首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >SQL SERVER 2000 遍历父子关系数据的表(二叉树)获得所有子节点 所有父节点及节点层数函数

SQL SERVER 2000 遍历父子关系数据的表(二叉树)获得所有子节点 所有父节点及节点层数函数

作者头像
geovindu
发布2026-06-18 09:49:43
发布2026-06-18 09:49:43
1160
举报
代码语言:javascript
复制
---SQL SERVER 2000 遍历父子关系數據表(二叉树)获得所有子节点 所有父节点及节点层数函数
---Geovin Du 涂聚文
--建立測試環境
Create Table GeovinDu
([ID] Int,
 fatherID Int,
 [Name] Varchar(10)
)
Insert A Select 1,        0,       '中国'
Union All Select 2,        1,          '广东'
Union All Select 3,        1,          '北京'
Union All Select 4,        2,          '深圳特区'
Union All Select 5,        2,          '广州'
Union All Select 6,        4,          '罗湖'
Union All Select 7,        4,          '福田'
Union All Select 8,        7,           '华强北'
Union All Select 9,        0,  '美国'
Union All Select 10,       9,         '华盛顿州'
GO
--建立函數

--取字子节点
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChildren]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetChildren]
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 GeovinDu Where fatherID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From GeovinDu 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
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParent]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetParent]
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 GeovinDu Where ID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From GeovinDu A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
Return
End

---分为几级
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getlevel]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getlevel]
GO
create function f_getlevel(@id INT) returns int
as
begin
  declare @re_str as varchar(3)
  set @re_str = ''
  declare @level as int
  set @level = 1
  select @re_str = fatherID from GeovinDu where [ID] = @id 
  while exists (select 1 from GeovinDu where [ID] = @re_str)
    begin
      select @re_str = fatherID from GeovinDu where [ID] = @re_str
      set @level = @level + 1
    end
  return @level
end
go




--測試
SELECT * FROM GeovinDu
GO

Select * From dbo.GetChildren(4)

Select * From dbo.GetParent(4)
GO

select * , dbo.f_getlevel([ID])  'level' from A

drop function dbo.f_getlevel
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-06-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档