在sqlserver中从2005开始支持树形递归查找,其方法如下:
--从给定的根节点(可以是多个)向下查找,直到所有子节点
with myT2 as( select * from 表名 Where 根节点查询条件
union all
select 表名.* from myT2 inner join 表名 on myT2.ID=表名.ParentID)
select * from myT2
--从给定的子节点(可以是多个)向上查找,直到所有根节点
with myT2 as( select * from 表名 Where 子节点查询条件
union all
select 表名.* from myT2 inner join 表名 on myT2.ParentID=表名.ID)
select * from myT2