自上向下的查询方法,查询出自身以及所有的子孙数据:

--自上往下搜索
;with maco as
(
select * from ty_Dictionary where id =21
union all 
select t.* from ty_Dictionary t,maco m where t.ParentID=m.ID
)
select distinct * from maco order by id desc

 

自下向上查询,查询出自身以及所有的直系祖先:

--自下往上搜索
;with maco as
(
select * from ty_Dictionary where id=23
union all 
select t.* from ty_Dictionary t,maco m where t.ID=m.ParentID
)
select * from maco order by id

 

删除自身以及所有的子孙数据:

;with maco as
(
select ID,ParentID from ty_Dictionary where ID=21
union all 
select t.ID,t.ParentID from ty_Dictionary t,maco m where t.ParentID=m.ID
)
delete from ty_Dictionary where ID in( select ID from maco group by ID)

 

 posted on 2017-10-25 17:27  F风  阅读(1030)  评论(1编辑  收藏  举报