FOR XML
09/03/2025 A query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifyi
A
query returns results as a rowset. You can optionally retrieve formal results of a SQL
query as XML by specifying the
clause in the query. The
clause can be used in
top-level queries and in subqueries. The top-level
clause can be used only in the
statement. In subqueries,
can be used in the
,
, and
statements.
can also be used in assignment statements.
In a
clause, you specify one of these modes:
The
mode generates a single
element per row in the rowset that is returned by the
statement. You can generate XML hierarchy by writing nested
queries.
The
mode generates nesting in the resulting XML by using heuristics based on the way
the
statement is specified. You have minimal control over the shape of the XML
generated. The nested
queries can be written to generate XML hierarchy beyond the
XML shape that is generated by
mode heuristics.
The
mode allows more control over the shape of the XML. You can mix attributes and
elements at will in deciding the shape of the XML. It requires a specific format for the resulting
rowset that is generated because of query execution. This rowset format is then mapped into
XML shape. The power of
mode is to mix attributes and elements at will, create
wrappers and nested complex properties, create space-separated values (for example, the
attribute might have a list of order ID values), and mixed contents.
However, writing
mode queries can be cumbersome. You can use some of the new
capabilities, such as writing nested
,
, or
mode queries and the
directive, instead of using
mode to generate the hierarchies. The nested
queries can produce any XML that you can generate by using the
mode. For
more information, see
Use nested FOR XML queries
and
TYPE directive in FOR XML queries.
The
mode together with the nested
query capability provides the flexibility of
the
mode in a simpler manner.
SELECT
FOR XML
FOR XML
FOR XML
SELECT
FOR XML
INSERT
UPDATE
DELETE
FOR XML
FOR XML
RAW
AUTO
EXPLICIT
PATH
RAW
<row>
SELECT
FOR XML
AUTO
SELECT
FOR XML
AUTO
EXPLICIT
EXPLICIT
OrderID
EXPLICIT
FOR XML
FOR XML RAW
AUTO
PATH
TYPE
EXPLICIT
FOR
XML
EXPLICIT
PATH
FOR XML
EXPLICIT