SQL Server中的递归查询

来源:互联网 发布:nginx cookie 跨域 编辑:程序博客网 时间:2024/05/17 06:01

Sql Server中不支持Connect by子句进行递归查询,不过可以通过使用with子句来实现递归查询。

下面来看下with子句的用法

with temp as  (Select fid,fnumber,fname,fmanagerIdfrom t_personwhere fmanagerId is not null)Select fid,fnumber,fname,fmanagerId from temp

看下运行结果



该语句将temp当做临时表,将数据暂时保存在里面。

下面看一下SQL语句使用嵌套定义的子查询temp来实现递归查询

With temp (fid,fnumber,fname,fmanagerid) as (Select t.fid,t.fnumber,t.fname,t.fmanagerid from T_person t where t.fid=’00001’Union allselect c.fid,c.fnumber,c.fname,c.fmanagerid from temp p,T_Person c where p.fid=c.fmanagerId)Select distinct fid,fnumber,fname,fmanagerid from temp order by fmanagerid,fid,fnumber,fname

执行结果:


这个递归查询SQL语句的核心部分在子查询中定义,子查询中使用UNION ALL操作符将两个select语句联合起来,第一个select语句作为查询条件,第二个select语句将temp和T_Person通过“where p.fid=c.fmanagerId”链接起来,第二个select语句会循环调用temp,从而列出Person表中id位”00001”的所有层次信息。


0 0