首页 > 数据库技术 > 详细

sqlserver查询父子级关系

时间:2017-10-25 17:44:40      阅读:372      评论:0      收藏:0      [点我收藏+]

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

--自上往下搜索
;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)

 

sqlserver查询父子级关系

原文:http://www.cnblogs.com/williamwsj/p/7730071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!