With as 递归查询

use TEST
create 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 CTE1
as
(
    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 ;

 

转载于:https://www.cnblogs.com/wjshan0808/p/4264419.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值