简体   繁体   中英

XML tag formation using sql query

My Xml Looks like this:

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

are all columns from a table.

<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 should alone be placed in between HealthAttribute tags which is completed using the following query:

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

Now I want the following columns alone in Assessment tag

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

Any help please?

New XML should look like this:

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

First of all, it's REALLY hard to understand what do you want to get. I think I've figured this out from your question and your pervious question (which, BTW, still don't have an accepted answer).

Here's query you need:

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

you can also do it like this, to have more control over names:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM