Annoying problem with XQuery

  • Hi,

    I have following xml document:

    <Root>

    <Header>

    <SomeTag1></SomeTag1>

    <SomeTag2></SomeTag2>

    </Header>

    <Data>

    <Item ID="1" AdditionalInfo="Some info">

    <SubItem ID="1">1</SubItem>

    <SubItem ID="2">2</SubItem>

    <SubItem ID="3">3</SubItem>

    </Item>

    <Item ID="2" AdditionalInfo="Some info">

    <SubItem ID="1">1</SubItem>

    <SubItem ID="2">2</SubItem>

    </Item>

    </Data>

    </Root>

    I need to extra each SubItem from the xml document into the following table:

    Data (

    SubItemId sometype,

    SubItemValue sometype,

    ItemId sometype,

    AdditionalInfo somety),

    where 'ItemId' and 'AdditionalInfo' are parent's values and 'SubItemValue' is text value of 'SubItem' tag.

    How to solve this problem in the most efficient way ?

    Thanks in advance,

    Zoran

  • Something like this (assuming you're using SS2K5 or above)?

    DECLARE @xml XML

    SELECT @xml='<Root>

    <Data>

    <Item ID="1" AdditionalInfo="Some info">

    <SubItem ID="1">1</SubItem>

    <SubItem ID="2">2</SubItem>

    <SubItem ID="3">3</SubItem>

    </Item>

    <Item ID="2" AdditionalInfo="Some info">

    <SubItem ID="1">1</SubItem>

    <SubItem ID="2">2</SubItem>

    </Item>

    </Data>

    </Root>'

    SELECT

    y.value('@ID[1]','INT') AS SubItemId,

    y.value('.','INT') AS SubItemValue,

    c.value('@ID[1]','INT') AS ItemId,

    c.value('@AdditionalInfo[1]','varchar(30)') AS AdditionalInfo

    FROM @xml.nodes('Root/Data/Item') T(c)

    CROSS APPLY

    c.nodes('SubItem') X(y)



    Lutz
    A pessimist is an optimist with experience.

    How to get fast answers to your question[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]

  • Thanks for your post Lutz.

    It solved my problem.

    Bye.:-)

Viewing 3 posts - 1 through 2 (of 2 total)

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