今天用到了sql的递归查询.递归查询是CTE语句with xx as(....)实现的. 假如表Category数据如下. 我们想查找机枪这个子分类极其层次关系(通过子节点,查询所有层级节点).以下是查询语句 WITH tt AS ( SELECT CategoryId,Name,Parent,0 level FROM dbo.Category WHERE CategoryId=15 --定位点成员 UNION ALL SELECT c.CategoryId,c.Name,c.Parent,tt…
CTE是如何进行递归的?产生递归的条件有三个,分别是 初始值 自身调用自身 结束递归的条件 1,示例代码 ;with cte as ( as jd union all as jd from cte ) select * from cte 查询结果如下 2,递归过程分析 2.1 初始值 select 1 as id, 1 as jd 提供初始值,CTE中的值只有这一个. 2.2 第一次递归调用 select id +1 as id ,jd+2 as jdfrom ctewhere id<10 在第…
SQL递归查询(with cte as) with cte as( select Id,Pid,DeptName,0 as lvl from Department where Id = 2 union all select d.Id,d.Pid,d.DeptName,lvl+1 from cte c inner join Department d on c.Id = d.Pid)select * from cte 1 表结构 Id Pid …