[英]Xml output in SQL Server
我希望表输出为XML。 我的表结果是
我需要像这样的结果
询问
Declare @colorTable table (Category varchar(100),Attribute varchar(100))
insert into @colorTable values ('Color','Red')
insert into @colorTable values ('Color','Blue')
insert into @colorTable values ('Color','Green')
insert into @colorTable values ('Transport','Bus')
insert into @colorTable values ('Transport','Car')
insert into @colorTable values ('Transport','Twoweeler')
select * from @colorTable
FOR XML PAth(''), ROOT ('xml'), ELEMENTS;
谢谢,
桑达尔
我们必须使用GROUP BY
编写查询,XML路径不允许在xml path(not allowed select statement)
内写入sql xml path(not allowed select statement)
Declare @colorTable table (Category varchar(100),Attribute varchar(100))
insert into @colorTable values ('Color','Red')
insert into @colorTable values ('Color','Blue')
insert into @colorTable values ('Color','Green')
insert into @colorTable values ('Transport','Bus')
insert into @colorTable values ('Transport','Car')
insert into @colorTable values ('Transport','Twoweeler')
select T1.Category as '@Value',
(
select T2.Attribute as '@Value'
from @colorTable as T2
where T2.Category = T1.Category
group by T2.Attribute
for xml path('Attribute'), type
)
from @colorTable as T1
group by Category
for xml path('Category'), root('xml')
输出值
<xml>
<Category Value="Color">
<Attribute Value="Blue" />
<Attribute Value="Green" />
<Attribute Value="Red" />
</Category>
<Category Value="Transport">
<Attribute Value="Bus" />
<Attribute Value="Car" />
<Attribute Value="Twoweeler" />
</Category>
</xml>
好吧,在特定情况下要实现目标,您应该为三个子支行Color
, Transport
和Electronics
进行三个子选择,然后将该xml部件加入xml
根目录下。
您可以使用以下查询进行操作:
select
(
select
Attribute as 'attribute/@value'
from @colorTable
where Category = 'Color'
for xml path(''), type
) as Color,
(
select
Attribute as 'attribute/@value'
from @colorTable
where Category = 'Transports'
for xml path(''), type
) as Transports,
(
select
Attribute as 'attribute/@value'
from @colorTable
where Category = 'Electronics'
for xml path(''), type
) as Electronics
for xml path(''), root('xml')
看一下EXPLICIT Mode with FOR XML
MSDN的 EXPLICIT Mode with FOR XML
。 可能会很痛苦,但是您可以控制输出;-)
最后我把这样的代码
选择Category作为值,(从@colorTable中选择Attribute作为值,其中Category = a.Category
@colorTable中的FOR XML raw('attribute'),TYPE)按类别分组。FOR XML raw('category'),ROOT('xml'),type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.