简体   繁体   English

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

[英]Postgis: create column with srid in procedure

Hello,你好,

I wonder how I could create a spatialized column with an srid retrieved from the db.我想知道如何使用从数据库中检索到的 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 $$;

Last solution doesn't work with generated columns.最后一个解决方案不适用于生成的列。 Ex:前任:

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

You can use format() to create your DDL dynamically.您可以使用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 $$;

You can also skip the variable declaration by passing the query itself as parameter:您还可以通过将查询本身作为参数传递来跳过变量声明:

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

And

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 $$;
  • This code assumes that project_options has a single row此代码假定project_options有单行

Demo: db<>fiddle演示: db<>fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM