Quiz: SQL Server 2005 XML ‘exist’ method

Among the features introduced in SQL Server 2005 is the new XML Datatype.  You can use this guy to store both untyped and typed XML information and maintain the infoset fidelity of the document.  We support a subset of the XQuery language which can be used to retrieve values from XML instances and reshape documents, amongst other things.  One particularly useful, although sometimes confusing, piece of functionality is the “exist” method.  The semantics are that if the XQuery statement evaluates to a node, then it returns true, if it evaluates to the empty set, then it returns false.  It is invoked like this:

declare @x xml
set @x = ‘<Person><Name>John</Name><Age>24</Age></Person>’
select @x.exist(‘/Person/Name[.=”John”]’)

The result of this query is the boolean (bit in T-SQL) value ‘1’ indicating that there does exist a “/Person/Name” node with value “John”. 

Ok, so now that you know that, what’s wrong with this query?  (Update: The intention is to get the customer_info for any customer named “John”.)

create table customers (
customer_id int primary key identity(1,1),
customer_info xml
select customer_info
from customers
where customer_info.exist(‘/Customer/Name = “John”‘) = 1
I’ll let you think about a bit and post back next week with what is wrong, why it is wrong, and how to correct it.

Comments (4)

  1. theCoach says:

    Wouldn’t this get back all customer_info (the where condition is not specific to a particular customer_info, but to the existence of any customer_info)?

  2. I think the SELECT statement will always return all the rows in the customers table. The expression /Customer/Name = "John" will return true or false and hence a nonempty result, in which cases the exist method would return 1. So far each row, exist would return 1; and so 1 = 1 matches for all rows and the SELECT statement will return all the rows in the table. The correct syntax would be the way you have in the first example with the @x variable and condition in square brackets.

  3. Last week I threw out a quick quiz about the XML datatypes ‘exist’ method.&amp;nbsp; The reason it was at…

  4. theCoach says:

    Although I am embarassed by my quick post, I like this problem. good one.