我有一个(相当冗长的)select query我需要在未知名称的表上运行才能返回另一个表。有没有办法使用dynamic commands执行此操作?
我在%I
上一直收到语法错误:
功能:
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;
查询:
SELECT angles('poly_and_multipoly');
答案 0 :(得分:3)
您忽略了format
函数来格式化字符串。
%我是format
函数的参数,在这里你只是试图执行碰巧有%I的文字字符串。
EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
USING newvalue, keyvalue;
在这里,您可以看到colname
是format
函数的参数,而newvalue
和keyvalue
是结果SQL查询的参数。
因此,使用正确的参数将您的字符串包装在format
函数中,您应该很高兴。