在写一句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