Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server 2008 Shredding XML

Hi I have some XML like this...

<Questions>
  <Question1>A</Question1>
  <Question2>B</Question2>
  <Question3>C</Question3>
</Questions>

I would like to return A,B,C. I have seen some similar questions but those had the same repeating node name. Unfortunately at this stage I cant change it. I have played with the SQL Xpath syntax for AGES, with no luck. I can get the whole Questions Node, but Ideally I would like the Actual Data. Multiple returned rows would also be OK.

Any help would be greatly appreciated.

Update - Kirill's answer is very close, except that I have more than 1 record in the table and it is returning all records data within 1 row. If I could achieve a row/xml file that would be perfect !!! Either by outputing another field from that record e.g. rownum or outputting another piece of data from the file e.g. ProfileName..

thanks,

Adrian !

like image 268
Adrian Turner Avatar asked Mar 30 '26 00:03

Adrian Turner


2 Answers

declare @x xml = N'<Questions>
  <Question1>A</Question1>
  <Question2>B</Question2>
  <Question3>C</Question3>
</Questions>
'

SELECT x.value('.','varchar(10)')
FROM @x.nodes('/Questions/*') x(x)

Output

----------
A
B
C
like image 171
Martin Smith Avatar answered Apr 01 '26 11:04

Martin Smith


Continuing on Martin's solution and with some inspiration from this:

declare @x xml = N'<Questions>
  <Question1>A</Question1>
  <Question2>B</Question2>
  <Question3>C</Question3>
</Questions>
'

DECLARE @Questions VARCHAR(MAX)

SELECT @Questions = COALESCE(@Questions + ', ', '') + Question
FROM (
    SELECT x.value('.','varchar(10)') as Question
    FROM @x.nodes('/Questions/*') x(x)
) as y

SELECT @Questions

Output:

A, B, C
like image 28
dillenmeister Avatar answered Apr 01 '26 11:04

dillenmeister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!