0

I have this query:

DECLARE @XML XML = 
'<det nItem="1">
    <prod>
        <cProd>222</cProd>
    </prod>
</det>
<det nItem="2">
    <prod>
        <cProd>888</cProd>
    </prod>
</det>'

SELECT
    det.value('@nItem', 'varchar(max)') as nItem,
    det_prod.value('(cProd)[1]', 'varchar(max)') as cProd
FROM
    @XML.nodes('/det') AS det(det),
    @XML.nodes('/det/prod') AS det_prod(det_prod)

It returns this result set:

nItem   cProd
-------------
   1    222
   1    888
   2    222
   2    888

but I want this returned like this:

 nItem  cProd
 -------------
   1    222
   2    888

Is there a way to do it without parse each <det> as a single xml?

2 Answers 2

1

You are CROSS JOINing the nodes. Instead use CROSS APPLY to join each det node to its related prod nodes. EG:

DECLARE @XML XML = 
'<det nItem="1">
    <prod>
        <cProd>222</cProd>
    </prod>
</det>
<det nItem="2">
    <prod>
        <cProd>888</cProd>
    </prod>
</det>'

SELECT
    det.value('@nItem', 'varchar(max)') as nItem,
    det_prod.value('(cProd)[1]', 'varchar(max)') as cProd

FROM
    @XML.nodes('/det') AS det(det)
CROSS APPLY
    det.det.nodes('prod') AS det_prod(det_prod)
Sign up to request clarification or add additional context in comments.

Comments

1

You are doing cross join you need

SELECT
    det.value('@nItem', 'varchar(max)') as nItem,
    det.value('.', 'varchar(max)') as cProd
FROM
    @XML.nodes('/det') AS det(det);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.