sql-serverxmlt-sqlxpathfor-xml

How to break up two xml tags with the same subchild names in SQL


I have created a script which takes data from a table in SQL and generates an XML output. The parent, child and sub-child tags are all the same which for 2 tags. The SQL script is outputting them as one XML value instead of 2.

 SELECT
 Request.TransactionRef AS [RequestHeader/RequestID],
'Deal.Trial' AS [RequestHeader/Action],
'DoDealValidate' AS [RequestHeader/ActionFlags/Flag],
'DoDealDerive' AS [RequestHeader/ActionFlags/Flag] 

The current results are:

<ActionFlags>
<Flag>DoDealValidateDoDealDerive</Flag>
</ActionFlags>




<ActionFlags>
<Flag>DoDealValidate</Flag>
<Flag>DoDealDerive</Flag>
</ActionFlags>

Solution

  • Just place something empty in between:

    SELECT
     'blah' AS [RequestHeader/RequestID],
    'Deal.Trial' AS [RequestHeader/Action],
    'DoDealValidate' AS [RequestHeader/ActionFlags/Flag],
    NULL AS [RequestHeader/ActionFlags],
    'DoDealDerive' AS [RequestHeader/ActionFlags/Flag] 
    FOR XML PATH('row');
    

    The background:

    The engine is running through the SELECT's columns and builds them one after the other.

    In your code the <Flag> is still open, therefore the content is written into the open element.

    My change will let the engine think