T-SQL Tutorial

SQL Server XML exist()


In SQL Server, the exist() method is a powerful function used to test if a particular node or attribute exists in an XML document stored in an XML column or variable. This function returns a Boolean value (True or False) indicating whether the specified node or attribute exists in the XML document.


Syntax

The syntax of the exist() method is as follows:

exist(xpath_expression as xml)

The xpath_expression parameter is an XPath expression that defines the node or attribute to be searched for in the XML document.


Example

Here is an example of how to use the exist() method to search for a specific node in an XML document:

DECLARE @xml XML = '
<employees>
<employee><name>John</name><age>30</age></employee>
<employee><name>Sara</name><age>25</age></employee>
</employees>'

SELECT @xml.exist('/employees/employee[name="John"]');

In this example, we have an XML document that contains information about employees. We want to check whether there is an employee node with a name node value of "John". The exist() method returns a value of 1, which means that the node exists.

The exist() method is often used in conjunction with the value() method to retrieve data from XML documents. Here's an example:

DECLARE @xml XML = '
<employees>
<employee><name>John</name><age>30</age></employee>
<employee><name>Sara</name><age>25</age></employee>
</employees>'

SELECT @xml.value('(/employees/employee[name="John"]/age)[1]', 'int');

In this example, we retrieve the age value of the employee node with a name node value of "John". The exist() method is used to check whether this node exists, and the value() method is used to retrieve the age value.

In conclusion, the exist() method is a useful function in SQL Server for searching XML documents stored in XML columns or variables. It allows you to easily determine whether a specific node or attribute exists in the XML document.