Advertisement
Intermediate SQL Server, XML Data Type & Querying

How do you convert the results of a SQL query directly into an XML formatted document using the FOR XML clause?

Short answer

You add the FOR XML clause to the end of a SELECT statement, choosing a mode such as RAW, AUTO, or PATH, each producing a different structure and level of control over the resulting XML output, which is useful for generating XML documents directly from relational data for…

Save SQL Server mock interview
Advertisement
AModel answer
You add the FOR XML clause to the end of a SELECT statement, choosing a mode such as RAW, AUTO, or PATH, each producing a different structure and level of control over the resulting XML output, which is useful for generating XML documents directly from relational data for purposes like data exchange with another system.
SELECT OrderId, CustomerName, Amount
FROM Orders
FOR XML PATH('Order'), ROOT('Orders');
Real-world example
An integration process generates a properly formatted XML document representing a batch of orders directly from a SQL query using FOR XML PATH, ready to be sent to an external partner system that expects data in XML format.
Likely follow-ups
  • What is the difference between the RAW, AUTO, and PATH modes in FOR XML?
  • How do you control the specific element and attribute names in the generated XML?
Related topics