数据库设计中经常碰到父子节点的关系结构,经常需要找到某个节点的根,或者某个节点的所有子节点,一般做法都是在业务层做递归的方式实现,或者数据库存储过程实现。但其实SQLServer提供的CTE可以很好的简化我们的工作,非常方便的实现这一功能。

例子:
妙用CTE,一条语句实现sql递归查询,SQLServer 递归  

1.正向递归,找某个节点下的所有子节点

with t as--如果CTE前面有语句,需要用分号隔断
(selectId,ParentId,Name
from WMS_Org whereId='2'union all select r1.Id,r1.ParentId,r1.Name from WMS_Org r1 join t as r2 on r1.ParentId= r2.Id) select*from t order byId

 

2.逆向递归,找某个节点下的上层节点,直至根节点

with t as--如果CTE前面有语句,需要用分号隔断
(selectId,ParentId,Name
from WMS_Org
where Id='9'union all
select r1.Id,r1.ParentId,r1.Name
from WMS_Org r1 join t as r2 on r1.Id= r2.ParentId)
select*from t order byId

 

仅仅是这里条件的变化哦:select r1.Id,r1.ParentId,r1.Name from WMS_Org r1 join t as r2 on r1.Id = r2.ParentId

Proc可参考:         http://www.cnblogs.com/keepfool/archive/2012/02/05/2338700.html

相关文章:

  • 2022-12-23
  • 2021-09-17
  • 2021-11-04
  • 2021-06-19
  • 2021-10-26
  • 2021-05-31
  • 2022-03-05
猜你喜欢
  • 2021-07-22
  • 2021-08-01
  • 2021-08-05
  • 2021-07-18
  • 2022-12-23
相关资源
相似解决方案