-
SQL递归函数列出父级的所有子级(ID ParentID模式)
-
-
-
-
-
- Create function [dbo].[GetChild](@ID varchar(10))
- returns @t table(ID varchar(10),ParentID varchar(10),Level int)
- as
- begin
- declare @i int
- set @i = 1
- insert into @t select @ID,@ID,0
- insert into @t select ID,ParentID,@i from Dept where ParentID = @ID
-
- while @@rowcount<>0
- begin
- set @i = @i + 1
- insert into @t
- select
- a.ID,a.ParentID,@i
- from
- Dept a,@t b
- where
- a.ParentID=b.ID and b.Level = @i-1
- end
- return
- end
-
-
-
- Declare @Id Int
- Set @Id = 24;
-
- With RootNodeCTE(Id,ParentId)
- As
- (
- Select Id,ParentId From Dept Where ParentId In (@Id)
- Union All
- Select Dept.Id,Dept.ParentId From RootNodeCTE
- Inner Join Dept
- On RootNodeCTE.Id = Dept.ParentId
- )
-
- Select * From RootNodeCTE
-
-
-
-
-
-
- create table Dept(ID int,ParentID int,msg varchar(20))
- insert into Dept select 1,0,null
- insert into Dept select 2,1,null
- insert into Dept select 3,1,null
- insert into Dept select 4,2,null
- insert into Dept select 5,3,null
- insert into Dept select 6,5,null
- insert into Dept select 7,6,null
- go
-
-
-
- Create function [dbo].[GetChild](@ID varchar(10))
- returns @t table(ID varchar(10),ParentID varchar(10),Level int)
- as
- begin
- declare @i int
- set @i = 1
- insert into @t select @ID,@ID,0
- insert into @t select ID,ParentID,@i from Dept where ParentID = @ID
-
- while @@rowcount<>0
- begin
- set @i = @i + 1
- insert into @t
- select
- a.ID,a.ParentID,@i
- from
- Dept a,@t b
- where
- a.ParentID=b.ID and b.Level = @i-1
- end
- return
- end
-
-
-
- select ID from dbo.GetChild(3)
- go
-
-
- /*
- 3
- 5
- 6
- 7
- */
-
-
- drop function GetChild
- drop table Dept
-
-
-
相关阅读:
c学习第3天
[BZOJ2124] 等差子序列
CF710F String Set Queries
Cow Hopscotch (dp+树状数组优化)
CF528D Fuzzy Search (bitset)
Gym 101667L Vacation Plans (dp)
Codeforces 432D Prefixes and Suffixes (kmp+dp)
[题解]BZOJ2115 XOR
洛谷 P2921 [USACO08DEC]在农场万圣节Trick or Treat on the Farm
从中国矢量图筛选出江苏省行政区划图
-
原文地址:https://www.cnblogs.com/zhangchenliang/p/2391383.html
Copyright © 2020-2023
润新知