我有父表与父子关系的表:
NodeId NodeName ParentId ------------------------------ 1 Node1 0 2 Node2 0 3 Node3 1 4 Node4 1 5 Node5 3 6 Node6 5 7 Node7 2
这里parentId = 0表示它是根级别节点.现在我想编写一个SQL查询,它将在父类别的所有级别返回子级.
例如对于nodeId = 1,它应该返回3,4,5,6.
我正在使用MS sql Server 2005
解决方法
with [CTE] as ( select * from [TheTable] c where c.[ParentId] = 1 union all select * from [CTE] p,[TheTable] c where c.[ParentId] = p.[NodeId] ) select * from [CTE]