Rex Applegate
Rex Applegate

Reputation: 37

How to compare between two numbers (twice) and return a string in XQuery

I have a pub database and I need to compare two numbers (latitude) and two more (longitude), and return every pub name that is located between those coordinates.

I tried a where clause using both logical and arithmetic operators, tried with one variable and two variables.

Output is always the same all pubs, regardless the coordinates.

for $x in db:open("pub", "pub.xml")/serviceList/service
where $x/geoData/latitude='40.400000000000' and $x/geoData/latitude='40.410000000000'
return $x/basicData/name

The idea is to loop the database find all the pubs whose coordinates are between 40.40 and 40.41 (latitude) and -3.7 i -3.71 (longitude) and return the name.

Upvotes: 1

Views: 797

Answers (2)

Mads Hansen
Mads Hansen

Reputation: 66783

You are currently testing whether the latitude value is equal to two different strings with and criteria (it will never match both values unless there are more than one latitude elements, but you haven't shown an example of the XML)

You probably want to compare those latitude and longitude values as numbers (remove the quotes from your values)

for $x in db:open("pub", "pub.xml")/serviceList/service
where (
  $x/geoData/latitude >= 40.4 and $x/geoData/latitude <= 40.41
  and 
  $x/geoData/longitude >= -3.7 and $x/geoData/latitude <= 3.7
)
return $x/basicData/name

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163458

The solution from Mads Hansen can be abbreviated to:

for $x in db:open("pub", "pub.xml")/serviceList/service
where (
  $x/geoData/latitude[. ge 40.4 and . le 40.41]
  and 
  $x/geoData/longitude[. ge -3.7 and . le 3.7]
)
return $x/basicData/name

or even further to

db:open("pub", "pub.xml")/serviceList/service
    [geoData[latitude[. ge 40.4 and . le 40.41] and longitude[. ge -3.7 and . le 3.7]]
    /basicData/name

Upvotes: 1

Related Questions