I have some problems using the exist() and value() methods in SQL Server 2008.
My XML looks like this:
<?xml version="1.0" encoding="UTF-8"?> <library> <branches> <branch> <codelib>1</codelib> <name>Campus</name> </branch> <branch> <codelib>2</codelib> <name>47th</name> </branch> <branch> <codelib>3</codelib> <name>Mall</name> </branch> </branches> <books> <book type="SF"> <codb>11</codb> <title>Robots</title> <authors> <author>author1 robots</author> <author>author2 robots</author> </authors> <price>10</price> <stocks> <branch codelib="1" amount="10"/> <branch codelib="2" amount="5"/> <branch codelib="4" amount="15"/> </stocks> <from>20</from> <to>30</to> </book> <book type="poetry"> <codb>12</codb> <title>Poetry book</title> <authors> <author>AuthorPoetry</author> </authors> <price>14</price> <stocks> <branch codelib="1" amount="7"/> <branch codelib="2" amount="5"/> </stocks> <from>25</from> <to>40</to> </book> <book type="children"> <codb>19</codb> <title>Faitytales</title> <authors> <author>AuthorChildren</author> </authors> <price>20</price> <stocks> <branch codelib="1" amount="10"/> <branch codelib="3" amount="55"/> <branch codelib="4" amount="15"/> </stocks> <from>70</from> <to>75</to> </book> <book type="literature"> <codb>19</codb> <title>T</title> <authors> <author>A</author> </authors> <price>17</price> <stocks> <branch codelib="1" amount="40"/> </stocks> <from>85</from> <to>110</to> </book> </books> </library> Given this XML, I have to write a SELECT clause that will use query(), value() and exist() 2 times each, minimum. I can't even use query() and exist() in the same SELECT, as it appears that the WHERE clause has no effect whatsoever.
For example, I want to retrieve all the <branch> elements that are children of the book with the type SF, but the select statement
declare @genre varchar(15) set @genre = 'SF' SELECT XMLData.query('//branch') from TableA WHERE XMLData.exist('//book[./@type = sql:variable("@genre")]') = 1 retrieves all the <branch> elements, not just the ones from the targeted book. I can't figure out what's wrong with my select. Also, I would appreciate a small example with query(), exist() and value() in the same select (is it possible to have nested select statements in sql xml?)