How do you extract a value from an XML column using the value method?
Short answer
You call the value method on an XML column, providing an XPath expression identifying the specific element or attribute you want to extract along with the SQL data type you want the result converted to, letting you pull a single scalar value out of an XML document directly…
Advertisement
AModel answer
You call the value method on an XML column, providing an XPath expression identifying the specific element or attribute you want to extract along with the SQL data type you want the result converted to, letting you pull a single scalar value out of an XML document directly within a regular SQL query.
SELECT ProductId,
ProductDetails.value('(/product/name)[1]', 'VARCHAR(100)') AS ProductName
FROM ProductCatalog;Real-world example
A reporting query extracts just the product name from an XML column using the value method, treating that extracted value like any other regular column for the rest of the query.
Likely follow-ups
- Why does the XPath expression need square brackets around the element index?
- What happens if the specified XPath does not match anything in the XML document?
Related topics