Shred XML datatype to name/value pair

  • Hi all,

    Thanks for listening 🙂 I have a smallish problem. Given a table with a XML column containing xml fragments like this:

    <ModelData>

    <Vehicle>

    <Segment>C</Segment>

    <Brand>Y</Brand>

    <NewPrice>17328</NewPrice>

    <CurrentPrice>7725</CurrentPrice>

    <Fuel></Fuel>

    <Type>210</Type>

    <Age>4</Age>

    </Vehicle>

    <CollisionPoint>G</CollisionPoint>

    <RepairDuration>3</RepairDuration>

    <DamageCause>111</DamageCause>

    <HitDirection>I</HitDirection>

    </ModelData>

    I need a qeury returning a resultset like:

    name value

    -------- ------

    Segment C

    Brand Y

    ........ ....

    HitDirection I

    I've tried OPENROWSET and that looks promising, but I can't get the exact result.

    Anyone care to help and/or point in the richt direction?

    Thanks,

    -Edoode

  • Something like this

    declare @x xml

    set @x='

    ... your xml

    '

    select r.value('local-name(.)','varchar(20)') as name,

    r.value('./text()[1]','varchar(20)') as value

    from @x.nodes('//*') as x(r)

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537
  • Superduper! Exactly what I needed.

    Points+1 🙂

    -Edoode

  • If I could bother you (all) again, what would be the xquery required to transform this XML fragment

    <ArrayOfNameValuePair>

    <NameValuePair>

    <Name>totalCostDep</Name>

    <Value>2357.81055</Value>

    </NameValuePair>

    <NameValuePair>

    <Name>totalCost</Name>

    <Value>1608.08594</Value>

    </NameValuePair>

    </ArrayOfNameValuePair>

    into this..

    name value

    totalCostDep 2357.81055

    totalCost 1608.08594

    Thanks!!

    -Edoode

  • select r.value('Name[1]','varchar(20)') as name,

    r.value('Value[1]','decimal(12,6)') as value

    from @x.nodes('/ArrayOfNameValuePair/NameValuePair') as x(r)

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply