开发者

Query to return the rows that are within a certain geographic distance to a given row (using sql server 2008)

I have a table with multiple records, each contains a field called "coords". This field has been updated with a geography point.

UPDATE testing SET [coords] = geography::Point(52.029736, -113.973541, 4326)
WHERE id=2"

What I need to do is... when a user is logged in, they have a record that belongs to them, for this example says its record id #1. They need to visit a page that shows all the other records who's "coords" field is located within a certain distance.

This is the best I have come up with;

1stly, i can find the starting coordinated with this statement;

SELECT coords FROM testing WHERE id=1

This gives me the originating coordinate as coords.Lat and coords.Long

Then I would like to find ones close by, so I have this;

SELECT * FROM testing WHERE coords.STDistance() <=(20 * 1609.344)

I do not know how to put the originating coords, into that second statement to make it work.

Do I need a stored procedure, or can I somehow put the coords.Lat/ coords.Long inside the brackets of the STDistance? Or am I tottaly off base on how I'm expecting this to work.

FYI, I have very little experience with sql server, I've never don开发者_运维知识库e anything "advanced", only simple select * from table where record = 1 and basic inserts and updates.


would this work ?

SELECT
    [near].* 
FROM 
    testing [near]
INNER JOIN
    testing [user] ON
    [user].coords.STDistance( [near].coords ) < (20 * 1609.344)
WHERE
    [user].id = 1


How about this?:

 DECLARE @g geography;
 SELECT @g = coords FROM testing WHERE id=1;        
 SELECT * FROM testing WHERE coords.STDistance(@g) <=(20 * 1609.344)


I solved it myself with 2 selects and 2 variables... Any suggestions to make it better?

sql1 = "SELECT coords.Lat, coords.Long FROM testing WHERE id=1"
lat2 = rs(0)
lon2 = rs(1)
sql2 = "SELECT * FROM testing WHERE id <> 1 AND coords.STDistance(geography::Point(" & lat2 & ", " & lon2 & ", 4326)) <=(20 * 1609.344)"
'20 miles or less
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜