0

With a SQL Server database, I try to write a query which looks like -

SELECT DATE, ID, NAME
FROM TEST_TBL 
FOR XML ??

but I'm not sure which XML option (RAW, EXPLICIT, PATH, AUTO) can be used in the query to have an XML output like this:

<resultset>
    <row>
        <column name="DATE">01/01/2016</column>
        <column name="ID">A01</column>
        <column name="NAME">JOHN DOE</column>
    </row>
    <row>
        <column name="DATE">01/02/2016</column>
        <column name="ID">A02</column>
        <column name="NAME">MARY DOE</column>
    </row>
</resultset>

2 Answers 2

2

Please try this:

SELECT 
'DATE' as 'column/@name', [DATE] as 'column', null, 
'ID' as 'column/@name', [ID] as 'column', null, 
'NAME' as 'column/@name', [NAME] as 'column', null
FROM TEST_TBL
FOR XML PATH('row'), ROOT('resultset')
Sign up to request clarification or add additional context in comments.

9 Comments

Good answer, +1 from my side, but you'd want to use 'DATE' instead of 'col1' and so on... Don't you?
very close, but the field names are not shown at the XML output - <column name="01/01/2016">01/01/2016</column> <column name="A01">A01</column> <column name="JOHN DOE">JOHN DOE</column>
@coconuts, Do not place the column twice... At the beginning of the line replace the 'col1' with 'DATE' . Don't forget the quotes there...
@Shungo, many thanks for the reminder. It works most of time, but if the value is NULL, the output of the XML file becomes <column name="ID"/> instead of <column name="ID"></column>
@coconuts, You can use CASE WHEN to check whether the value is NULL, then set the value you want
|
0

Try this query

declare @XML xml

    set @XML = 

  '<resultset>
    <row>
        <column name="DATE">01/01/2016</column>
        <column name="ID">A01</column>
        <column name="NAME">JOHN DOE</column>
    </row>
    <row>
        <column name="DATE">01/02/2016</column>
        <column name="ID">A02</column>
        <column name="NAME">MARY DOE</column>
    </row>
</resultset>'

    select 
    T.N.value('column[1]', 'varchar(max)') as Date,
    T.N.value('column[2]', 'varchar(max)') as ID,
    T.N.value('column[3]', 'varchar(max)') as Name
    from @XML.nodes('/resultset/row') as T(N)

Result:

enter image description here

1 Comment

Thank you very much for your help. Please pardon me actually what I'm seeking for is the opposite - a SQL server query by using 'FOR XML' options to output an XML file just like the one shown above.

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.