Reputation: 45
I wish to generate xml data in the following format - animal value must be tag name
<pets>
<dog>
<name>spot</name>
</dog>
<cat>
<name>tom</name>
</cat>
</pets>
I can write some dynamic sql but if there is a better way????
;with cte(animal,name)
as
(
select 'dog','spot' union
select 'cat','tom'
)
select
animal
,name
from cte
for xml path(animal),root('pets')
Upvotes: 0
Views: 44
Reputation: 3560
Use the next code:-
SELECT (
SELECT 'spot' AS name
FOR
XML PATH('dog'),
TYPE
),
( SELECT 'tom' AS name
FOR
XML PATH('cat'),
TYPE
)
FOR XML PATH(''),
ROOT('Pets')
GO
Result:-
<Pets>
<dog>
<name>spot</name>
</dog>
<cat>
<name>tom</name>
</cat>
</Pets>
Upvotes: 1