SQL 中的尖括号">"自动转成>,SQL递归简单写法

在写一句SQL的时候,发现有时SQL会自动把> 转成>

代码如下:

if object_id('t_001') >0 drop table t_001
create table t_001 (id int ,val varchar(100),nid int)
insert into t_001 
select 0,'我',1 union 
select 1,'爱',2 union
select 2,'听',3 union
select 3,'你',4 union
select 4,'说',5 union
select 5,'我',6 union
select 6,'是',7 union
select 7,'乖',8 union
select 8,'猪',9 union
select 9,'猪',NULL 

select * from t_001

if object_id('f_t_001')>0 drop function f_t_001
go
create function f_t_001 ( @id int,@nid int)
returns varchar(500)
as
begin
	declare @tval varchar(20),@tid int,@tnid int
	select @tval=val,@tid=id ,@tnid=nid
    from t_001
    where id=@id
	return
		case
		when @id=@nid  or isnull(@tnid,'')='' then  isnull(@tval,'') 

		else isnull(@tval+'->'+dbo.f_t_001(@tnid,@nid),'') 
		end
end

go 
select dbo.f_t_001 (3,8)


这是原来的传统方法 ,FUNCTION

返回结果:你->说->我->是->乖->猪

 

select 
stuff(
(select  '->',val+'' from t_001 where id between 3 and 8 for xml path(''))
,1,2,'')

但发现出来的结果是:gt;你->说->我->是->乖->猪

没找到是什么原因,也不管了,就这么着吧,直接用Replace

select 
stuff(
Replace(
(select  '->' +'',val+'' from t_001 where id between 3 and 8 for xml path(''))
,'>','>')
,1,2,'')

出来的答案是对了,但为什么一定要Replace呢?

如果你有更好的办法,请告知,谢谢

 

如果这个NID是不连续的,例如,如下的数据,

if object_id('t_001') >0 drop table t_001  
create table t_001 (id int ,val varchar(100),nid int)  
insert into t_001   
select 0,'我',1 union   
select 1,'爱',3 union  
select 2,'听',4 union  
select 3,'你',2 union  
select 4,'说',5 union  
select 5,'我',6 union  
select 6,'是',7 union  
select 7,'乖',8 union  
select 8,'猪',9 union  
select 9,'猪',NULL  


就不能直接用上面的代码了,而要先根据NID获取,可以利用SQL2005以上版本的WITH,实现递归

with ctea (id,val,nid,tlevel) as
(
select id,val,nid,0 as tlevel from t_001 where id = 0
union all 
select t.id,t.val,t.nid,e.tlevel+1 from t_001 t inner join ctea e on e.nid = t.id
)
select * from ctea order by tlevel


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值