Use of the FOR XML clause to retrieve query results as XML

SQL Anywhere allows you to execute a SQL query against your database and return the results as an XML document by using the FOR XML clause in your SELECT statement. The XML document is of type XML.

The FOR XML clause can be used in any SELECT statement, including subqueries, queries with a GROUP BY clause or aggregate functions, and view definitions.

SQL Anywhere does not generate a schema for XML documents generated by the FOR XML clause.

Within the FOR XML clause, you specify one of three XML modes that control the format of the XML that is generated:

  • RAW   represents each row that matches the query as an XML <row> element, and each column as an attribute.

  • AUTO   returns query results as nested XML elements. Each table referenced in the SELECT list is represented as an element in the XML. The order of nesting for the elements is based on the order of the columns in the SELECT list.

  • EXPLICIT   allows you to write queries that contain information about the expected nesting so you can control the form of the resulting XML.

The following sections describe the behavior of all three modes of the FOR XML clause regarding binary data, NULL values, and invalid XML names. The section also includes examples of how you can use the FOR XML clause.

 See also

FOR XML and binary data
FOR XML and NULL values
Encoding illegal XML names
FOR XML examples