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都通用
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都通用
相关文章推荐
- T-SQL系列之合并多行查询数据到一行:FOR XML PATH
- [已解决]:通过sql for xml查询到的xml字符串,如何存为标准格式的xml文件?
- SQL 字段charindex,stuff,ltrim, for xml path('') 操作字符串 合并查询结果项值
- SQL查询-将列转换成字符串(for xml path)
- for xml path以及sql合并查询
- 对sql for xml的查询结果作分页处理思路
- SQL SERVER中 用FOR XML PATH将查询结果以XML输出 然后应用于 sql 合并字段功能介绍
- 查询 SQL_Server 所有表的记录数: for xml path
- SQL Server2005中使用XML-FOR XML(RAW模式查询)
- SQLServer For XML Path的运用
- SQL SERVER FOR XML PATH
- 灵活运用 SQL SERVER FOR XML PATH
- 关于hibernate纯sql查询返回结果集的问题(hbm.xml中不写多表关联)
- 使用SQL查询DB2 9中的XML数据
- SQLServer2005 XML在T-SQL查询中的典型应用
- 数据库查询XML结构,FOR XML PATH 语句的应用
- 利用 T-sql 的从句 for xml path('') 实现多行合并到一行, 并带有分隔符
- SQL查询xml内容
- SQL Server FOR XML
- SQL之 Stuff和For xml path