SQL Server XQuery Introduction


The website w3schools.com says: “XQuery is to XML what SQL is to databases. XQuery is designed to query XML data”.

XQuery is about working with XML Variables. You can easily define one just by declaring it with the XML data type as you can see below. In the example below we have simple typed the XML into our sql code (or perhaps in our stored procedure).

This post is part of a series:

  1. query() – Introduction
  2. exist() – Part 2
  3. – Part 3
  4. modify(‘insert sql:variable(“@xml”)…) – Part 4
  5. modify(‘insert sql:variable(“@xml”)…) – Part 5
  6. modify(‘replace value of… – Part 6
  7. modify(‘replace value of… with(if… – Part 7

The query() Method Against an XML Type Variable

DECLARE @XML XML
SET @XML = 
'<root>
  <row1>
    <value>1</value>
  </row1>
  <row2>
    <value>2</value>
  </row2>
</root>
';
DECLARE @rowsselected int;
SELECT @XML.query('/root/row1')

Here is the result.

<row1>
  <value>1</value>
</row1>

Here is another example. Here is the new xml we are working with.

<root>
  <row1>
    <value>1</value>
  </row1>
  <row2>
    <value>2</value>
	<amount>2</amount>
  </row2>
</root>

Here is the T-SQL code.

SELECT @XML.query('/root/row2/amount')

Here is the result.

<amount>2</amount>
Series NavigationSQL Server XQuery Part 2 >>

Leave a comment

Your email address will not be published. Required fields are marked *