PLPGSQL Function to Calculate Bearing

爱⌒轻易说出口 提交于 2019-12-02 07:01:14

In PL/pgSQL it's most effective to do as much as is elegantly possible in basic SQL queries at once. You can largely simplify.

I didn't get a definition of the sort order out of your question and left ??? to fill in for you:

CREATE OR REPLACE FUNCTION get_bearings_from_points(_bgeom geometry)
  RETURNS TABLE (x numeric, y numeric, z numeric, bearing numeric) AS
$func$
BEGIN
   FOR x, y, z, bearing IN
      SELECT ST_X(t.wgs_geom), ST_Y(t.wgs_geom), ST_Z(t.wgs_geom)
           , ST_Azimuth(t.wgs_geom, lead(t.wgs_geom) OVER (ORDER BY ???))
      FROM   points_table t
      WHERE  ST_Within(t.local_geom, _bgeom)
      ORDER  BY ???
   LOOP
      RETURN NEXT;
   END LOOP;
END
$func$ LANGUAGE plpgsql;

The window function lead() references a column from the next row according to sort order.

This can be simplified further to a single SQL query - possibly wrapped into an SQL function:

CREATE OR REPLACE FUNCTION get_bearings_from_points(_bgeom geometry)
  RETURNS TABLE (x numeric, y numeric, z numeric, bearing numeric) AS
$func$
   SELECT ST_X(t.wgs_geom), ST_Y(t.wgs_geom), ST_Z(t.wgs_geom)
        , ST_Azimuth(t.wgs_geom, lead(t.wgs_geom) OVER (ORDER BY ???))
   FROM   points_table t
   WHERE  ST_Within(t.local_geom, $1)  -- use numbers in pg 9.1 or older
   ORDER  BY ???
$func$ LANGUAGE sql;

Parameter names can be referenced in pg 9.2 or later. Per release notes of pg 9.2:

Allow SQL-language functions to reference parameters by name (Matthew Draper)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!