简体   繁体   English

如何在 SQL 服务器中递归获取值?

[英]How to get a values recursively in SQL Server?

I have below sample data.我有以下样本数据。

IF OBJECT_ID('tempdb..#tempData1') IS NOT NULL 
     DROP TABLE #tempData1

CREATE TABLE #tempData1
(
     ParentItemId varchar(20),
     ChildItemId varchar(20)
)

INSERT INTO #tempData1 VALUES('2000-194-819','2000-212-595')
INSERT INTO #tempData1 VALUES('2000-212-771','2000-212-704')
INSERT INTO #tempData1 VALUES('2000-212-704','2000-212-705')
INSERT INTO #tempData1 VALUES('2000-212-595','2000-211-801')
INSERT INTO #tempData1 VALUES('2000-212-801','2000-211-578')

I want to find ParentItemId and its children我想找到ParentItemId和它的孩子

WHERE ParentItemId = '2000-194-819'

I wrote this query:我写了这个查询:

SELECT B1.ParentItemID 
FROM #tempData1 B1 
WHERE NOT EXISTS (SELECT B2.ParentItemID 
                  FROM #tempData1 B2 
                  WHERE B2.ParentItemID = B2.ChildItemId)
  AND ParentItemID = '2000-194-819'

Current output:当前 output:

'2000-194-819'

Expected output:预期 output:

2000-194-819
2000-212-595
2000-212-801

Please help.请帮忙。

You can use a recursive CTE.您可以使用递归 CTE。 For example:例如:

with
n as (
  select ParentItemId, ChildItemId 
  from #tempData1 
  where ParentItemID = '2000-194-819'
 union all
  select d.ParentItemId, d.ChildItemId
  from n 
  join #tempData1 d on d.ParentItemId = n.ChildItemId
)
select * from n

The recursive CTE is made of two parts:递归 CTE 由两部分组成:

  • The first part of the CTE -- the anchor member -- is located before the UNION ALL clause and retrieves the first set of rows; CTE 的第一部分——锚成员——位于UNION ALL子句之前并检索第一组行; it's the starting point:这是起点:

     select ParentItemId, ChildItemId from #tempData1 where ParentItemID = '2000-194-819'
  • The second part of the CTE -- the recursive member -- is placed after the UNION ALL clause. CTE 的第二部分——递归成员——放在UNION ALL子句之后。 This part is executed iteratively for the new rows retrieved until it doesn't return any more rows.这部分对检索到的新行迭代执行,直到不再返回任何行。 This way you can walk a graph, as we are doing here.这样你就可以像我们在这里做的那样走一个图表。

     select d.ParentItemId, d.ChildItemId from n join #tempData1 d on d.ParentItemId = n.ChildItemId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM