您的位置:首页 > 数据库

SQL FOR XML 查询【原创】

2009-10-30 10:24 302 查看
今天在群里碰到一个问题,群友说是一道面试题,禁不住好奇,问题如下:

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都通用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: