Table 作为 PostgreSQL 参数的名称 - 使用 %I 的语法错误

Table name as a PostgreSQL Parameter - syntax error using %I

我有一个(相当长的) 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:

上收到语法错误

函数:

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');

您忽略了用于格式化字符串的 format 函数。

%I 是 format 函数的参数,在这里您只是试图执行一个恰好包含 %I 的文字字符串。

EXECUTE format('UPDATE tbl SET %I =  WHERE key = ', colname)
    USING newvalue, keyvalue;

在这里,您可以看到 colnameformat 函数的参数,而 newvaluekeyvalue 是结果 SQL 查询的参数.

因此,使用适当的参数将您的字符串包装在 format 函数中,您就可以开始了。