--估计是这样的吧,表设计不太合理--表一:存放这颗树的顶层结点。
select ID=identity(int),TopNode=ParentNode
into tb1
from(
select distinct ParentNode from TblTree a
where not exists(
select * from TblTree
where ChileNode=a.ParentNode
)a
--表二:存放这棵树的最底层的叶结点,也就是说这些结点再也没有下层数据了。
select ID=identity(int),BottomNode=a.ChileNode,TopNodeID=b.id
into tb2
from(
select distinct ParentNode,ChileNode from TblTree a
where not exists(
select * from TblTree
where ParentNode=a.ChileNode
)a,tb1 b where a.ParentNode=b.TopNode
--表三:存放这棵树的非顶层结点,也就是说除了顶层结点的所有结点都要放进来,当然也包括中间层结点和叶结点。
select ID=identity(int),ChildNode=a.ChileNode,TopNodeID=b.id
into tb2
from(
select distinct a.ParentNode,a.ChileNode 
from TblTree a left join(
select ParentNode from tb1
union
select BottomNode from tb2
)b on a.ParentNode=b.ParentNode or a.ParentNode=b.ChileNode
where b.b.ParentNode  is null or b.ChileNode is null
)a,tb1 b where a.ParentNode=b.TopNode