In SQL 2005, is there a way to convert the following xml into a table?
<root>
<r>
<data>"col1"</data>
<data>"col2"</data>
<data>"col3"</data>
</r>
<r>
<data>"data1"</data>
<data>""</data>
<data>"data3"</data>
</r>
<r>
<data>"data"</data>
<data>"data"</data>
<data>"data"</data>
</r>
</root>
I want the output to be
col1 col2 col3
----------------
data data3
data data data
The xml can have different number of columns so the solution needs to account for this.
Thanks in advance.
Since I use dynamic SQL here it is appropriate to suggest reading The Curse and Blessings of Dynamic SQL.
An explanation of what is going on.
This query is used to get the columns names from the first
rnode:/root/r[1]makes sure we get the first row.row_number()enumerates the columns making a connection between a number and the column name.The resulting query in @SQL is this:
/root/r[position()>1]gets allrnodes except the first one. The1indata[1]comes fromrow_number()and[col1]comes from the corresponding column name.quotename()adds the brackets[]to the column alias. Withoutquotename()this query could be used for SQL injection.replace()is used to remove"from the string. It will remove all occurrences of"so if you expect"to be part of a value you could usesubstring()to remove"instead.I have used
varchar(10)as the size of column data. You should modify that to whatever you need.