I am trying to generate some XML with different levels of nesting, and despite being overly simplified, the XML output will be format-free:
<invoice number="1"> <charge code="foo" rate="123.00"> <surcharge amount="10%" /> </charge> <charge code="bar" /> </invoice>
The database schema I inherited for this has a charge stored in different tables, which means that the surcharges are stored differently based on the table from which the charge was made.
Given that you cannot use UNION with FOR XML , I made several UNION ing in CTE, so something like:
WITH Charges ( [@code], [@rate], surcharge, InvoiceId ) AS ( SELECT code AS [@Code], amount AS [@rate], NULL as surcharge, InvoiceId FROM item.charges UNION ALL SELECT code AS [@Code], amount AS [@rate], ( SELECT amount AS [@amount] FROM order.surcharges os WHERE oc.ChargeId = os.ChargeId FOR XML PATH('surcharge'), TYPE ), InvoiceId FROM order.charges oc ) SELECT Number AS [@number], ( SELECT [@code], [@rate], surcharge FROM Charges WHERE Charges.InvoiceId = i.InvoiceId ) FROM Invoices i FOR XML PATH( 'invoice' ), TYPE
Now this is incredibly close, giving (note the nested <surcharge> ):
<invoice number="1"> <charge code="foo" rate="123.00"> <surcharge> <surcharge amount="10%" /> </surcharge> </charge> <charge code="bar" /> </invoice>
But I need to find a way to get the final query to include the value of the XML column, which will be considered as the content of the element, and not as a new element. Is this possible, or do I need to take a new approach?