【问题标题】:Postgis: create column with srid in procedurePostgis:在过程中使用 srid 创建列
【发布时间】:2022-01-05 17:12:46
【问题描述】:

你好,

我想知道如何使用从数据库中检索到的 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);

【问题讨论】:

    标签: postgresql postgis plpgsql alter-table generated-columns


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 非常好,谢谢
    猜你喜欢
    • 2016-11-05
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多