It seems like its all about location this week. This is a fantastic bit of code that I keep on using again and again... I often need to pull records out of a database ordered by proximity, i.e a SQL stored procedure like -
CREATE PROCEDURE [dbo].[Get_Data]@long_ float,@lat_ floatASBEGINSET NOCOUNT ON;
SELECT top 3 [Address ID], dbo.udfComputeDistance(@lat_,@long_,a.lat_,a.long_) as distance from Addresses as aorder by distancereturn 0END
This will return 3 records nearest to a location you specify in a table of addresses that has the long and lats stored against each one. So the magic all happens in a SQL function called udfComputeDistance
CREATE FUNCTION [dbo].[udfComputeDistance](@lat1 float,@lon1 float,@lat2 float,@lon2 float)RETURNS floatASbegin-- dLong represents the differences in longitudes-- while dLat is the difference in latitudesdeclare @dLong floatdeclare @dLat float-- To keep the calculation easier to understand,-- we have simplified it by computing it by parts.-- This value temporarily holds the value of the-- first calculation.declare @temp float-- Convert the decimal degrees to radiansset @lat2 = radians(@lat2)set @lon1 = radians(@lon1)set @lat1 = radians(@lat1)set @lon2 = radians(@lon2)-- Compute the degree differencesset @dLong = @lon2 - @lon1set @dLat = @lat1 - @lat2-- Compute the first part of the equationset @temp = (square(sin(@dLat/2.0))) + cos(@lat2) * cos(@lat1) * (square(sin(@dLong/2.0)))-- Return the approximate distance in miles-- Note that 3956 is the approximate median radius of the Earth.return (2.0 * atn2(sqrt(@temp), sqrt(1.0-@temp)))*3956.0end
Now I'm not going to take credit for this brilliant function. It has come from Kent Tegels of SQL Junkies fame -
http://sqljunkies.com/Tutorial/21DC68CD-1A97-4909-8157-523CA249CC80.scuk
Needless to say, it just does the job. I use it all the time.
Theme design by Jelle Druyts
Pick a theme: BlogXP calmBlue
My Virtual Earth Balloon Races www.racingballoon.com Richard JonesPowered By The Fridge Server