t-SQL:使用变量过滤结果集

时间:2017-03-21 14:25:51

标签: sql sql-server sql-server-2008 tsql geolocation

请原谅我的天真。

我有一个查询,可以让你找到球体上两点之间的距离,在这种情况下,是邮政编码之间的距离。

SELECT  TOP 5 zip, city, state, latitude, longitude,
    69.0 * DEGREES(ACOS(COS(RADIANS(latpoint))
            * COS(RADIANS(latitude))
            * COS(RADIANS(longpoint) - RADIANS(longitude))
            + SIN(RADIANS(latpoint))
            * SIN(RADIANS(latitude)))) AS distance_in_miles
FROM    us_loc_data
JOIN    (
         SELECT 39.317974 AS latpoint, -94.57545 AS longpoint 
        ) AS p ON 1=1
ORDER BY distance_in_miles

正如您从连接中看到的那样,通过将一对坐标指定为"开始"来过滤结果集。点,然后返回前5个最近位置的列表。 (以下示例)

enter image description here

最后,我想通过指定一个起始邮政编码而不是一对坐标来过滤结果。如何实现变量?什么是最佳做法?

1 个答案:

答案 0 :(得分:2)

未经测试,但您只需更改子查询即可通过邮政编码拉取Lat / Lng。

Declare @Zip varchar(10) = '02806'

SELECT  TOP 5 zip, city, state, latitude, longitude,
    69.0 * DEGREES(ACOS(COS(RADIANS(latpoint))
            * COS(RADIANS(latitude))
            * COS(RADIANS(longpoint) - RADIANS(longitude))
            + SIN(RADIANS(latpoint))
            * SIN(RADIANS(latitude)))) AS distance_in_miles
FROM    us_loc_data
JOIN    (
         SELECT latitude AS latpoint
              , longitude AS longpoint 
          From  us_loc_data 
          Where Zip = @Zip
        ) AS p ON 1=1
ORDER BY distance_in_miles