Question

I've an XML like following

Declare @BathData XML
SET @BathData='<Batch>
<Customers>
<Customer>
    <CustomerId>1</CustomerId>
    <Product>
        <ProductId>10</ProductId>
        <ProductId>11</ProductId>
    </Product>
</Customer>
<Customer>
        <CustomerId>2</CustomerId>
        <Product>
            <ProductId>22</ProductId>
            <ProductId>23</ProductId>
            <ProductId>25</ProductId>
        </Product>
</Customer>

 </Customers>
 </Batch>'

the result i want is as following

CusomerId ProductId
1           10
1           11
2           20
2           23
2           35

and i am using following way to sort it out

 SELECT Finaldata.R.value('CustomerId[1]','int')            
 CustomerId,Finaldata.R.value('Product[1]','int') as ProductId
 FROM @BathData.nodes('//Batch/Customers/Customer') as Finaldata (R)

but obviously its not working a quick response would really help thanks

Was it helpful?

Solution

Iterate over the ProductIds. You can fetch the customer from two levels up (../../CustomerId):

SELECT  Finaldata.R.value('(../../CustomerId)[1]','int') as CustomerId
,       Finaldata.R.value('(.)[1]','int') as ProductId
FROM    @BathData.nodes('/Batch/Customers/Customer/Product/ProductId') 
             as Finaldata (R)

Dot . works as a reference to the current node.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top