Search code examples
sql-serversql-server-2016

How to export formatted XML output by using SQL Server


I try to do formatted XML output using SQL Server 2016.

This is my code:

SELECT *
FROM [GRADUATE]
FOR XML PATH('applicant'), ROOT('applicantsuniversity'), ELEMENTS XSINIL;

The output is

enter image description here

The output I have to submit needs to look like this:

enter image description here

Question #1: how can I put this line to show in my code?

enter image description here

Question #2: how to treat null values?

How can I adapt my code to show an output like this:

enter image description here

not like this:

enter image description here

Thanks for the help.


Solution

  • You need put the whole thing in a subquery and create the root element manually.

    Use the , TYPE option to embed XML within other XML queries. The subquery should not have a column name, or you will get a second level of nesting.

    Use @ in the column name to specify an attribute.

    Remove the , ELEMENTS XSINIL to get rid of xsi:nil attributes. If you actually want to show empty elemnts then you can do ISNULL(maidenName, '')

    SELECT
      [@university] = '123456',
      (
        SELECT g.*
        FROM GRADUATE g
        FOR XML PATH('applicant'), TYPE
      )
    FOR XML PATH('applicants');
    

    If you actually need to get that university attribute from the data then you need some kind of aggregation. STRING_AGG would make sense if you have it in your version, but you do need to cast it back to XML afterwards.

    SELECT
      [@university] = g.university,
      CAST(g.xmlData AS xml)
    FROM (
        SELECT
          g.university,
          xmlData = STRING_AGG(x.xmlData, '')
        FROM GRADUATE g
        CROSS APPLY
        (
            SELECT g.*
            FOR XML PATH('applicant')
        ) x(xmlData)
    ) g
    FOR XML PATH('applicants');