Question

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?

Was it helpful?

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top