Postgis:在过程中使用 srid 创建列

Postgis: create column with srid in procedure

您好,

我想知道如何使用从数据库中检索到的 srid 创建空间化列。

-- OK --
ALTER TABLE POI ADD COORDS GEOMETRY(POINT, 26916);

-- KO (invalid input syntax for type integer: "sridval") --
DO $$
DECLARE
    sridval int;
BEGIN
    sridval := (select srid FROM project_options);
    ALTER TABLE POI ADD COORDS GEOMETRY(POINT, sridval);
END$$;

-- OK but verbose --
DO $$
DECLARE
    sridval int;
BEGIN
    ALTER TABLE POI ADD COORDS GEOMETRY(POINT);
    sridval := (select srid FROM project_options);
    PERFORM updategeometrysrid('POI', 'coords', sridval);
END $$;

最后一个解决方案不适用于生成的列。例如:

ALTER TABLE POI ADD COORDS GEOMETRY(POINT, /*put srid here?*/) generated always as (ST_MakePoint(longitude, latitude)) stored;
CREATE INDEX COORDS_IDX ON POI USING GIST (COORDS);

您可以使用 format() 动态创建 DDL。

DO $$
DECLARE
    sridval int;
BEGIN
 sridval := (SELECT srid FROM project_options); 
 EXECUTE FORMAT('ALTER TABLE poi ADD COLUMN coords geometry(point, %s)',sridval);
END $$;

您也可以通过将查询本身作为参数传递来跳过变量声明:

DO $$
BEGIN
  EXECUTE FORMAT('ALTER TABLE poi ADD coords geometry(point, %s)',
                 (SELECT srid FROM project_options));
END $$;

DO $$
BEGIN
 EXECUTE FORMAT('ALTER TABLE poi ADD coords geometry(point, %s) 
                 GENERATED ALWAYS AS (ST_MakePoint(longitude, latitude)) STORED;',
                (SELECT srid FROM project_options));
END $$;
  • 此代码假定 project_options 有一行

演示:db<>fiddle