SQL XML scalar extraction
doc.value('(/order/total)[1]', 'decimal(10,2)') pulls one typed scalar out of XML. The .value side of SQL Server's pair, and its Oracle equivalent.
- 类别
- Strings
- Returns
scalar- In this category
- 165 of 172
语法
column.value('xpath', 'sql_type') -- SQL Server
XMLCAST(XMLQUERY(...) AS type) -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | the .value() method over xml columns |
| PostgreSQL | Different name or syntax | xpath() then subscript and cast |
| MySQL | Different name or syntax | ExtractValue(xml_text, xpath) returns the text |
| SQLite | Not built in | no XML support |
| Oracle | Different name or syntax | XMLCAST + XMLQUERY; EXTRACTVALUE is deprecated |
示例
SQL Server
SELECT doc.value('(/order/total)[1]', 'decimal(10,2)') AS total
FROM orders_xml;
Oracle
SELECT XMLCAST(XMLQUERY('/order/total/text()'
PASSING doc RETURNING CONTENT) AS NUMBER) AS total
FROM orders_xml;
MySQL
SELECT ExtractValue(doc_text, '/order/total') AS total FROM orders_xml;
值得了解
- SQL Server's .value() needs a path that is a singleton at compile time, so '/order/total' fails with "'value()' requires a singleton" even when only one node exists. Write '(/order/total)[1]'.
- .value() must cast to a SQL type ('decimal(10,2)', 'nvarchar(max)'); .query() returns XML instead: the method pair splits scalars from fragments.
- EXTRACTVALUE is Oracle's deprecated predecessor: prefer XMLCAST(XMLQUERY(...)) in new code, or migrate the column to JSON if you control the format.
Questions about .value() / XMLCAST
.query() or .value()?
.value() for one scalar, typed, with the mandatory [1] subscript; .query() for XML fragments. They pair like JSON_VALUE and JSON_QUERY.
Why does .value() say it requires a singleton?
SQL Server checks the path's type before running it, and '/a/b' could match many nodes. Parenthesise and subscript, '(/a/b)[1]', to promise a single node.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
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.