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 表结构 Id Pid DeptName ----------- ----------- ---------------…
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 …
今天用到了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…
网易新闻的盖楼乐趣多,某一天也想实现诸如网易新闻跟帖盖楼的功能,无奈技术不佳(基础不牢),网上搜索了资料才发现SQL查询方法有一种叫递归查询,整理如下: 一.查询出 id = 1 的所有子结点 with my1 as (select * from table where id = 1 union all select table.* from my1, table where my1.id = table.fatherId) select * from my1 结果包含1这条记录,如果不想包含,…
1.数据环境准备 参考Oracle递归查询文章. 2.查询某个节点下的所有子节点 with cte(id,name,parent_id) as ( select id,name,parent_id from SC_DISTRICT where name='巴中市' union all select sd.id,sd.name,sd.parent_id from SC_DISTRICT sd ,cte c where c.id = sd.parent_id )select * from cte r…
数据库设计中经常碰到父子节点的关系结构,经常需要找到某个节点的根,或者某个节点的所有子节点,一般做法都是在业务层做递归的方式实现,或者数据库存储过程实现.但其实SQLServer提供的CTE可以很好的简化我们的工作,非常方便的实现这一功能. 例子: 1.正向递归,找某个节点下的所有子节点 with t as--如果CTE前面有语句,需要用分号隔断(selectId,ParentId,Name from WMS_Org whereId'union all select r1.Id,r1.Paren…