I am trying to create an xml output in SQL 2008 using FOR XML Path. This is working fine:
<Taxonomy>
<Category Level="1">Clothing</Category>
<SubCategory Level="2">Jeans</SubCategory>
</Taxonomy>
But I would like the output to be:
<Taxonomy>
<Category Level="1">Clothing</Category>
<Category Level="2">Jeans</Category>
</Taxonomy>
Of course you can code as following:
1 as 'Taxonomy/Category/@Level',
2 as 'Taxonomy/Category/@Level',
t.MainCat as 'Taxonomy/Category',
t.SubCat as 'Taxonomy/Category',
But this gives an error message: Attribute-centric column 'Column name is repeated. The same attribute cannot be generated more than once on the same XML tag.
What can be done to get the desired output? Would a subselect work or some kind of cross apply? Or perhaps a union? But how?
---- EDIT - after several answers came up with following solution:
SELECT
1 as 'Category/@Level',
t.Cat as 'Category'
FROM table t
UNION
SELECT
2 as 'Category/@Level',
t.SubCat as 'Category'
FROM table t
FOR XML PATH (''), ROOT('Taxonomy')
gives this output:
<Taxonomy>
<Category Level="1">Clothing</Category>
<Category Level="2">Jeans</Category>
</Taxonomy>
Still have to figure out how to put this partial coding in a much larger code with several 'nested' FOR XML's already