问题
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