SqlServer with递归查询的使用

SqlServer with递归查询的使用

with tempAgent (AgentId,ParentId)

as(

select AgentId,ParentId from AgentInfo where AgentId=2 --要查询的根节点

union all

select a.AgentId,a.ParentId from AgentInfo a   --所有查询出所有的数据

inner join tempAgent on a.ParentId=tempAgent.AgentId --查询父节点等于Id的数据

)

select * from tempAgent

AgentId ParentId

2 1

7 2

8 2

9 7

原文地址:https://www.cnblogs.com/eimers/p/9025619.html