Monday, March 19, 2012

Advanced SELECT for a newbie

I have a table full of Latitudes, Longitudes, address, customername, etc. , I need to grab some input(Latitude, Longitude, range) from the user. So now I have a source lat, long(user) and destination lat, long(rows in dbase). I need to take the 2 points and compute a distance from the user given lat, long to every lat, long in the database and check that distance againt the range given from the user. If the distance is below the range, I need to put that row into a temp table and return the temp table at the end of the stored proc.

As of right now I am completely lost and need some guidance.

I would also like to be able to add the computed distance to a table. Here is the function and stored procedure i have so far...

ALTER PROCEDURE [dbo].[sp_getDistance]

@.srcLat numeric(18,6),
@.srcLong numeric(18,6),
@.range int
AS
BEGIN
SET NOCOUNT ON;

SELECT * FROM dbo.PL_CustomerGeoCode cg
WHERE dbo.fn_computeDistance(@.srcLat, cg.geocodeLat, @.srcLong, cg.geocodeLong) < @.range

END

CREATE FUNCTION fn_computeDistance
(
-- Add the parameters for the function here
@.lat1 numeric(18,6),
@.lat2 numeric(18,6),
@.long1 numeric(18,6),
@.long2 numeric(18,6)
)
RETURNS numeric(18,6)
AS
BEGIN
-- Declare the return variable here
DECLARE @.dist numeric(18,6)

IF ((@.lat1 = @.lat2) AND (@.long1 = @.long2))
SELECT @.dist = 0.0
ELSE
IF (((sin(@.lat1)*sin(@.lat2))+(cos(@.lat1)*cos(@.lat2)*cos(@.long1-@.long2)))) > 1.0
SELECT @.dist = 3963.1*acos(1.0)
ELSE
SELECT @.dist = 3963.1*acos((sin(@.lat1)*sin(@.lat2))+(cos(@.lat1)*cos(@.lat2)*cos(@.long1-@.long2)))

-- Return the result of the function
RETURN @.dist

Thanks,

Kyle

What's the problem you're facing? If you want to add a computed column for the distance to the table, you can use something like:

ALTER TABLE dbo.PL_CustomerGeoCode ADD ComputedDistance AS dbo.fn_computeDistance(@.srcLat, cg.geocodeLat, @.srcLong, cg.geocodeLong)

No comments:

Post a Comment