根节点下子节点层级不定,可能3、4、5层,LEVEL字段表示层级,PID字段父节点ID。
如何根据ID字段(可能为任何层ID)取LEVEL为1(根节点)
http://blog.csdn.net/softkexin/article/details/7389443
这种答案社区很多,大多数时候得用到递归,对与新手有些比较难写
那样写菜鸟我看不懂
能不能多写些注释解释一下,公用表表达式实现子节点查询父节点。现在急需要这个
--公用表表达式实现子节点查询父节点(SqlServer2005+)
DECLARE @ChildID int
SET @ChildID=6
DECLARE @CETParentID int
select @CETParentID=PID FROM tb where ID=@ChildID
with CTEGetParent as
(
select * from tb where ID=@CETParentID
UNION ALL
(SELECT a.* from tb as a inner join
CTEGetParent as b on a.ID=b.PID
)
)
SELECT * FROM CTEGetParent
昨天找出来的一个简单的实现方式
with cte as
(
select a.* from 表名 a where id='子节点ID
union all
select k.* from 表名 k inner join cte c on c.pid = k.id
)select * from cte
where cte.level = '1'--过滤层级