Obtaining query results as XML

SQL Anywhere supports two different ways to obtain query results from your relational data as XML:

The FOR XML clause and the SQL/XML functions supported by SQL Anywhere give you two alternatives for generating XML from your relational data. In most cases, you can use either one to generate the same XML.

For example, this query uses FOR XML AUTO to generate XML:

SELECT ID, Name
FROM Products
WHERE Color='black'
FOR XML AUTO;

The following query uses the XMLELEMENT function to generate XML:

SELECT XMLELEMENT(NAME product,
          XMLATTRIBUTES(ID, Name))
FROM Products
WHERE Color='black';

Both queries generate the following XML (the result set has been formatted to make it easier to read):

<product ID="302" Name="Tee Shirt"/>
<product ID="400" Name="Baseball Cap"/>
<product ID="501" Name="Visor"/>
<product ID="700" Name="Shorts"/>
Tip

If you are generating deeply-nested documents, a FOR XML EXPLICIT query will likely be more efficient than a SQL/XML query because EXPLICIT mode queries normally use a UNION to generate nesting, while SQL/XML uses subqueries to generate the required nesting.


Using the FOR XML clause to retrieve query results as XML
Using FOR XML RAW
Using FOR XML AUTO
Using FOR XML EXPLICIT