SQL FOR XML 查詢【原創】

來源:互聯網
上載者:User

  今天在群裡碰到一個問題,群友說是一道面試題,禁不住好奇,問題如下:

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-CODE

declare @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都通用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.