XML SQL query Output format issue

亡梦爱人 提交于 2019-12-11 11:58:09

问题


My SQL query is:

select MedicalHeightValue, MedicalWeightValue 
from TableA

My column names & values are:

MedicalHeightValue(67), MedicalWeightValue(220)

Output should be like:

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

回答1:


Try something like this:

;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')



回答2:


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

you can also do this without explicitly specifying columns:

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')

but I think it's a bit overkill for your task



来源:https://stackoverflow.com/questions/19492459/xml-sql-query-output-format-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!