1

我的 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>
4

2 回答 2

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')
于 2013-10-21T10:59:27.257 回答
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')

但我认为这对你的任务来说有点矫枉过正

于 2013-10-21T11:30:02.163 回答