该问题来自论坛提问,演示SQL代码如下
- --建立测试环境
- set nocount on
- create table test(ID varchar(20),NAME varchar(20))
- insert into test select '1','aaa'
- insert into test select '1','bbb'
- insert into test select '1','ccc'
- insert into test select '2','ddd'
- insert into test select '2','eee'
- go
- --测试
- select *from (select distinct id from test)a
- OUTER APPLY(
- select value='<root>'+(
- select name from test path
- where id = A.id
- for xml auto)+'<root/>') b
- --删除测试环境
- drop table test
- set nocount off
- /*--结果
- id value
- -------------------- --------------------------------------------------------------------
- 1 <root><path name="aaa"/><path name="bbb"/><path name="ccc"/><root/>
- 2 <root><path name="ddd"/><path name="eee"/><root/>
- */
本文展示了一段 SQL 代码示例,通过使用 FOR XML AUTO 子句将多个记录聚合为一个 XML 结构的字符串。具体操作包括创建测试表、插入数据、使用 OUTER APPLY 进行数据聚合并最终删除测试表。
378

被折叠的 条评论
为什么被折叠?



