1

I have a table Table with one column ID. It contains simple letters, let's say Table = 'A', 'B', 'C'.

I need to create an xml file which looks like this

<Table>
  <ID>A</ID>
  <ID>B</ID>
  <ID>C</ID>
</Table>

So I tried

select * from Table for XML AUTO, ELEMENTS

But this yields

<Table>
  <ID>A</ID>
</Table>
<Table>
  <ID>B</ID>
</Table>
<Table>
  <ID>B</ID>
</Table>

So as far as I understand, the inner node collection represents one single record of a table (in this case, consisting of a single field/node) and the surrounding tag indicates the record itself. But this is not what I would prefer to see.

My (quite dirty) solution converts the xml into a string, removes the

</Table><Table>

pairs and then reconstructs the XML

declare @x nvarchar(max)
set @x = (select id from Table for xml auto, elements)
set @x = replace(@x, '</Table><Table>', '')
select cast(@x as xml)

My questions is simple: Is there a correct way to achieve my goal or do I have to live with this ugly 'solution'?

2 Answers 2

3

I think you want to avoid using AUTO if you want a specific output format and use PATH instead. Not tested but how about this:

SELECT * 
FROM Table 
FOR XML PATH('ID'), ROOT('Table')
Sign up to request clarification or add additional context in comments.

2 Comments

Almost, but not quite right. It creates <Table><ID><ID>A</ID></ID><ID>... so an additional inner node '<ID>':-(
So, I got it! "select * from Table for XML Path(''), Root('Table')" Does the trick!
1

@Dave Sexton gave me the right kick:

The solution to the above is as follows:

select ID 
  from Table 
   for XML Path(''), Root('Table')

Comments

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.