TL; DR您「做錯了」兩件事:returns integer
應該是returns float
並且最後select ..
應該是return ..
。
詳情:
RETURN
從PL/pgSQL函數返回一個值 - 你需要使用它,而不是最後SELECT
。並且st_distance(..)
根據http://postgis.refractions.net/docs/ST_Distance.html返回float
值,因此您需要在您的第一行中使用returns float
。
試試這個:
CREATE OR REPLACE FUNCTION calc_distance_for_cities(fromCityId bigint, toCityId bigint) RETURNS float LANGUAGE plpgsql as $$
DECLARE
fromCityCoords Geometry;
toCityCoords Geometry;
BEGIN
SELECT coords INTO fromCityCoords FROM geo_cities WHERE geo_cities.id = fromCityId;
SELECT coords INTO toCityCoords FROM geo_cities WHERE geo_cities.id = toCityId;
RETURN ST_Distance(fromCityCoords, toCityCoords, true);
END;
$$;
而且,這個功能其實並不需要PL/pgSQL的語言,可以輕鬆地在普通的SQL實現,與CTE(https://www.postgresql.org/docs/current/static/queries-with.html):
create or replace function calc_distance_for_cities(int8, int8) returns float as $$
with _from(city_coords) as (
select coords from geo_cities where geo_cities.id = $1
), _to(city_coords) as (
select coords from geo_cities where geo_cities.id = $2
)
select st_distance(_from.city_coords, _to.city_coords)
from _from, _to;
$$ language sql;
或者甚至沒有CTE:
create or replace function calc_distance_for_cities(int8, int8) returns float as $$
select st_distance(
(select coords from geo_cities where geo_cities.id = $1),
(select coords from geo_cities where geo_cities.id = $2)
);
$$ language sql;