Search code examples
sql-serverxmlsql-server-2008for-xml

Select the same element multiple times using forxml?


I found an example of using for xml to create xml here.

But in my case, I need to create xml that has multiple similar elements. Something like:

<params>
  <param>value1</param>
  <param>value2</param>
</param>

But if I try the following query:

SELECT (
  SELECT
'value1' AS [param],
'value2' AS [param]
FOR XML PATH('params'))

I end up with <params><param>value1value2</param></params> as my result. Not my desired output.

Any suggestions on how I could get the desired output?


Solution

  • -- An extra empty column in between
    select
      'value1' AS [param],
      '',
      'value2' AS [param]
    for xml path('params')
    
    -- A derived table by using union all
    select 'value1' union all
    select 'value2'
    for xml path('param'), root('params')
    
    -- Subqueries in the field list
    select
      (select 'value1' for xml path('param'), type),
      (select 'value2' for xml path('param'), type)
    for xml path('params')