鉴于我有这个结果集结构(多余的字段已被剥离)
Id | ParentId | Name | Depth
----------------------------
是否可以按树顺序返回记录,即Parent
,Children
如果 aChild
是 a Parent
,那么它们的Children
,如果不是 thenSibling
等等?例如,
Id | ParentId | Name | Depth
----------------------------
1 NULL Major 1
2 1 Minor 2
3 1 Minor 2
4 3 Build 3
5 3 Build 3
6 1 Minor 2
/* etc, etc */
我能想到的唯一方法就是遵循这篇文章 -
并针对每条记录包含[LeftExtent]
和[RightExtent]
字段。现在文章中的 SQL 在Ids
唯一时可以正常工作,但是在这种特定的树结构中,相同的记录Id
可能会出现在树中的不同位置(ParentId
显然字段不同)。我认为问题出在文章中的这个 SQL 中 -
INSERT INTO @tmpStack
(
EmployeeID,
LeftExtent
)
SELECT TOP 1 EmployeeID, @counter
FROM Employee
WHERE ISNULL(ParentID, 0) = ISNULL(@parentid,0)
/* If the Id has already been added then record is not given [LeftExtent] or [RightExtent] values. */
AND EmployeeID NOT IN (SELECT EmployeeID FROM @tmpStack)
如何更改它以允许为具有重复的记录Ids
提供 [LeftExtent] 和 [RightExtent] 值,或者我完全错过了一种更简单的方法来按我需要的顺序返回结果集?