sql server 递归查询
向上递归
比如:北京市海淀区XX街道XX号,如果我们只存储【XX号】,但是想要显示【北京市海淀区XX街道XX号】。
--向上递归 用子节点查询所有父节点
with temp
as
(
select * from 表名 where Id='123'
union all
select a.* from 表名 a inner join temp on a.Id = temp.ParentId
)
select * from temp
向下递归
比如:一个5级树形图,我们要查询到某3级节点下的所有4级节点和5级节点。
--向下递归 用父节点查询所有子节点
with temp
as
(
select * from 表名 where Id='01'
union all
select a.* from 表名 a inner join temp on a.ParentId = temp.Id
)
select * from temp
将递归查询出的数据作为查询条件查询其他表
比如:
1、有一个与5级树形图关联的列表。
2、当树形图中某一个第3级节点设置无效时,那么关联在这个第3级节点下的所有数据都不显示,包括3级节点下的4级节点、5级节点以及相关联的列表信息。
3、在这种情况下,我们需要先查出所有有效树形图数据,在根据查询到的数据查询出有效的列表信息。
--将递归查询出的数据作为查询条件查询其他表
with temp
as
(
select * from 表名 where Id='01'
union all
select a.* from 表名 a inner join temp on a.ParentId = temp.Id
)
select * from temp
LEFT OUTER JOIN 表名1 as x ON x.字段名 = temp.Id
where 其他条件