T-SQL Tutorial

SQL Server XML query()


SQL Server XML query() method is a powerful tool used for extracting data from XML documents stored within a SQL Server database. This method is part of the XML data type in SQL Server, which enables developers to work with XML data in a native way within the database.

The query() method is used to extract a subset of an XML document based on a specific XPath expression. The XPath expression is passed as an argument to the query() method, and the result of the expression is returned as an XML data type. The query() method can be used in both SELECT and UPDATE statements.


Example

Here's an example of how to use the query() method in a SELECT statement:

SELECT Col1, Col2,
XMLCol.query('/Root/Node[@Attr="Value"]') AS ExtractedXML
FROM MyTable;

In this example, Col1 and Col2 are regular columns in the MyTable table, while XMLCol is an XML column. The query() method is used to extract a subset of the XML data stored in the XMLCol column, based on the XPath expression '/Root/Node[@Attr="Value"]'. The result of the query() method is returned as an XML data type in the ExtractedXML column.


The query() method can also be used in an UPDATE statement to modify XML data within an XML column:

UPDATE MyTable
SET
XMLCol.modify('replace value of (/Root/Node[@Attr="Value"]/text())[1] with "NewValue"')
WHERE ID = 1;

In this example, the modify() method is used to replace the value of a specific node in the XML data stored in the XMLCol column. The XPath expression is '/Root/Node[@Attr="Value"]/text()', which selects the text value of the node. The value is replaced with the string "NewValue". The WHERE clause limits the update to the row with an ID value of 1.

In conclusion, SQL Server XML query() method is a powerful tool that enables developers to work with XML data in a native way within a SQL Server database. It allows for the extraction of data from an XML document based on specific XPath expressions, and it can also be used to modify XML data within an XML column.