我有一个像这样的SQL表
ID | ParentID
1 | null
2 | null
3 | null
4 | 1
5 | 4
6 | 5
7 | 6
8 | 7
9 | 8
现在,正如您所看到的,维持了子父关系。我想要一个查询来选择给定ID的“所有级别”子级。
假设我输入ID = 1
,结果应为
ID | ParentID
1 | null
4 | 1
5 | 4
6 | 5
7 | 6
8 | 7
9 | 8
因此,所有直系孩子以及他们孩子的任何级别的孩子都应该出现。
是否可以在MS SQL服务器中执行此操作?我有MS-SQL server 2012。
答案 0 :(得分:3)
以下是一个带有额外字段名称的示例,但使用CTE时,递归很简单:
DECLARE @ID int
SET @ID = 1;
WITH CTE_Table_1
(
ID,
Name,
ParentID,
TreeLevel
)
AS(
SELECT
ID,
Name,
ParentID,
0 AS TreeLevel
FROM Table_1
WHERE ID = @ID
UNION ALL
SELECT
T.ID,
T.Name,
T.ParentID,
TreeLevel + 1
FROM Table_1 T
INNER JOIN CTE_Table_1 ON CTE_Table_1.ID = T.ParentID
)
SELECT * FROM CTE_Table_1
答案 1 :(得分:1)
尝试这项工作:http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=101053
-- Structure
create table dbo.MyPeople (Id int, Name varchar(30), ParentId int)
-- Data
insert dbo.MyPeople
select 1, 'P1', null
union all select 2, 'P2', null
union all select 3, 'P1C1', 1
union all select 4, 'P1C2', 1
union all select 5, 'P2C1', 2
union all select 6, 'P1C2C1', 4
union all select 7, 'P1C1C1', 3
union all select 8, 'P1C1C1C1', 7
union all select 9, 'P2C1C1', 5
union all select 10, 'P1C3', 1
go
-- Function
create function dbo.AncestorPath(@Id int) returns varchar(100) as
begin
declare @Path varchar(100)
while 0 = 0
begin
select @Path = cast(Id as varchar(5)) + isnull('/' + @Path, ''), @Id = ParentId
from dbo.MyPeople where Id = @Id
if @@rowcount = 0 break
end
return @Path
end
go
-- Calculation
select * from (
select *, dbo.AncestorPath(Id) as AncestorPath from dbo.MyPeople) a
where '/' + AncestorPath + '/' like '%/1/%'
或
尝试像这样的递归程序
ALTER PROCEDURE dbo.GetChildren
@ParentId int
AS
SET NOCOUNT ON
SELECT *
FROM MainTable
WHERE ChildId IN
(
SELECT ParentId
FROM f_GetChildren(@ParentId)
UNION
SELECT ChildId
FROM f_GetChildren(@ParentId)
)
ORDER BY ParentId
SET NOCOUNT OFF
RETURN
答案 2 :(得分:0)
从SQL Server 2005开始,Common Table Expressions已添加到SQL Server的T-SQL中,可帮助您进行此类层次查询。这就是你要找的东西!