SQL Server-查询附近的酒店
问题描述
根据手机上已知的客户经纬度坐标,查询5公里范围内的酒店。
在《酒店信息表》中有经度和纬度两个字段存储酒店坐标,计算客户坐标与酒店坐标之间的距离,返回5公里内的所有酒店信息。
代码实现
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 32 33 34 35 36 37 38 39 | 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 |
本文作者:khrushchefox
本文链接:https://www.cnblogs.com/khrushchefox/p/16324118.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步