ThunderDev
ThunderDev

Reputation: 1158

SQL FOR XML use values as column names

The FOR XML command uses column names to create the XML nodes. I need my nodes to be named after values I'm getting from the database. As far as I know you can't do something such as

SELECT Key AS Section

SECTION         | KEY                | VALUE
-----------------------------------------------------------
PageAddProduct  |   ErrorDateFormat  |  Incorrect value
PageAddProduct  |   ErrorNotSelected |  Please select value
WidgetLogin     |   Title            |  Connexion
WidgetLogin     |   MailLabel        |  Mail

This is the desired XML output

<Resources>
  <WidgetLogin>
    <Title>Connexion</Title>
    <MailLabel>Mail</MailLabel>
  </WidgetLogin>
</Resources>

Not sure if you can get this with For Xml. Help would be much appreciated.

Upvotes: 0

Views: 132

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 139010

You can build your XML as a string and then cast to XML.

This sample code will work in SQL Server 2012 since it is using the concat function but it can easily be rewritten to use + instead.

select cast(concat('<Resources>',
                   (
                   select concat('<',T1.SECTION,'>',
                                 (
                                 select concat('<',T2.[KEY],'>',
                                               (select T2.VALUE for xml path('')),
                                               '</',T2.[KEY],'>')
                                 from T as T2
                                 where T1.SECTION = T2.SECTION
                                 for xml path(''), type
                                 ).value('text()[1]', 'nvarchar(max)'),
                                 '</',T1.SECTION,'>')
                   from T as T1
                   group by T1.SECTION
                   for xml path(''), type
                   ).value('text()[1]', 'nvarchar(max)'),
                   '</Resources>') as xml)

SQL Fiddle

Upvotes: 1

Umesh
Umesh

Reputation: 2742

You can use FOR XML like below:

SELECT Section as Title, Value as MailLabel
FROM table
FOR XML PATH('WidgetLogin'), ROOT('Resources'), TYPE 

Upvotes: 0

Related Questions