SQL Recursive:获取孩子的父值
Posted
技术标签:
【中文标题】SQL Recursive:获取孩子的父值【英文标题】:SQL Recursive: Get parent value for child 【发布时间】:2020-05-13 12:55:51 【问题描述】:我创建了一个返回所有父母和所有孩子的递归 SQL。父母总是在 KFID 列中有一个值,孩子没有。如何从一个父级为其所有子级选择 KFID 值?
SELECT B.LFDNR
,convert(varchar(max), '') /*convert(varchar(max), ROW_NUMBER() OVER(ORDER BY B.POSI))*/ AS Position
,0 as FLAG
,B.KFID
,B.BGRNR
FROM MU_Navigator.KONFIG_BASE B -- WITH (NOLOCK)
WHERE (B.BELID = @belegLfdnr)
AND (ISNULL(B.PAREN, '') = '') -- is root / hasnt parent
UNION ALL
SELECT B.LFDNR
,CASE WHEN T.Position = '' THEN '' ELSE T.Position + convert(varchar(max), '.') END + convert(varchar(max), ROW_NUMBER() OVER(ORDER BY B.POSI)) AS Position
,0 as flag
,B.KFID
,t.BGRNR
FROM MU_Navigator.KONFIG_BASE B INNER JOIN
KBTree T
ON (B.PAREN = T.LFDNR) -- on primary key, bijective n:1 relation
WHERE (B.BELID = @belegLfdnr) -- redundant, but query plan is much more efficient with that prefilter
当前结果:
+------------+----------+------+--------+-------+
| LFDNR | Position | flag | KFID | BGRNR |
+------------+----------+------+--------+-------+
| 0260897021 | | 0 | NULL | BU |
| 0260897022 | 1 | 0 | 004530 | BU |
| 0260897170 | 1.1 | 0 | NULL | BU |
| 0260897153 | 1.2 | 0 | NULL | BU |
| 0260897023 | 2 | 0 | 002442 | BU |
| 0260897025 | 2.1 | 0 | NULL | BU |
| 0260897024 | 3 | 0 | 002524 | BU |
| 0260897026 | 3.1 | 0 | NULL | BU |
+------------+----------+------+--------+-------+
【问题讨论】:
你想要什么结果? 【参考方案1】:在第二个子查询中,我想你要替换:
B.KFID
与:
COALESCE(B.KFID, T.KFID)
这应该在层次结构中引入最新的KFID
。
【讨论】:
以上是关于SQL Recursive:获取孩子的父值的主要内容,如果未能解决你的问题,请参考以下文章