Tuesday 8 October 2013

Lat Long points within a radius in SQL Server

--Create a temp table with some random points for testing purposes
create table #Points(
 id int identity(1,1) not null,
 x decimal(10,5),
 y decimal(10,5))

declare @count int = 0
while @count < 20
begin
 insert into #Points(x,y)
  values (rand()*100.0 - 50.0,
  RAND()*100.0 - 50.0)
 set @count = @count + 1
end

declare @locX decimal(10,5) = 0.0
declare @locY decimal(10,5) = 0.0
declare @radius decimal(10,5) = 15.0

--SELECT Points closer than @radius
select * from #Points p
WHERE power(p.x - @locX, 2) + POWER(p.y - @locY, 2) < POWER(@radius,2)

--SELECT Points and show their distance from origin (@locX, @locY)
select p.*, POWER(power(p.x - @locX, 2) + POWER(p.y - @locY, 2), 0.5)
from #Points p

No comments:

Post a Comment