您可以使用以下查询:
;WITH Attrs AS (
-- Anchor query: Get the root records
SELECT row, value, displayvalue, parentrow, parentvalue
FROM x
WHERE parentrow IS NULL
UNION ALL
-- Recursive query: Get the records of the next level
SELECT child.row, child.value, child.displayvalue, child.parentrow, child.parentvalue
FROM x AS child
INNER JOIN Attrs AS parent
ON child.parentrow = parent.row AND child.parentvalue = parent.value
)
SELECT row, value, displayvalue, parentrow, parentvalue
FROM Attrs
递归的第一个子查询
CTE
,也称为
锚
查询,获取层次结构的根记录。因此,您必须放置
parentrow IS NULL
在此子查询上。
第二个子查询将表与前一个递归的结果连接起来,以获取树层次结构中下一级的记录。没有必要使用
parentrow为空
在这个子查询中,由于第一次执行递归产生的记录是
已经
根节点记录。
Demo here
编辑:
将序号添加到我们得到的查询中:
;WITH Attrs AS (
-- Anchor query: Get the root records
SELECT row, seqno, value, displayvalue,
parentrow, parentvalue, parentseq
FROM x
WHERE parentrow IS NULL
UNION ALL
-- Recursive query: Get the records of the next level
SELECT child.row, child.seqno, child.value, child.displayvalue,
child.parentrow, child.parentvalue, child.parentseq
FROM x AS child
INNER JOIN Attrs AS parent
ON child.parentrow = parent.row AND
child.parentvalue = parent.value AND
child.parentseq = parent.seqno
)
SELECT row, value, displayvalue, parentrow, parentvalue
FROM Attrs