SQL FOR XML 查询【原创】

  今天在群里碰到一个问题,群友说是一道面试题,禁不住好奇,问题如下:

id  strvalue type
1    how      1
2    are      1
3    you      1
4    fine     2
5    thank    2
6    you      2

要求用sql把它们搜索出来成为这样的
#how are you#fine thank you#

 

下面这个Select XML是我实现的,没有格式化,有点乱。。。嘿嘿

SQL-CODE select (select '#'+replace(replace((SELECT strvalue FROM tb_test t
 where type = 1 FOR XML AUTO),'<t strvalue="',' '),'"/>', ' ')+'#')+
 (select replace(replace((SELECT strvalue FROM tb_test t
 where type = 2 FOR XML AUTO),'<t strvalue="',' '),'"/>', ' ')+'#')

05里面的测试通过

群里有人给出了另一个实现方法:

SQL-CODEdeclare @t table(id int identity(1,1),v varchar(10),t int,temp varchar(max))
insert @t
select v='how',t=1,temp=''
union all select 'are',1,''
union all select 'you',1,''
union all select 'fine',2,''
union all select 'thank',2,''
union all select 'you',2,''

declare @t1 int,@temp varchar(max)
set @temp=''
update @t set @temp=case when t=@t1 then @temp+' '+v else @temp+'#'+v end
,@t1=t,temp=@temp from @t
select max(temp)+'#' from @t


select * from @t
--#how are you#fine thank you#

2000和05都通用

转载于:https://www.cnblogs.com/myssh/archive/2009/10/30/1592846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值