Question : Ideas on making this Query less CPU intensive?

SELECT  @lat1= latitude,
        @long1 = longitude
FROM ZipCodes
WHERE zipcodes = @ZipCode

SELECT ZipCodes ,DistanceInMiles
FROM
(
 SELECT  ZipCodes,3958.75 * ( Atan(Sqrt(1 - power(((Sin(@Lat1/57.2958) * Sin(latitude/57.2958)) +
    (Cos(@Lat1/57.2958) * Cos(latitude/57.2958) * Cos((longitude/57.2958) - (@Long1/57.2958)))), 2)) /
    ((Sin(@Lat1/57.2958) * Sin(latitude/57.2958)) + (Cos(@Lat1/57.2958) * Cos(latitude/57.2958) *
    Cos((longitude/57.2958) - (@Long1/57.2958)))))) DistanceInMiles
 FROM ZipCodes
) a
WHERE a.DistanceInMiles <= @GivenMileRadius
--AND ZipCodes <> @ZipCode
ORDER BY DistanceInMiles

I put this as a stored procedure on my SQL server 2008, and it works.
The problem is all that trig bogs down the CPU like mad.  Is there a quicker non-cpu intensive way someone can think of to do this?  Maybe create new columns with some pre-calculated values that would speed up searches?   The canadian side of the zip codes has over 700,000 entries (canada has a ton of zip codes!)  Is there a "less trig" version of this?  I don't need pinpoint accuracy.  Also, The max radius will always be 50 miles.

Answer : Ideas on making this Query less CPU intensive?

I'm not sure there would be much difference in execution time, but I am a big fan of Scalar functions in a situation like this.

The scalar function would encapsulate the math your are performing.  You could do something like this.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
CREATE FUNCTION [dbo].[udf_CalculateDistance] 
	(@Lat1 decimal(9,4), @Long1 decimal(9,4), @latitude decimal(9,4), @longitude decimal(9,4))
RETURNS decimal(9,4)
AS
	BEGIN
		DECLARE @Result decimal(9,4)
		SET @Result = (3958.75 * ( Atan(Sqrt(1 - power(((Sin(@Lat1/57.2958) * Sin(@latitude/57.2958)) +
    (Cos(@Lat1/57.2958) * Cos(@latitude/57.2958) * Cos((@longitude/57.2958) - (@Long1/57.2958)))), 2)) /
    ((Sin(@Lat1/57.2958) * Sin(@latitude/57.2958)) + (Cos(@Lat1/57.2958) * Cos(@latitude/57.2958) *
    Cos((@longitude/57.2958) - (@Long1/57.2958))))))

      Return @result
	END



//then in your stored proc


SELECT  @lat1= latitude,
        @long1 = longitude
FROM ZipCodes
WHERE zipcodes = @ZipCode

SELECT 
   ZipCodes ,
   dbo.udf_CalculateDistance(@lat1,@long1,a.latitude,a.longitude) as [DistanceInMiles]
FROM ZipCodes as a
WHERE a.DistanceInMiles <= @GivenMileRadius
--AND ZipCodes <> @ZipCode
ORDER BY DistanceInMiles
Random Solutions  
 
programming4us programming4us