this is my first time posting a question and I hope not to waste any of your time. Thanks in advance for any help.
I am attempting to calculate the distance between every zip-code in the United States and a list of 495 buildings (384 unique). I already have the latitude/longitude and an approximation for the distance. My problem comes in the form of not being sure how to update the rows in the table individually. For instance, the set function I use will change all the rows in the table to the most recently calculated value. I am using Sql Server 2008 R2, and have the following tables with the following columns: tbl_Zip_Code_Coordinates w/ Zip, Lat, Long, State, Closest_Building, Zip_ID; Tbl_Building_Coordinates w/ Zip, Lat, Long, Store_ID
Here is the code I am currently attempting
Declare @ZipID int = 1
DECLARE @ZipLat Decimal (12,6)
DECLARE @ZipLong Decimal (12,6)
while (@ZipID < 43194)
Begin
Set @ZipLat = (Select Lat from Zip_Code_Coordinates where Zip_ID = @ZipID)
Set @ZipLong= (Select Long from Zip_Code_Coordinates where Zip_ID = @ZipID)
Update Zip_Code_Coordinates
set Closest_Building = (select min(Sqrt( SQUARE((@ZipLat - Buildings_Coordinates.lat)*68.96799738887665)
+SQUARE((@ZipLong - Buildings_Coordinates.Long)*54.69366983621222)))
from Buildings_Coordinates, Zip_Code_Coordinates
where Zip_ID = @ZipID
)
set @ZipID = @ZipID + 1
end
I suppose you also need the ID for the closest building. If so, you could use the following code as is or with some modifications: