Let’s say we have the following XML:
<root>
<row>
<column>row 1 col 1</column>
<column>row 1 col 2</column>
<column>row 1 col 3</column>
</row>
<row>
<column>row 2 col 1</column>
<column>row 2 col 2</column>
<column>row 2 col 3</column>
</row>
<row>
<column>row 3 col 1</column>
<column>row 3 col 2</column>
<column>row 3 col 3</column>
</row>
</root>
How do I transpose this, using T-SQL XQuery to:
<root>
<column>
<row>row 1 col 1</row>
<row>row 2 col 1</row>
<row>row 3 col 1</row>
</column>
<column>
<row>row 1 col 2</row>
<row>row 2 col 2</row>
<row>row 3 col 2</row>
</column>
<column>
<row>row 1 col 3</row>
<row>row 2 col 3</row>
<row>row 3 col 3</row>
</column>
</root>
I suspect there might be a really nice approach using
PIVOT, but I don’t know it well enough to be able to say for sure. What I offer here works. I have split it up into chunks for better formatting and to provide commentary:To start with let’s capture the example data
Now the actual transposing code:
Establish the size of the matrix:
Shred the data, use
ROW_NUMBERto capture the index (the-1is to make it zero based), and use modulo and integer divide on the index to work out the new row and column numbers:With this CTE
FlattenedInputavailable, all we now need to do is get theFOR XMLoptions and query structure right and we’re done:Sample output:
Works on any size ‘square’ data. Note the lack of sanity checking / error handling.