• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wjshan0808

Learn from yesterday, Live for today, For a better tomorrow.
 ————wjshan0808

博客园    首页    新随笔    联系   管理    订阅  订阅

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 ;

 


posted @ 2015-01-31 17:54  wjshan0808  阅读(223)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3