SQL Server-查询附近的酒店
问题描述
根据手机上已知的客户经纬度坐标,查询5公里范围内的酒店。
在《酒店信息表》中有经度和纬度两个字段存储酒店坐标,计算客户坐标与酒店坐标之间的距离,返回5公里内的所有酒店信息。
代码实现
create function fnGetDistance (@LatBegin real, @LngBegin real, @LatEnd real, @LngEnd real)
returns float
as
begin
declare @del_lat float, @del_lng float, @factor float, @distance float
select @factor = pi()/180 -- 将角度转换为弧度,不清楚数据的格式,或许不需要转换
select @del_lat = @LatEnd - @LatBegin -- 两点间纬度差
select @del_lng = @LngEnd - @LngBegin -- 两点间经度差
select @distance = 6378.137*2*asin(sqrt(square(sin(@del_lat*@factor/2))+cos(@LatBegin*@factor)*cos(@LatEnd*@factor)*square(sin(@del_lng*@factor/2))))
-- 半正矢公式,单位为km
return(@distance)
end
go
declare @Lat0 real, @Lng0 real, @Lat1 real, @Lng1 real, @distance float, @i float
select @Lat0 = 30
select @Lng0 = 114 --起点经纬度
select @i = 0
declare Cursor_hotel cursor
for select Latitude, Longitude from Hotel
open Cursor_hotel
fetch next from Cursor_hotel
into @Lat1, @Lng1
while @@fetch_status = 0
begin
exec @distance = fnGetDistance @Lat0, @Lng0, @Lat1, @Lng1
if @distance <= 5
begin
@i = @i +1
print '找到第'+ltrim(str(@i))+'个5公里内酒店的纬度和经度为:'+str(@Lat1)+' , '+str(@Lng1)
end
fetch next from Cursor_hotel
into @Lat1, @Lng1
end
if @i = 0
print '很抱歉,没有找到5公里内的酒店!'
close Cursor_hotel
deallocate Cursor_hotel
go

浙公网安备 33010602011771号