我有一个这样的表,在同一个表中有一个父子关系
AccountID| ParentID | AccountName ---------------------------------------------- 1 | 0 | Root 2 | 1 | Child1 3 | 1 | Child2 4 | 2 | Child3 5 | 4 | Child1 6 | 5 | Child1 7 | 6 | Child1 8 | 6 | Child1
因此,当我发送帐户ID 7 时,我必须按顺序获取表格,如孩子,父亲,祖父......那样..所以对于7,我需要得到所有的parets像此
AccountID --------- 7 6 5 4 2 1
答案 0 :(得分:5)
您可以使用recursive CTE:
declare @childAccID int
set @childAccID = 7
;WITH Rec_CTE
AS(
SELECT 1 AS Level,
tChild.*
FROM dbo.TableName tChild
WHERE tChild.AccountID = @childAccID
UNION ALL
SELECT Level + 1 AS Level,
parent.*
FROM Rec_CTE tParent
INNER JOIN dbo.TableName parent
ON parent.AccountID = tParent.ParentID
)
SELECT * FROM Rec_CTE
ORDER BY Level
答案 1 :(得分:4)
试试这个:
create table DemoTable
(
accountid bigint
,parentid bigint
,accountname nvarchar(128)
)
insert DemoTable(accountid,parentid,accountname)
select 1, null, 'Root'
union select 2, 1, 'Child1'
union select 3, 1, 'Child2'
union select 4, 1, 'Child3'
union select 5, 2, 'Child1.1'
union select 6, 2, 'Child1.2'
go
declare @findMe bigint = 6;
with myCTE as
(
select accountid,parentid,accountname,1 hierarchyLevel
from DemoTable
where accountid = @findMe
union all
select b.accountid,b.parentid,b.accountname, a.hierarchyLevel + 1
from myCTE a
inner join DemoTable b
on b.accountid = a.parentid
)
select * from myCTE
order by hierarchyLevel