1

I have been trying (with no success yet) to produce the following XML output

<table>
    <row>
        <column name="column_name">[value]</column>
        <column name="column_name">[value]</column>
    </row>
    <row>
        <column name="column_name">[value]</column>
        <column name="column_name">[value]</column>
    </row>
</table>

Can anyone suggest a route that will allow me to achieve this output?

Thank you in advance for any help you can provide.

2
  • 3
    Just google "SQL SERVER SELECT FOR XML". There's tons of stuff on this including tutorials and many answers on this site. If you have a specific question, please let us know. Commented Nov 11, 2015 at 22:44
  • Could you give some examples of SQL statements you've tried so far? StackOverflow is best when you have a specific question or issue that you are trying to resolve based on the effort you've put in so far. Commented Nov 12, 2015 at 1:05

1 Answer 1

1

Don't know if this is still of interest, but the code was this:

(The trick is the "empty node" between the two column declarations...)

DECLARE @tbl TABLE(col1 INT, col2 VARCHAR(100));
INSERT INTO @tbl VALUES(1,'test1'),(2,'test2');

SELECT 'col1' AS [column/@name]
      ,col1 AS [column]

      ,'' --this is needed to allow the same name twice...

      ,'col2' AS [column/@name]
      ,col2 AS [column]
FROM @tbl
FOR XML PATH('row'),ROOT('table');

/*
<table>
  <row>
    <column name="col1">1</column>
    <column name="col2">test1</column>
  </row>
  <row>
    <column name="col1">2</column>
    <column name="col2">test2</column>
  </row>
</table>
*/
Sign up to request clarification or add additional context in comments.

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.