XML SQL查询输出格式问题

时间:2013-10-21 10:48:07

标签: sql sql-server xml sqlxml

我的SQL查询是:

select MedicalHeightValue, MedicalWeightValue 
from TableA

我的专栏名称&值是:

MedicalHeightValue(67), MedicalWeightValue(220)

输出应该是:

<HealthAttribute>
   <Identifier>MedicalHeightValue</Identifier>
   <Value>67</Value>
</HealthAttribute>
<Healtttribute>
   <Identifier>MedicalWeightValue</Identifier>
   <Value>220</Value>
</HealthAttribute>

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

;WITH CteData AS
(
    SELECT  
        'MedicalHeightValue' AS 'Identifier', MedicalHeightValue AS 'Value' 
    FROM dbo.TableA

    UNION ALL

    SELECT  
       'MedicalWeightValue' AS 'Identifier', MedicalWeightValue AS 'Value' 
    FROM dbo.TableA
)
SELECT *
FROM CteData
FOR XML PATH('HealthAttribute')

答案 1 :(得分:0)

select C.Value, C.Identifier
from TableA
    outer apply (values
        ('MedicalHeightValue', MedicalHeightValue),
        ('MedicalWeightValue', MedicalWeightValue)
    ) as C(Identifier, Value)
for xml path('HealthAttribute')

您也可以在不明确指定列的情况下执行此操作:

with cte(data) as (
    select * from TableA for xml path(''), type
), cte2 as(
    select
        T.C.value('.', 'nvarchar(max)') as Value,
        T.C.value('local-name(.)', 'nvarchar(max)') as Identifier
    from cte as c
        outer apply c.data.nodes('*') as T(C)
)
select *
from cte2
for xml path('HealthAttribute')

但我觉得你的任务有点过分