T-SQL Tutorial

SQL Server XML value()


The SQL Server XML value() method is a powerful XML function that allows you to extract a specific value from an XML document. This method returns a single scalar value of a specified data type from an XML instance.


Syntax

The syntax for using value() is as follows:

xml_data.value('XQuery Expression', 'Data Type')

Here, xml_data is the XML column or variable from which you want to extract a value. The XQuery Expression parameter is an XPath expression that specifies the location of the value you want to extract. The Data Type parameter is the data type you want to convert the extracted value to.


Example

For example, suppose you have an XML column called my_xml in a table called MyTable. The my_xml column contains the following XML:

CREATE TABLE MyTable(
id INT,
my_xml XML
);

INSERT INTO MyTable (id, my_xml)
VALUES (1, '<employees>
<employee>
<name>John Smith</name>
<title>Software Engineer</title>
<salary>100000</salary>
</employee>
<mployee>
<name>Jane Doe</name>
<title>Project Manager</title>
<salary>120000</salary>
</employee>
</employees>');

You can use the value() method to extract the salary of the first employee by running the following query:

SELECT my_xml.value('(employees/employee[1]/salary)[1]', 'INT') AS my_column
FROM MyTable;

This query will return 100000 as the value of the first employee's salary.

Note that the value() method only returns a single value. If you want to extract multiple values, you need to use the nodes() method to shred the XML into rows and then use value() to extract each value separately.