![](/img/trans.png)
[英]Given any child in the hierarchy, fetch complete tree by INFORMIX hierarchical SQL
[英]Recursively generate hierarchy for any given node in the tree?
此CTE提取SuiteID
和ParentSuiteID
的层次结构作为下面的结果集。 我想传递作为各自级别的父级的SuiteID
和所有SuiteID
。
WITH HIERARCHY AS
( select T1.SuiteID,T1.Title,T1.ParentSuiteID, 0 Level
FROM tbl_Suite(nolock) T1
Where T1.ParentSuiteID = 0 AND T1.PlanID = '404'
UNION ALL
select T2.SuiteID,T2.Title,T2.ParentSuiteID,Level+1
from tbl_Suite(nolock) AS T2
INNER JOIN HIERARCHY AS H ON T2.ParentSuiteID = H.SuiteID
)
SELECT *
FROM HIERARCHY
+---------+------------------------+---------------+-------+ | SuiteID | Title | ParentSuiteID | Level | +---------+------------------------+---------------+-------+ | 10664 | root | 0 | 0 | | 10681 | Prod Test Environment | 10664 | 1 | | 11097 | Dev Test Environment | 10664 | 1 | | 11155 | Training Environment | 10664 | 1 | | 11156 | Production Environment | 10664 | 1 | | 11100 | Bridge PMS | 11097 | 2 | | 11126 | Bridge PTS | 11097 | 2 | | 11139 | Client 360 | 11097 | 2 | | 11140 | Contact Manager | 11097 | 2 | | 11145 | Revenue DashBoard | 11097 | 2 | | 11141 | Finance flow | 11140 | 3 | | 11142 | Premium Finance flow | 11140 | 3 | | 11143 | Client Contacts | 11140 | 3 | | 11127 | Direct Bill | 11126 | 3 | +---------+------------------------+---------------+-------+
我想编写一个查询,通过时提供以下结果集(SuiteID = 11100):
SuiteID Title ParentSuiteID Level 10664 root 0 0 11097 Dev Test Environment 10664 1 11100 Bridge PMS 11097 2
Declare @Table table (SuiteID int,Title varchar(50),ParentSuiteID int)
Insert into @Table values
(10664 ,'root ', 0),
(10681 ,'Prod Test Environment ',10664 ),
(11097 ,'Dev Test Environment ',10664 ),
(11155 ,'Training Environment ',10664 ),
(11156 ,'Production Environment ',10664 ),
(11100 ,'Bridge PMS' ,11097 )
Declare @Fetch int = 11100
;with cteHB as (
Select SuiteID
,ParentSuiteID
,Lvl=1
,Title
From @Table
Where SuiteID =@Fetch
Union All
Select R.SuiteID
,R.ParentSuiteID
,P.Lvl+1
,R.Title
From @Table R
Join cteHB P on P.ParentSuiteID = R.SuiteID )
Select Lvl = Row_Number() over (Order By Lvl Desc) -1
,SuiteID
,ParentSuiteID
,Title
From cteHB
Order By 1
退货
Lvl SuiteID ParentSuiteID Title
0 10664 0 root
1 11097 10664 Dev Test Environment
2 11100 11097 Bridge PMS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.