sql递归

create table region
(
	id int primary key identity(1,1),
	name nvarchar(50),
	upperId int
)

insert into region(name) values('中国');
insert into region(name) values('美国');
insert into region(name,upperId) values('浙江',1);
insert into region(name,upperId) values('江苏',1);
insert into region(name,upperId) values('加州',2);
insert into region(name,upperId) values('嘉兴',3);
insert into region(name,upperId) values('嘉善',6);

select * from region;

with reg as 
( 
    select id,name,upperId from region where id=2
    union all 
    select r.id,r.name,r.upperId from reg
    inner join region r on reg.id = r.upperId
) 
select * from reg 

获取全路径

with reg as 
( 
    select ParameterID,Code,Name,UpperID
    ,cast(Code AS nvarchar(4000)) Path_Code
    ,cast(Name AS nvarchar(4000)) Path_Name 
	FROM SYS_Parameter_EN where Code='EvaluationOfItem'
    union all 
    select r.ParameterID,r.Code,r.Name,r.UpperID
	,cast((reg.Path_Code+'/'+r.Code) AS nvarchar(4000)) Path_Code
    ,cast((reg.Path_Name+'/'+r.Name) AS nvarchar(4000)) Path_Name from reg
    inner join SYS_Parameter_EN r on reg.ParameterID = r.UpperID
) 
select * from reg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值