如何在SQL中输出带有属性和字段值的xml

时间:2011-12-14 09:38:52

标签: xml tsql

我想从xml中的表中输出一些字段。我需要将列的名称放在name-attribute中。输出必须类似于:

<udfields>
<udfield name="infoplanner">Test for the info</udfield>
<udfield name="plant">Amsterdam</udfield>
<udfield name="capability"/>
</udfields>

我尝试过这样的事情:

SELECT TOP 3
    ko.infoPlanner AS "udfield/name/@infoplanner"
  , ko.plant AS "udfield/name/@plant"
  , ko.capability AS "udfield/name/@capability"
FROM    sometable ko
WHERE   CONVERT(VARCHAR(8), ko.datumtijd, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)
        AND COALESCE(ko.infoPlanner, '') <> ''
FOR     XML PATH('')

提前感谢,莱昂

1 个答案:

答案 0 :(得分:7)

我猜你正在寻找这样的东西:

declare @T table
(
  infoplanner int,
  plant int,
  capability int
)

insert into @T
select 1, 2, 3 union all
select 10, 20 ,30

select (select 'infoplanner' as '@name', 
               infoplanner as '*' 
        for xml path('udfield'), type),
       (select 'plant' as '@name',
               plant as '*' 
        for xml path('udfield'), type),
       (select 'capability' as '@name',
               capability as '*' 
        for xml path('udfield'), type)
from @T
for xml path('udfields')

结果:

<udfields>
  <udfield name="infoplanner">1</udfield>
  <udfield name="plant">2</udfield>
  <udfield name="capability">3</udfield>
</udfields>
<udfields>
  <udfield name="infoplanner">10</udfield>
  <udfield name="plant">20</udfield>
  <udfield name="capability">30</udfield>
</udfields>