// strings reference

SQL FOR XML clause

SELECT id, total FROM orders FOR XML PATH('order'), ROOT('orders') returns <orders><order><id>1</id><total>5</total></order>...</orders>.

类别
Strings
Returns
XML
In this category
166 of 172

语法

SELECT ... FOR XML [RAW | AUTO | EXPLICIT | PATH('name')] [, ROOT('name')]

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL Different name or syntax xmlelement / xmlattributes / xmlagg functions
MySQL Not built in no XML generation
SQLite Not built in no XML generation
Oracle Different name or syntax XMLElement, XMLForest, XMLAgg

示例

SQL Server

SELECT id, total
FROM orders
FOR XML PATH('order'), ROOT('orders');

SQL Server

SELECT id AS '@id', total AS '*'
FROM orders FOR XML PATH;

PostgreSQL

SELECT xmlelement(name order,
  xmlattributes(id AS id), total) AS doc
FROM orders;

值得了解

  • PATH mode shapes output through column aliases: '@id' becomes an attribute, '*' becomes the element's text, 'customer/name' nests elements. A nested FOR XML PATH subquery needs , TYPE to stay XML instead of escaped text.
  • The pre-2017 string-aggregation idiom, STUFF((SELECT ',' + name ... FOR XML PATH('')), 1, 1, ''), escapes & and < unless you add , TYPE and read .value('.', 'nvarchar(max)'). On SQL Server 2017+ use STRING_AGG.
  • Oracle composes with XMLElement, XMLForest and XMLAgg; PostgreSQL has the lowercase xmlelement/xmlattributes/xmlagg set. Function-style on both, not a clause.

Questions about FOR XML

How do I get JSON instead?

FOR JSON PATH on SQL Server, JSON_ARRAYAGG with JSON_OBJECT on MySQL and Oracle, json_agg with json_build_object on PostgreSQL, json_group_array with json_object on SQLite.

Why is my FOR XML output truncated?

SSMS truncates the display of xml results; the data is intact. Click the XML cell to open the full document, or cast the result to nvarchar(max).

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.