0

我的 XML 看起来像这样:

biometrictDate, biometricID,dateOfBirth, firstName, gender, 
lastName, consumerUserId, MedicalHeightValue

是表中的所有列。

<Assessment biometrictDate="20120305 08:03:00" biometricID="74330759" 
            dateOfBirth="1975-04-08" firstName="BRYAN" gender="M" lastName="HAYES" 
            consumerUserId="120004223500"> 
    <HealthAttribute>
        <Identifier>MedicalHeightValue</Identifier>
        <Value>67</Value>
    </HealthAttribute>
</Assessment>

MedicalHeightValue应该单独放置在HealthAttribute使用以下查询完成的标签之间:

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

现在我只想要评估标签中的以下列

{biometrictDate, biometricID, dateOfBirth, firstName, gender, lastName, consumerUserId} 

请问有什么帮助吗?

新的 XML 应该如下所示:

<Assessment biometrictDate="20120305 08:03:00" biometricID="74330759" 
            dateOfBirth="1975-04-08" firstName="BRYAN" gender="M" lastName="HAYES" 
            consumerUserId="120004223500"> 
   <HealthAttribute> 
      <Identifier>MedicalHeightValue</Identifier> 
      <Value>67</Value> 
   </HealthAttribute> 
</Assessment>
4

1 回答 1

0

首先,真的很难理解你想要得到什么。我想我已经从你的问题和你以前的问题(顺便说一句,仍然没有公认的答案)中弄清楚了这一点。

这是您需要的查询:

select
    A.biometrictDate, A.biometricID, A.dateOfBirth,
    A.firstName, A.gender, A.lastName, A.consumerUserId,
    (
        select *
        from (values
            ('MedicalHeightValue', A.MedicalHeightValue),
            ('MedicalWeightValue', A.MedicalWeightValue)
        ) as V(Identifier, Value)
        for xml path('HealthAttribute'), type
    )
from table1 as A
for xml raw('Assessment')

您也可以这样做,以更好地控制名称:

select
    A.biometrictDate as [@biometrictDate],
    A.biometricID as [@biometricID],
    A.dateOfBirth as [@dateOfBirth],
    A.firstName as [@firstName],
    A.gender as [@gender],
    A.lastName as [@lastName],
    A.consumerUserId as [@consumerUserId],
    (
        select *
        from (values
            ('MedicalHeightValue', A.MedicalHeightValue),
            ('MedicalWeightValue', A.MedicalWeightValue)
        ) as V(Identifier, Value)
        for xml path('HealthAttribute'), type
    )
from table1 as A
for xml path('Assessment')

sql fiddle demo

于 2013-10-22T10:06:34.343 回答