T-SQL Tutorial

SQL Server XML nodes()

The SQL Server XML nodes() method is a powerful feature that allows you to extract XML data stored in a SQL Server database. With this method, you can perform a variety of operations on XML data, such as selecting, filtering, and sorting nodes.

The nodes() method works by using the XQuery language to navigate and extract XML data. XQuery is a query language designed specifically for XML data, and it provides a rich set of functions and operators for working with XML.

The nodes() method takes an XQuery expression as its argument, which specifies the nodes to be selected. The XQuery expression can include a variety of functions and operators, such as descendant, attribute, and namespace, as well as more advanced operations like union and intersect.


For example, suppose you have an XML document stored in a SQL Server database that represents a list of employees. Each employee is represented by an <employee> element, which has child elements for the name, title, and department:

<employee id="100">
<name>John Doe</name>
<employee id="101">
<name>Jane Smith</name>

To extract the names of all employees in the list, you could use the following nodes() method:

SELECT EmployeeData.Employee.query('name').value('.', 'varchar(100)') as EmployeeName
FROM Employees
CROSS APPLY EmployeeData.nodes('/employees/employee') as EmployeeData(Employee)

This expression uses the nodes() method to select all <employee> elements in the document, and then uses the query() function to select the <name> element for each employee. The value() function is then used to extract the text value of the <name> element as a string.

The nodes() method is a powerful tool for working with XML data in SQL Server, and it can be used in a variety of scenarios, from simple extractions to complex data transformations. With its support for XQuery, you can take advantage of a rich set of functions and operators to create powerful and flexible XML data selections.