I'd like to generate the following output using SQL Server 2012:
<parent>
<item>1</item>
<item>2</item>
<item>3</item>
</parent>
From three different columns in the same table (we'll call them col1, col2, and col3).
I'm trying to use this query:
SELECT
t.col1 as 'item'
,t.col2 as 'item'
,t.col3 as 'item'
FROM tbl t
FOR XML PATH('parent'), TYPE
But what I get is this:
<parent>
<item>123</item>
</parent>
What am I doing wrong here?
A couple notes here: If you use FOR XML EXPLICIT, you can't use WITH XMLNAMESPACES (a requirement I didn't mention, so I'm still leaving the accepted answer). While Iheria's answer was also very helpful, there's another simpler possibility I've since realized:
I think this is probably the easiest and most performant way (I haven't benchmarked it, but I can't imagine using
UNPIVOT
would be faster and, if anything, the multipleSELECT
option likely is refactored to this by the engine anyway).There are actually a few ways to solve this with the XML Path syntax.
The first is to UNPIVOT your results first, for example:
The 2nd doesn't require the unpivot, but repeats more of your query:
Both of these will combine multiple rows of data all under the same parent node. For example, if you have 2 rows, the first with 1,2,3 and the second 4,5,6, you'd get:
If, instead, you want each row you unpivot to have a unique parent element per row, then, assuming you have some row identifier on each row (I'll call it parentId), you can group these by that row by tweaking these approaches:
or
Which would result in:
Sql Fiddle with demo
I think if you change the alias of the columns like this it should work. This is because the aliases are same and may be the data type of data is same as well. In case if you have different data in col1, col2 and col3, it shouldn't be showing this behaviour.
Ok, you can't use path for that. Use explicit, instead,
Add a column with NULL as value to generate a separate item node for each column.
Result:
SQL Fiddle
Why does this work?
Columns without a name are inserted as text nodes. In this case the NULL value is inserted as a text node between the
item
nodes.If you add actual values instead of NULL you will see what is happening.
Result:
Another way to specify a column without a name is to use the wildcard character
*
as a column alias.Columns with a Name Specified as a Wildcard Character
It is not necessary to use the wildcard in this case because the columns with NULL values don't have a column name but it is useful when you want values from actual columns but you don't want the column name to be a node name.