Convert XML to Table data
<Resp ID="1199" WID="425">
  <Qtn ID="1" Crt="0" Scr="0">
    <Value>Orange</Value>
    <Value>Yuzu</Value>
  </Qtn>
  <Qutn ID="2" Crt="1" Scr="1">
    <Value>Soy Milk</Value>
  </Qtn>
</Resp>

I have the above xml. What i need to do is, Converting this data to table format. Basically i need to create a view, which represents the xml data in table format. The XML is well defined format. I need to get these in the following format given below.

Resp ID WID Qtn ID Value Scr Crt
1199 425 1 Orange 0 0
1199 425 1 Yuzu 0 0
1199 425 2 Soy Milk 1 1

I need a select query to get results like the above.

Thank you.

September 12th, 2015 7:25am


DECLARE @x xml =
'<Resp ID="1199" WID="425">
  <Qtn ID="1" Crt="0" Scr="0">
    <Value>Orange</Value>
    <Value>Yuzu</Value>
  </Qtn>
  <Qtn ID="2" Crt="1" Scr="1">
    <Value>Soy Milk</Value>
  </Qtn>
</Resp>'

SELECT R.r.value('@ID', 'int') AS [Resp ID],
       R.r.value('@WID', 'int') AS WID,
       Q.q.value('@ID', 'int') AS [Qtn ID],
       V.v.value('(./text())[1]', 'nvarchar(20)') AS Value,
       Q.q.value('@Crt', 'tinyint') AS Crt,
       Q.q.value('@Scr', 'tinyint') AS Scr
FROM   @x.nodes('/Resp') AS R(r)
CROSS APPLY R.r.nodes('Qtn') AS Q(q)
CROSS APPLY Q.q.nodes('Value') AS V(v)

Free Windows Admin Tool Kit Click here and download it now
September 12th, 2015 11:28am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics