I have a (rather lengthy) select query that I need to run on tables of unknown names to return another table. Is there a way to do this using dynamic commands?
I keep getting a syntax error on %I
:
Function:
CREATE OR REPLACE FUNCTION angles(table_name TEXT)
RETURNS TABLE (id int, name varchar, polygon_num int, point_order int) AS
$BODY$
BEGIN
RETURN QUERY EXECUTE 'select id,
name,
polygon_num,
point_order as vertex,
--
case when point_order = 1
then last_value(ST_Astext(ST_Makeline(sp,ep))) over (partition by id, polygon_num)
else lag(ST_Astext(ST_Makeline(sp,ep)),1) over (partition by id, polygon_num order by point_order)
end ||' - '||ST_Astext(ST_Makeline(sp,ep)) as lines,
--
abs(abs(
case when point_order = 1
then last_value(degrees(ST_Azimuth(sp,ep))) over (partition by id, polygon_num)
else lag(degrees(ST_Azimuth(sp,ep)),1) over (partition by id, polygon_num order by point_order)
end - degrees(ST_Azimuth(sp,ep))) -180 ) as ang
from (-- 2.- extract the endpoints for every 2-point line segment for each linestring
-- Group polygons from multipolygon
select id,
name,
coalesce(path[1],0) as polygon_num,
generate_series(1, ST_Npoints(geom)-1) as point_order,
ST_Pointn(geom, generate_series(1, ST_Npoints(geom)-1)) as sp,
ST_Pointn(geom, generate_series(2, ST_Npoints(geom) )) as ep
from ( -- 1.- Extract the individual linestrings and the Polygon number for later identification
select id,
name,
(ST_Dump(ST_Boundary(the_geom))).geom as geom,
(ST_Dump(ST_Boundary(the_geom))).path as path -- To identify the polygon
from %I ) as pointlist ) as segments';
END;
$BODY$
LANGUAGE plpgsql;
Query:
SELECT angles('poly_and_multipoly');