首页 > 代码库 > With as 递归查询
With as 递归查询
use TESTcreate table Provinces( pro_Id int primary key identity(1,1), pro_Name nvarchar(255), pro_Code nvarchar(8), pro_PId int) exec sp_rename ‘Provinces‘, ‘Area‘select * from Area execute sp_rename ‘Area.pro_Id‘,‘a_Id‘,‘Column‘insert into Area values(‘河南省‘,‘0023‘,0)insert into Area(a_Name,a_Code,a_PId) values(‘郑州市‘,‘0024‘,1)insert into Area values(‘金水区‘,‘0025‘,2)insert into Area values(‘北京市‘,‘0021‘,0)insert into Area(a_Name,a_Code,a_PId) values(‘朝阳区‘,‘0022‘,4) --若declare @count int;--; 必须的--公共表表达式--1:/*with CTE1(id) AS(--查询出当前省(父)SELECT a_Id FROM Area where a_Code=‘0023‘ union all --显示当前级别以下的所有有关的数据(子)select Area.a_Id from CTE1 --查找出属于当前省的数据 inner join Area on CTE1.id=Area.a_PId --递归 ),CTE2 as( --总计 select count(*) as cou from CTE1 ) */--2:with CTE1as( select a_Id from Area where a_Code=‘0021‘union all select Area.a_Id from CTE1 inner join Area on CTE1.a_Id=Area.a_PId)--select * from Area where a_Id in( select * from CTE1) union select null,null,‘总计‘, cou from CTE2;--则print @count ;
With as 递归查询
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。