0

How to create XML in below format from SQL Query in SQL Server?

<ROOT><ELEMENT>VALUE1</ELEMENT></ROOT>
<ROOT><ELEMENT>VALUE2</ELEMENT></ROOT>
<ROOT><ELEMENT>VALUE3</ELEMENT></ROOT>
2
  • Show your query and result Commented Jan 20, 2017 at 14:37
  • The root-node is the one (and only!) outer-most element. There is no rule that it must be named <root>, nor is there a rule, that nodes within the XML should not be named as such. But it is - at least - very unusual... The multiple <ROOT> nodes could mean, that you need several independant XMLs... If the existing answers do not solve your issue, please poste some sample data and the expected output, together with some details about your goal. And - last but not least - show what you've tried already... Commented Jan 20, 2017 at 20:35

2 Answers 2

1
 SELECT t.value AS ELEMENT          
     FROM [dbo].tbl t
     FOR XML PATH ('ROOT');
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it something like:

select T.Element as 'Element'
from 
(
    select 'VALUE1' as Element
    union all 
    select 'VALUE2'
    union all 
    select 'VALUE3'
) as T
for xml path('ROOT')

See MSDN for more information.

3 Comments

Derived table is not necessary
@Prdp well, it is just "ready-to-use" snippet and subquery is just emulation of source table.
got the solution SELECT ROW.ELEMENT AS ELEMENT FROM table_name ROW FOR XML AUTO,elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.